diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index f5f20b233d..7e3c9ccc69 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -3,11 +3,13 @@ # See https://github.com/DefinitelyTyped/DefinitelyTyped#edit-an-existing-package /types/a-big-triangle/ @MathiasPaumgarten +/types/a11y-dialog/ @Goyatuzo /types/abbrev/ @BendingBender /types/abs/ @AyaMorisawa /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 @@ -15,7 +17,7 @@ /types/ace-diff/ @innovation-team /types/acl/ @tkQubo /types/acorn/ @RReverser @e-cloud -/types/actioncable/ @zhu1230 +/types/actioncable/ @zhu1230 @szechyjs /types/actions-on-google/ @joelhegg /types/activedirectory2/ @pasthelod /types/activex-access/ @zspitz @@ -52,11 +54,14 @@ /types/aggregate-error/ @BendingBender /types/agora-rtc-sdk/ @menthays /types/ajv-errors/ @afshawnlotfi +/types/ale-url-parser/ @msn0 /types/alertify/ @jjeffery /types/alexa-sdk/ @petebeegle @hoo29 @pascalwhoop @blforce @rk-7 @alexmalcoci /types/alexa-voice-service/ @dolanmiu /types/algebra.js/ @CaselIT -/types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss +/types/algoliasearch/ @cbaptiste @haroenv @aherve @samouss @keichinger +/types/ali-app/ @taoqf +/types/ali-oss/ @ptrdu /types/allure-js-commons/ @zaqqaz /types/almost-equal/ @cmaddalozzo /types/alt/ @Shearerbeard @@ -68,7 +73,7 @@ /types/amphtml-validator/ @kevincharm /types/amplify/ @joeriks /types/amplify-deferred/ @joeriks @laurentiustamate94 -/types/amplitude-js/ @Asido +/types/amplitude-js/ @Asido @danmana /types/amqp/ @seikho @jonnysparkplugs /types/amqp-connection-manager/ @rogierschouten /types/amqp-rpc/ @wokim @@ -149,18 +154,20 @@ /types/animation-frame/ @qinfchen /types/animejs/ @A-Babin /types/annyang/ @hisham @theluk +/types/ansi/ @Gustavo6046 /types/ansi-colors/ @rogierschouten /types/ansi-escape-sequences/ @aomarks /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 /types/any-db-transaction/ @rogierschouten /types/anybar/ @khoomeister /types/anymatch/ @BendingBender +/types/aos/ @shermendev /types/apex.js/ @y13i /types/aphrodite/ @asvetliakov /types/api-error-handler/ @tkrotoff @@ -168,6 +175,8 @@ /types/apigee-access/ @CasperSkydt /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 @@ -195,18 +204,22 @@ /types/array-sort/ @DanielMSchmidt /types/array-uniq/ @DanielRosenwasser /types/array-unique/ @CSLTech +/types/array.prototype.flatmap/ @hallettj /types/arrify/ @wanganjun /types/artillery/ @kmccoan-allocadia /types/asana/ @tkqubo /types/asap/ @fpascutti +/types/ascii-art/ @lukaselmer /types/ascii2mathml/ @RagibHasin /types/asenv/ @remisery /types/asn1js/ @microshine /types/aspnet-identity-pw/ @jt000 +/types/assert/ @nicoabie @LinusU /types/assert-equal-jsx/ @seryl /types/assert-plus/ @KostyaTretyak /types/assertsharp/ @brunolm /types/assets-webpack-plugin/ @kryops +/types/astring/ @nkappler /types/async/ @borisyankov @kern0 @Penryn @fenying @pascalmartin /types/async-cache/ @BendingBender /types/async-lock/ @elisee @afharo @rhymmor @@ -214,11 +227,13 @@ /types/async-retry/ @albertywu @MeLlamoPablo /types/async.nexttick/ @pyrho /types/asynciterator/ @rubensworks +/types/athenajs/ @warpdesign /types/atlaskit__button/ @dijimsta /types/atlaskit__calendar/ @lstanden /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 @@ -227,7 +242,8 @@ /types/atom-mocha-test-runner/ @GlenCFL /types/atpl/ @soywiz /types/audiosprite/ @Perlmint -/types/auth0/ @wbhob @westy92 @amiram +/types/auth-header/ @ForbesLindesay +/types/auth0/ @westy92 /types/auth0-angular/ @homesar /types/auth0-js/v7/ @advancedrei /types/auth0-js/ @adrianchia @mdurrant @peterblazejewicz @@ -238,12 +254,13 @@ /types/auto-sni/ @janwo /types/autobahn/ @darkl @valepu /types/autolinker/ @leonyu -/types/autoprefixer/ @odnamrataizem +/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 +/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 /types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites /types/axe-webdriverjs/ @JoshuaKGoldberg @@ -266,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 @@ -288,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 @@ -301,10 +318,11 @@ /types/bases/ @harikv /types/bash-glob/ @mrmlnc /types/basic-auth/ @moonpyk @vesse +/types/basicauth-middleware/ @nchaulet /types/batch-stream/ @drudge /types/bazinga-translator/ @alexndlm /types/bcrypt/ @codeanimal @IOAyman @dstapleton92 -/types/bcryptjs/ @RafaelKr +/types/bcryptjs/ @RafaelKr @branoholy /types/bdfjs/ @jeremejevs /types/beats/ @urish /types/bech32/ @micksatana @@ -314,10 +332,10 @@ /types/bencode/ @tobenna /types/better-curry/ @pocesar /types/better-queue/ @maozedong -/types/better-scroll/ @stoneChen -/types/better-sqlite3/ @Morfent @matrumz +/types/better-scroll/ @stoneChen @cnjack +/types/better-sqlite3/ @Morfent @matrumz @sant123 /types/bezier-easing/ @ptlis -/types/bezier-js/ @danmarshall +/types/bezier-js/ @danmarshall @Epskampie /types/bgiframe/ @sumegizoltan /types/bidirectional-map/ @helenanderson /types/big.js/ @nycdotnet @googol @@ -326,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 @@ -338,9 +356,8 @@ /types/bitcoinjs-lib/ @mhegazy @dlebrecht @rbuckton @micksatana @youssefgh @kento1218 /types/bitcore-lib/ @lautarodragan /types/bittorrent-protocol/ @feross @tlaziuk -/types/bitwise/ @danwbyrne -/types/bitwise-xor/ @rogierschouten -/types/bl/ @Bartvds +/types/bitwise-xor/ @rogierschouten @BendingBender +/types/bl/ @Bartvds @reconbot /types/blacklist/ @mhegazy /types/blazy/ @julienpa /types/blessed/ @brynbellomy @skellock @@ -371,7 +388,7 @@ /types/boom/ @rogatty @AJamesPhillips @jineshshah36 @TimonVS @danielmachado /types/bootbox/ @vbortone @konpikwastaken @kanup @icereed @trodi @stannynuytkens @renjfk /types/bootpag/ @rdeneau -/types/bootstrap/v3/ @borisyankov +/types/bootstrap/v3/ @borisyankov @denisname /types/bootstrap/ @denisname /types/bootstrap-3-typeahead/ @AndersonFriaca /types/bootstrap-datepicker/ @borisyankov @@ -383,6 +400,7 @@ /types/bootstrap-slider/ @dbeckwith @leonard-thieu /types/bootstrap-switch/ @johnmbaughman /types/bootstrap-table/ @talatbaig +/types/bootstrap-toggle/ @gricey432 /types/bootstrap-touchspin/ @albinsunnanbo /types/bootstrap-treeview/ @jbtronics /types/bootstrap-validator/ @BradyLiles @@ -401,6 +419,7 @@ /types/breeze/ @borisyankov /types/bricks.js/ @kondi /types/bro-fs/ @ffflorian +/types/broccoli-plugin/ @dfreeman /types/brorand/ @chrootsu /types/browser-bunyan/ @PaulLockwood @kryops /types/browser-fingerprint/ @LKay @@ -409,7 +428,8 @@ /types/browser-report/ @JTOne123 /types/browser-resolve/ @marionebl /types/browser-sync/ @joeskeen @aznnomness -/types/browserify/ @AndrewGaspar @jvilk @leonard-thieu +/types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU +/types/browserslist/ @davecardwell /types/bs58/ @chrootsu /types/bson/ @horiuchi @CaselIT /types/btoa/ @johngeorgewright @@ -423,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 +/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 @@ -439,9 +459,12 @@ /types/byline/ @reppners /types/bytebuffer/ @cappellin /types/bytes/ @danny8002 @believer +/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 /types/callsites/ @BendingBender /types/calq/ @eirikhm @@ -450,6 +473,8 @@ /types/camelcase-keys/ @mhegazy /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 @@ -464,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 @@ -475,6 +502,7 @@ /types/chai-datetime/ @cliffburger @mattbishop /types/chai-dom/ @mattlewis92 /types/chai-enzyme/ @asvetliakov +/types/chai-fs/ @dimitardanailov /types/chai-fuzzy/ @Bartvds /types/chai-http/ @Nemo157 @G1itcher @CaselIT @bas-l /types/chai-jest-snapshot/ @mattvperry @@ -493,7 +521,7 @@ /types/chardet/ @Gebatzens /types/charm/ @Xananax /types/charset/ @cspotcode -/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @archy-bold @braincore @gebeto @frabnt @alexdor @mahnuh +/types/chart.js/ @anuti @FabienLavocat @KentarouTakeda @larrybahr @mernen @josefpaij @danmana @guillaume-ro-fr @archy-bold @braincore @frabnt @alexdor @mahnuh @Conrad777 /types/chartist/ @mtgibbs @psimonski @clottman @affilnost @sunnyrjuneja /types/chartmogul-node/ @chartmogul /types/chayns/ @HenningKuehl @@ -501,11 +529,12 @@ /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 /types/chokidar/ @reppners @felixfbecker @bayssmekanique +/types/chordsheetjs/ @adamsbloom /types/chosen-js/ @borisyankov @denisname /types/chownr/ @BendingBender /types/chroma-js/v0/ @invliD @@ -518,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 @@ -532,7 +562,9 @@ /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 /types/cli-spinner/ @janslow /types/cli-table/ @arylo @@ -558,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 @@ -573,26 +605,30 @@ /types/color-namer/ @in19farkt /types/color-string/ @BendingBender @danmarshall /types/colorbrewer/ @mtraynham +/types/colresizable/ @gilleswaeber /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 +/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 /types/command-line-usage/ @matrumz @Dvorsky /types/commangular/ @hiraash /types/comment-json/ @Jason3S +/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 +/types/complex/ @AyaMorisawa @pavasich /types/component-emitter/ @psnider /types/compose-function/ @denis-sokolov /types/compressible/ @BendingBender @@ -612,6 +648,7 @@ /types/confit/ @ethanresnick /types/connect/ @SomaticIT @EvanHahn /types/connect-busboy/ @pinguet62 +/types/connect-datadog/ @moshegood /types/connect-ensure-login/ @0x6368656174 /types/connect-flash/ @AndreasGassmann /types/connect-history-api-fallback/ @douglasduteil @@ -620,11 +657,13 @@ /types/connect-mongo/ @Syati /types/connect-mongodb-session/ @NattapongSiri /types/connect-pg-simple/ @pasieronen -/types/connect-redis/ @xstoudi @morcerf +/types/connect-redis/ @xstoudi /types/connect-slashes/ @samherrmann /types/connect-timeout/ @cyrilschumacher +/types/consola/ @Jungwoo-An /types/console-log-level/ @ofrobots /types/console-stamp/ @ericbyers @guusdegraeve +/types/console-ui/ @dfreeman /types/consolidate/ @soywiz @theosherry @nicolashenry /types/consul/ @chrootsu /types/content-disposition/ @bomret @@ -636,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 @@ -651,6 +690,7 @@ /types/cordova-plugin-background-mode/ @Lordnoname /types/cordova-plugin-badge/ @timbru31 /types/cordova-plugin-ble-central/ @gjunge +/types/cordova-plugin-bluetoothclassic-serial/ @tuvokki /types/cordova-plugin-canvascamera/ @lordazzi /types/cordova-plugin-device-name/ @larrybahr /types/cordova-plugin-file-opener2/ @cyrilgandon @@ -669,17 +709,20 @@ /types/cordova_app_version_plugin/ @larrybahr /types/cordovarduino/ @hendrikmaus /types/core-js/ @rbuckton @mfdeveloper +/types/core-object/ @dfreeman /types/correlation-id/ @natemara /types/cors/ @pluma /types/cosmiconfig/v4/ @ozum /types/cosmiconfig/ @ozum @szeck87 @saadq @jinwoo -/types/cote/ @makepost +/types/cote/ @makepost @roblabat /types/couchbase/ @maouida @fluggo /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 /types/cp-file/ @BendingBender /types/cpx/ @alan-agius4 @@ -688,32 +731,40 @@ /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 /types/createjs-lib/ @evilangelist @gyohk /types/credential/ @phuvo /types/credit-card-type/ @LKay +/types/critters-webpack-plugin/ @JuanJoseGonGi /types/cron/ @horiuchi @winup /types/cropperjs/ @stepancar /types/croppie/ @connor4312 @dklmuc @sarunint @knuthelgesen /types/cross-spawn/ @Alorel /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 @@ -725,15 +776,16 @@ /types/cucumber/ @abraaoalves @jan-molak @isoung @BendingBender @ErikSchierboom /types/currency-formatter/ @mhegazy @davidmpaz /types/custom-error-generator/ @thmiceli +/types/custom-functions-runtime/ @OfficeDev @Zlatkovsky @mscharlock /types/cwise/ @taoqf /types/cwise-compiler/ @taoqf /types/cwise-parser/ @taoqf /types/cybozulabs-md5/ @pine613 /types/cytoscape/ @phreed @wy193777 @ypconstante @janniclas @cerberuser /types/d3/v3/ @gustavderdrache @borisyankov @MatthiasJobst -/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov -/types/d3/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-array/ @gustavderdrache @borisyankov @tomwanzek +/types/d3/v4/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3/ @tomwanzek @gustavderdrache @borisyankov @denisname +/types/d3-array/ @gustavderdrache @borisyankov @tomwanzek @denisname /types/d3-axis/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-box/ @lk-chen /types/d3-brush/ @tomwanzek @gustavderdrache @borisyankov @@ -745,16 +797,17 @@ /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 /types/d3-format/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-geo/ @ledragon @tomwanzek @gustavderdrache @borisyankov +/types/d3-graphviz/ @DomParfitt /types/d3-hexbin/ @uncovertruth @tomwanzek @denisname /types/d3-hierarchy/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-hsv/ @arrayjam @denisname -/types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-interpolate/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-path/ @tomwanzek @gustavderdrache @borisyankov /types/d3-polygon/ @tomwanzek @gustavderdrache @borisyankov /types/d3-quadtree/ @tomwanzek @gustavderdrache @borisyankov @denisname @@ -765,12 +818,12 @@ /types/d3-scale/v1/ @tomwanzek @gustavderdrache @borisyankov /types/d3-scale/ @tomwanzek @gustavderdrache @borisyankov /types/d3-scale-chromatic/ @Ledragon @gustavderdrache @borisyankov @henriquefm -/types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-selection/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-selection-multi/ @gustavderdrache @borisyankov /types/d3-shape/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-time/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-time/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-time-format/ @tomwanzek @gustavderdrache @borisyankov -/types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov +/types/d3-timer/ @tomwanzek @gustavderdrache @borisyankov @denisname /types/d3-tip/ @brspnnggrt /types/d3-transition/ @tomwanzek @gustavderdrache @borisyankov /types/d3-voronoi/ @tomwanzek @gustavderdrache @borisyankov @denisname @@ -802,6 +855,7 @@ /types/datejs/ @rupertavery /types/daterangepicker/ @SirMartin @smasala @nertzy /types/dav/ @ToastHawaii +/types/dayzed/ @samhh /types/db-migrate-base/ @nickiannone /types/db-migrate-pg/ @nickiannone /types/db.js/ @cgwrench @@ -809,8 +863,9 @@ /types/dd-trace/ @ColinBradley @alloy /types/deasync/ @Sicilica /types/debessmann/ @vkorehov -/types/debounce/ @denis-sokolov -/types/debug/ @swook @galtalmor @zamb3zi +/types/debounce/ @denis-sokolov @joshuakgoldberg @wcarson +/types/debounce-promise/ @whtsky +/types/debug/ @swook @galtalmor @zamb3zi @brasten /types/decamelize/ @samverschueren /types/decay/ @enaeseth /types/decompress/ @plantain-00 @jbethke @@ -824,7 +879,6 @@ /types/deep-freeze/ @Bartvds @aluanhaddad /types/deep-freeze-es6/ @mattbishop /types/deep-freeze-strict/ @mhegazy -/types/deepmerge/ @marvinscharle @syy1125 @AppLover69 /types/defaults/ @IbtihelCHNAB /types/defer-promise/ @niklasf /types/define-lazy-prop/ @BendingBender @@ -843,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 @@ -857,7 +914,9 @@ /types/detect-pointer/ @thomastilkema /types/detect-port/ @lith-light-g /types/detect-touch-events/ @thomastilkema -/types/detox/ @TareqElMasri +/types/detective/ @TeamworkGuy2 +/types/detox/ @TareqElMasri @stevechun +/types/dev-ip/ @mike-engel /types/devexpress-aspnetcore-bootstrap/ @devexpress @skubarenko /types/df-visible/ @Litee /types/dhtmlxgantt/ @mkozhukh @chriscamicas @@ -866,16 +925,21 @@ /types/di-lite/ @dcrusader /types/diacritics/ @otociulis /types/dialogflow/ @dyladan -/types/diff/ @vvakame @szdc +/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 @@ -886,10 +950,12 @@ /types/dojo/ @vansimke /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 -/types/dompurify/ @bazuzi +/types/dompurify/ @bazuzi @FlowCrypt /types/domready/ @dotnetnerd /types/donna/ @vvakame /types/dookie/ @swanest @@ -900,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 @@ -916,6 +982,7 @@ /types/draggabilly/ @jaydubu /types/dragster/ @zskovacs /types/dragula/ @pwelter34 @abruzzihraig +/types/dropbox-chooser/ @quas94 /types/dropboxjs/ @Steve-Fenton @xperiments /types/dropkickjs/ @VorobeY1326 /types/dropzone/v4/ @nvivo @outring @renuo @Hikariii @@ -923,7 +990,7 @@ /types/dts-generator/ @mtraynham /types/duplexer2/ @Goldsmith42 /types/duplexer3/ @BendingBender -/types/duplexify/ @strax +/types/duplexify/ @strax @kinwa91 /types/duplicate-package-checker-webpack-plugin/ @mtraynham /types/durandal/ @BlueSpire /types/dustjs-linkedin/ @mdezem @@ -946,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 @@ -959,6 +1026,7 @@ /types/ejs/ @benliddicott /types/ejs-locals/ @jt000 /types/ejson/ @shantanubhadoria +/types/elastic-apm-node/ @shahaed /types/elasticsearch/ @CasperSkydt @bfsmith @ddunkin @pushplay @mlamp @ahmadferdous @SimonSchick @brabster @deerawan /types/electron-config/ @mrfunkycold @unindented /types/electron-debug/ @unindented @@ -979,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 @@ -1023,7 +1091,9 @@ /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 /types/engine.io/ @KentarouTakeda /types/engine.io-client/ @KentarouTakeda @@ -1039,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 @@ -1097,16 +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/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki +/types/expo/v27/ @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 @@ -1137,6 +1213,7 @@ /types/express-mung/ @cyrilschumacher /types/express-myconnection/ @Cellule /types/express-mysql-session/ @Akim95 +/types/express-ntlm/ @forivall /types/express-oauth-server/ @atd-schubert /types/express-openapi/ @mugeso /types/express-paginate/ @AmirTugi @@ -1146,15 +1223,20 @@ /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 +/types/express-sitemap-xml/ @ffflorian /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 +/types/express-ws-routes/ @gstamac /types/express-xml-bodyparser/ @noticeMaker @macedigital /types/extend/ @reppners /types/extjs/ @brian428 @@ -1168,8 +1250,9 @@ /types/f1/ @neolwc /types/fabric/ @oklemencic @joewashear007 @mrand01 @NotWoods @bmartinson @RogerioTeixeira @BradleyHill /types/facebook-instant-games/ @menushka @oyvindjam -/types/facebook-js-sdk/ @amritk @mahmoudzohdi +/types/facebook-js-sdk/ @amritk @mahmoudzohdi @fluidsonic /types/facebook-pixel/ @noctishsu +/types/factory-girl/ @stackbuilders @sestrella @elcuy /types/faker/v3/ @Kuniwak /types/faker/ @bensw @basp @Kuniwak @mattbishop /types/falcor/ @Quramy @@ -1181,11 +1264,15 @@ /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 +/types/fastify-static/ @leomelzer /types/favico.js/ @drowse314-dev-ymat /types/favicons/ @mohsen1 /types/fb/ @JoshStrobl @@ -1212,7 +1299,7 @@ /types/feedme/ @codeanimal /types/feedparser/ @cortopy /types/fetch-jsonp/ @tkrotoff -/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues +/types/fetch-mock/ @asvetliakov @tamird @merrywhether @chrissinclair @matttennison @quentinbouygues @mtsmfm /types/fetch.io/ @newraina /types/ffi/ @loyd @waitingsong /types/ffi-napi/ @keerthi16 @KiranNiranjan @@ -1234,25 +1321,29 @@ /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 /types/firebase-token-generator/ @dotdotcommadot /types/firebird/ @karak /types/firefox/ @vvakame -/types/firefox-webext-browser/ @bomjacob +/types/firefox-webext-browser/ @jsmnbom /types/firmata/ @troywweber7 /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 @@ -1260,11 +1351,13 @@ /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 /types/flux/ @stkb @GiedriusGrabauskas /types/fluxible/ @xbim +/types/fluxible-addons-react/ @xbim /types/fluxible-router/ @xbim /types/fluxxor/ @mrk21 /types/fm-websync/ @markusmauch @@ -1289,6 +1382,7 @@ /types/foundation/ @borisyankov /types/fpsmeter/ @alampros /types/framebus/ @kbukum +/types/franc/ @wlegate /types/frctl__fractal/ @pmccloghrylaing /types/freedom/ @jpevarnek /types/freeport/ @atd-schubert @@ -1323,11 +1417,13 @@ /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 /types/gae.channel.api/ @vvakame /types/gamedig/ @ivansieder +/types/gamepad/ @Lange /types/gamequery/ @Laubi /types/ganache-core/ @LogvinovLeon /types/gandi-livedns/ @xstoudi @@ -1490,9 +1586,12 @@ /types/get-stdin/ @DanielRosenwasser /types/get-stream/ @douglasduteil @BendingBender /types/get-value/ @DanielRosenwasser +/types/getenv/ @impankratov /types/getopts/ @azasypkin /types/getos/ @BendingBender /types/gettext.js/ @jucrouzet +/types/gh-pages/ @DanielRosenwasser +/types/ghauth/ @Leko /types/gifffer/ @gatimus /types/gijgo/ @atatanasov /types/giraffe/ @darthapo @@ -1500,16 +1599,24 @@ /types/git-branch/ @rynclark /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 /types/glidejs/ @milanjaros -/types/glob/ @vvakame @voy +/types/glob/v5/ @vvakame @voy +/types/glob/ @vvakame @voy @ajafff /types/glob-base/ @alan-agius4 /types/glob-expand/ @vvakame /types/glob-parent/ @mrmlnc @@ -1520,20 +1627,21 @@ /types/globalize-compiler/ @iclanton /types/globby/ @douglasduteil @ikatyang /types/globule/ @durad +/types/glue/v4/ @gjednaszewski /types/glue/ @garfty -/types/gm/ @ChaosinaCan @maartenvanvliet +/types/gm/ @ChaosinaCan @maartenvanvliet @mlejva /types/go/ @NorthwoodsSoftware /types/google-adwords-scripts/ @jafaircl /types/google-apps-script/ @motemen @grant /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 @@ -1541,26 +1649,31 @@ /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 -/types/googlepay/ @Fluccioni @Radu-Raicea -/types/got/ @BendingBender @LinusU @ikokostya +/types/googlepay/ @Fluccioni @Radu-Raicea @fstanis +/types/got/v8/ @BendingBender @LinusU @ikokostya +/types/got/ @BendingBender @LinusU @ikokostya @stijnvn /types/graceful-fs/v2/ @Bartvds /types/graceful-fs/ @Bartvds @BendingBender /types/gradient-string/ @Ailrun /types/graham_scan/ @hberntsen /types/gramps__rest-helpers/ @claude /types/graphite-udp/ @EricByers -/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 +/types/graphlib-dot/ @DomParfitt +/types/graphql/ @TonyPythoneer @calebmer @intellix @firede @kepennar @freiksenet @IvanGoncharov @DxCx @rportugal @tgriesser @dyst5422 @adnsio @divyenduz @bradzacher @clayne11 @JCMais /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 /types/graphql-relay/ @arvitaly @nitintutlani @Grelinfo /types/graphql-resolve-batch/ @nayni +/types/graphql-resolvers/ @mike-engel /types/graphql-type-json/ @schfkt /types/graphviz/ @mhfrantz /types/grasp/ @agnoster @@ -1570,12 +1683,11 @@ /types/grecaptcha/v0/ @brentj73 /types/grecaptcha/ @DethAriel @rafaeltavares /types/gregorian-calendar/ @cwalv -/types/grid-styled/ @antonvasin @vittorio @lhache /types/gridfs-stream/ @liorm /types/gridstack/ @PascalSenn @ZoolWay @Sl1MBoy /types/grpc-error/ @danwbyrne /types/grunt/ @jeffmay @basarat -/types/gsap/ @codebelt @ProbablePrime @philipbulley +/types/gsap/ @codebelt @ProbablePrime @philipbulley @leomeloxp /types/gtin/ @RafaelKr /types/guid/ @maroy1986 /types/gulp/ @GiedriusGrabauskas @@ -1618,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 @@ -1662,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 @@ -1704,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 @@ -1721,6 +1837,8 @@ /types/holderjs/ @renjfk /types/hooker/ @misak113 /types/hopscotch/ @pimterry @Aurimas1 +/types/host-validation/ @dintopple +/types/hosted-git-info/ @OiyouYeahYou /types/howler/ @xperiments @tdukart @alien35 @nicholashza /types/hpp/ @kryops /types/html-entities/ @xstoudi @@ -1732,7 +1850,7 @@ /types/html-void-elements/ @rhysd /types/html-webpack-plugin/ @deevus @bumbleblym @tlaziuk /types/html-webpack-template/ @bumbleblym -/types/html2canvas/ @rwhepburn @tan9 @sschocke +/types/html2canvas/ @rwhepburn @tan9 @sschocke @Ristaaf /types/htmlbars-inline-precompile/ @chriskrycho /types/htmlparser2/ @staticfunction @LinusU /types/htmltojsx/ @basarat @@ -1744,7 +1862,7 @@ /types/http-graceful-shutdown/ @dlee-nvisia /types/http-link-header/ @screendriver /types/http-proxy/ @SomaticIT @Raigen @DanielMSchmidt -/types/http-proxy-agent/ @mrmlnc +/types/http-proxy-agent/ @mrmlnc @steprescott /types/http-proxy-middleware/ @zebMcCorkle @BendingBender /types/http-rx/ @L2jLiga /types/http-server/ @plantain-00 @@ -1759,13 +1877,16 @@ /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 /types/i18n/ @SomaticIT @FindQ +/types/i18n-abide/ @smbell /types/i18n-js/ @ypresto /types/i18next/v2/ @mxl @deerawan @GiedriusGrabauskas -/types/i18next/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/v8/ @mxl @deerawan @GiedriusGrabauskas +/types/i18next/ @mxl @deerawan @GiedriusGrabauskas @lenovouser @qqilihq @butchyyyy /types/i18next-browser-languagedetector/v0/ @cyrilschumacher @GiedriusGrabauskas /types/i18next-browser-languagedetector/ @cyrilschumacher @GiedriusGrabauskas /types/i18next-express-middleware/ @cyrilschumacher @@ -1791,6 +1912,7 @@ /types/ignore-styles/ @tai2 /types/iltorb/ @Alorel @reconbot /types/image-size/ @elisee +/types/image-type/ @ffflorian /types/imagemagick/ @soywiz /types/imagemagick-native/ @horiuchi /types/imagemapster/ @delphinus35 @@ -1802,11 +1924,11 @@ /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 -/types/in-app-purchase/ @l-jonas +/types/in-app-purchase/ @l-jonas @IchordeDionysos /types/in-range/ @DanielRosenwasser /types/inboxsdk/ @rdoursenaud @amiram /types/incremental-dom/ @basarat @lanthaler @vvakame @@ -1816,40 +1938,47 @@ /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 -/types/inline-style-prefixer/ @ahz @dpetrezselyova +/types/inline-style-prefixer/ @ahz @dpetrezselyova @franklixuefei /types/inquirer/ @tkQubo @ppathan @jouderianjr @bang88 @bitjson @synarque @jrockwood @kwkelly @Ailrun +/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 +/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 @@ -1859,19 +1988,22 @@ /types/is-ci/ @atd-schubert /types/is-color/ @VitorLuizC /types/is-compressed/ @mhegazy +/types/is-docker/ @YashdalfTheGray /types/is-empty/ @termosa /types/is-finite/ @mhegazy /types/is-glob/ @mrmlnc -/types/is-hotkey/ @petester42 +/types/is-hotkey/ @petester42 @kalley /types/is-ip/ @coderslagoon /types/is-mobile/ @LogvinovLeon /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 @@ -1885,6 +2017,7 @@ /types/is-url-superb/ @kryops /types/is-uuid/ @tedre191 /types/is-windows/ @mizunashi-mana +/types/isaac/ @mo /types/isbn-utils/ @elhaard /types/iscroll/ @csrakowski @devlato /types/ismobilejs/ @Ty3uK @@ -1906,8 +2039,11 @@ /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 /types/jasmine-enzyme/ @bolatovumar /types/jasmine-es6-promise-matchers/ @stephenlautier @@ -1918,10 +2054,10 @@ /types/jasmine-node/ @svi3c /types/jasmine-promise-matchers/ @matthewjh /types/jasmine_dom_matchers/ @devoto13 -/types/jasminewd2/ @sjelin +/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 @@ -1930,8 +2066,9 @@ /types/jdataview/ @RReverser /types/jdenticon/ @mtr /types/jest/v16/ @NoHomey @jwbay -/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald +/types/jest/ @NoHomey @jwbay @asvetliakov @alexjoverm @epicallan @ikatyang @wsmd @JamieMason @douglasduteil @ahnpnl @joshuakgoldberg @UselessPickles @r3nya @hotell @sebald @andys8 /types/jest-axe/ @JoshuaKGoldberg +/types/jest-cli/ @lifeiscontent /types/jest-diff/ @myabc /types/jest-docblock/ @ikatyang /types/jest-each/ @theutz @nickmccurdy @@ -1950,12 +2087,14 @@ /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 /types/joi/ @Bartvds @laurence-myers @cglantschnig @DavidBR-SW @GaelMagnan @ralekna @schfkt @rokoroku @dankraus @wanganjun @rafaelkallis @aconanlai @zaphoyd @thewillg @SimonSchick /types/joigoose/ @boothwhack /types/josa/ @vichyssoise @@ -1967,7 +2106,7 @@ /types/jqrangeslider/ @qcz /types/jquery/v1/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu /types/jquery/v2/ @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @DickvdBrink @King2500 @leonard-thieu -/types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 +/types/jquery/ @leonard-thieu @borisyankov @choffmeister @Steve-Fenton @Diullei @tasoili @jasons-novaleaf @seanski @Guuz @ksummerlin @basarat @nwolverson @derekcicerone @AndrewGaspar @seikichi @benjaminjackman @s093294 @JoshStrobl @johnnyreilly @DickvdBrink @King2500 @terrymun /types/jquery-ajax-chain/ @humana-fragilitas /types/jquery-alertable/ @stever /types/jquery-animate-scroll/ @AndersonFriaca @@ -1982,6 +2121,7 @@ /types/jquery-editable-select/ @baywet /types/jquery-focus-exit/ @AndersonFriaca /types/jquery-focusable/ @AndersonFriaca +/types/jquery-formatdatetime/ @AndersonFriaca /types/jquery-fullscreen/ @bgrieder /types/jquery-galleria/ @rimig /types/jquery-gray/ @AndersonFriaca @@ -2100,11 +2240,11 @@ /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 -/types/jschannel/ @yitzchok +/types/jschannel/ @yitzchok @McFlat /types/jscrollpane/ @qcz /types/jsdeferred/ @minodisk /types/jsdom/ @leonard-thieu @palmfjord @@ -2112,7 +2252,7 @@ /types/jsend/ @CaselIT /types/jsesc/ @Bartvds /types/jsfl/ @soywiz -/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln +/types/jsforce/ @dolanmiu @netes @amphro @tnoonan-salesforce @whiteabelincoln @borys-kupar /types/jsftp/ @xyleen /types/jsgraph/ @rosinbum /types/jshamcrest/ @dharkness @@ -2125,8 +2265,10 @@ /types/json-patch-gen/ @RohdeK /types/json-pointer/ @Bartvds /types/json-query/ @mtraynham +/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 @@ -2134,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 @@ -2144,15 +2287,18 @@ /types/jsonnet/ @hookclaw /types/jsonp/ @surenkov /types/jsonpath/ @horiuchi @ikatyang +/types/jsonquery/ @JimmyBoh /types/jsonrpc-serializer/ @Akim95 @many20 /types/jsonstream/ @Bartvds /types/jsontoxml/ @benstevens48 -/types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk +/types/jsonwebtoken/ @SomaticIT @danielheim @brikou @vpk @rlgod /types/jsonwebtoken-promisified/ @SomaticIT @danielheim @brikou @aneilbaboo -/types/jspdf/ @amberjs +/types/jspath/ @dex4er +/types/jspdf/ @amberjs @lleios @jemerald /types/jsqrcode/ @lordazzi /types/jsrender/ @zakki /types/jsreport-core/ @taoqf +/types/jsreport-html-embedded-in-docx/ @taoqf /types/jsreport-html-to-xlsx/v1/ @me /types/jsreport-html-to-xlsx/ @me /types/jsreport-jsrender/ @taoqf @@ -2174,7 +2320,9 @@ /types/jui/ @easylogic /types/jui-core/ @easylogic /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 @@ -2184,22 +2332,27 @@ /types/jwt-express/ @nickp10 /types/jwt-simple/ @kenfdev @GaelMagnan /types/jwt-then/ @phenomax +/types/k6/ @MajorBreakfast /types/kafka-node/ @dansitu @bkim54 @sfrooster @amiram -/types/karma/ @tkrotoff @43081j +/types/karma/v1/ @tkrotoff @43081j +/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 /types/karma-webpack/ @mtraynham /types/katex/ @mrand01 /types/kcors/ @Xstoudi @izayoiko -/types/kdbush/ @DenisCarriere +/types/kdbush/ @DenisCarriere @chrfrasco +/types/kdbxweb/ @Roang-zero1 /types/keen-tracking/ @rui-ferreira /types/kefir/ @AyaMorisawa @HitoriSensei /types/kendo-ui/ @telerik -/types/keyboardjs/ @vbortone @piranha771 +/types/kerberos/ @velezsarain +/types/keyboardjs/ @vbortone @piranha771 @teoxoy +/types/keycloak-connect/ @gstamac /types/keygrip/ @jkeylu /types/keymaster/ @nitram509 /types/keymirror/ @jfahrenkrug @@ -2212,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 @@ -2236,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 @@ -2251,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 @@ -2262,28 +2417,34 @@ /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 /types/koa-sslify/ @wingsbob /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 +/types/koa-websocket/ @moimael @jacogr @zdila @Kroisse /types/koa-xml-body/ @uwinkelvos /types/koa2-cors/ @xialeistudio /types/koa2-session-redis/ @DimaMukhin /types/koa__cors/ @Xstoudi @izayoiko @stevehipwell @sjmcdowall /types/kolite/ @borisyankov /types/konami.js/ @mareek +/types/kos-core/ @ali-Kos /types/kraken-js/ @darkwebdev @micksatana /types/kramed/ @tonicblue /types/kss/ @giladgray @@ -2292,14 +2453,18 @@ /types/kuromoji/ @mzsm @kgtkr /types/lab/ @prashaantt /types/ladda/ @dflor003 @leemicw +/types/lambda-log/ @armonge +/types/lambda-tester/ @ivank @HajoAhoMantila /types/lasso/ @darkwebdev /types/later/ @jasond-s /types/latinize/ @GiedriusGrabauskas /types/latlon-geohash/ @rimig /types/launchpad/ @rictic +/types/layzr.js/ @shermendev /types/lazy-value/ @ikatyang -/types/lazy.js/ @Bartvds +/types/lazy.js/ @Bartvds @miso440 /types/lazypipe/ @tomc974 +/types/ldap-filters/ @pluma /types/ldapjs/ @cvillemure @peterkooijmans /types/leadfoot/ @theintern /types/leaflet/v0/ @rgripper @@ -2314,7 +2479,7 @@ /types/leaflet-imageoverlay-rotated/ @tkleinke /types/leaflet-label/ @Nemo157 /types/leaflet-mouse-position/ @Hanyon -/types/leaflet-polylinedecorator/ @soucekv +/types/leaflet-polylinedecorator/ @soucekv @michaelfaisst /types/leaflet-providers/ @BendingBender /types/leaflet-rotatedmarker/ @robert-prib-polestar /types/leaflet-routing-machine/ @chanakadrathnayaka @@ -2329,32 +2494,43 @@ /types/leaflet.pancontrol/ @Brictarus /types/leaflet.pm/ @tkleinke /types/leaflet.polylinemeasure/ @RiON69 +/types/leakage/ @atd-schubert /types/leapmotionts/ @logotype +/types/ledgerhq__hw-transport/ @danwbyrne +/types/ledgerhq__hw-transport-node-hid/ @danwbyrne +/types/ledgerhq__hw-transport-u2f/ @danwbyrne /types/legal-eagle/ @j-f1 /types/lerna-get-packages/ @LogvinovLeon -/types/less/ @thasner @pranaygp @dwaxweiler +/types/less/ @thasner @pranaygp @dwaxweiler @chigix /types/less-middleware/ @federicobond /types/less2sass/ @gatimus /types/lestate/ @thelambdaparty /types/level-codec/ @danwbyrne /types/level-sublevel/ @basp -/types/leveldown/ @tarruda @LinusU -/types/levelup/ @blittle @tarruda +/types/leveldown/v1/ @tarruda @LinusU +/types/leveldown/ @MeirionHughes @danwbyrne +/types/levelup/v1/ @blittle @tarruda +/types/levelup/ @MeirionHughes @danwbyrne /types/leven/ @jmalonzo /types/levenshtein/ @geoffreak /types/libpq/ @Lodin /types/libsodium-wrappers/ @ffflorian +/types/libsodium-wrappers-sumo/ @ffflorian /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 /types/line-reader/ @stpettersens /types/linear-gradient/ @Jack-Works /types/lingui__core/ @huan086 +/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 @@ -2371,6 +2547,7 @@ /types/lockfile/v0/ @Bartvds /types/lockfile/ @Bartvds @BendingBender /types/lockr/ @droritos +/types/locks/ @flippynips /types/locutus/ @hookclaw /types/lodash/v3/ @bczengel @chrootsu /types/lodash/ @bczengel @chrootsu @stepancar @aj-r @ailrun @e-cloud @thorn0 @jtmthf @DomiR @@ -2671,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 @@ -2682,31 +2860,36 @@ /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 /types/magic-number/ @stpettersens /types/magicsuggest/ @leonardochaia /types/magnet-uri/ @tlaziuk /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/mali/ @danwbyrne +/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 @@ -2720,9 +2903,10 @@ /types/markdown-it/ @rapropos /types/markdown-it-anchor/ @seryl /types/markdown-it-container/ @hronex +/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 @@ -2730,7 +2914,8 @@ /types/maskedinput/ @lokeshpeta /types/masonry-layout/ @m-a-wilson @warriorrocker /types/massive/v3/ @swissspidy @clarenceh -/types/massive/ @swissspidy @clarenceh @AmazingTurtle +/types/massive/v4/ @swissspidy @clarenceh @AmazingTurtle +/types/massive/ @swissspidy @clarenceh @AmazingTurtle @mike-engel /types/match-media-mock/ @asvetliakov /types/match-sorter/ @claasahl /types/material-components-web/ @BrentDouglas @ckosti @@ -2767,11 +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 @@ -2790,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 @@ -2800,11 +2988,12 @@ /types/messenger/ @derekcicerone /types/meteor/ @barbatus @fullflavedave @orefalo @dagatsoin @birkskyum @ardatan @stefanholzapfel @andrei-markeev @lmachens /types/meteor-accounts-phone/ @DAB0mB +/types/meteor-astronomy/ @Deadly0 /types/meteor-collection-hooks/ @twastvedt /types/meteor-jboulhous-dev/ @vangorra /types/meteor-persistent-session/ @vangorra /types/meteor-prime8consulting-oauth2/ @vangorra -/types/meteor-publish-composite/ @vangorra +/types/meteor-publish-composite/ @vangorra @mrz5018 /types/meteor-roles/ @vangorra @mattmm3d /types/meteor-universe-i18n/ @mathewmeconry /types/method-override/ @santialbo @@ -2841,7 +3030,8 @@ /types/mitm/ @alejo90 /types/mixpanel/ @hjellek @Manduro /types/mixto/ @vvakame -/types/mjml/ @aahoughton +/types/mjml/ @aahoughton @marpstar +/types/mjml-react/ @henrinormak /types/mkdirp/ @Bartvds @mrmlnc /types/mkdirp-promise/ @pluma /types/mkpath/ @optical @@ -2860,9 +3050,11 @@ /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 +/types/module-deps/ @TeamworkGuy2 /types/moji/ @yasupeke /types/moment-business/ @wonbyte /types/moment-business-time/ @swist @@ -2877,11 +3069,11 @@ /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 +/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 -/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 +/types/mongoose/ @horiuchi @sindrenm @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz @@ -2893,6 +3085,7 @@ /types/mongoose-simple-random/ @rsxdalv /types/mongoose-unique-validator/ @stevehipwell /types/mongorito/ @pinguet62 +/types/mongration/ @soulthreads /types/moo/ @deltaidea @MofX /types/moonjs/ @DanielRosenwasser /types/morgan/ @staticfunction @pscanf @@ -2902,6 +3095,7 @@ /types/motor-hat/ @muntyan /types/mousetrap/ @qcz /types/move-concurrently/ @mgroenhoff +/types/moveto/ @shermendev /types/moviedb/ @basarat @0x6368656174 /types/moxios/ @itoasuka /types/mozilla-readability/ @charlesvdv @@ -2918,6 +3112,7 @@ /types/muicss/ @samuelneff /types/multer/ @jt000 @DavidBR-SW @mxl @hyunseob /types/multer-gridfs-storage/v1/ @devconcept +/types/multer-gridfs-storage/v2/ @devconcept /types/multer-gridfs-storage/ @devconcept /types/multer-s3/ @tcaesvk @galtalmor @terski /types/multi-typeof/ @mhegazy @@ -2932,10 +3127,12 @@ /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 /types/mz/ @ThomasHickman -/types/n3/ @phreed @rubensworks +/types/n3/ @phreed @rubensworks @LaurensRietveld /types/named-regexp-groups/ @jewbre /types/named-routes/ @qqilihq /types/nanoajax/ @nathancahill @@ -2969,15 +3166,19 @@ /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 /types/newline-remove/ @OpenByteDev -/types/newman/ @LogvinovLeon -/types/newrelic/ @mastermatt +/types/newman/ @LogvinovLeon @Graham42 +/types/newrelic/ @mastermatt @brookspatton /types/nexpect/ @vvakame -/types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira +/types/next/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv +/types/next-redux-saga/ @leocavalcante /types/next-redux-wrapper/ @stevegeek @Jungwoo-An +/types/next-server/ @dru89 @brikou @jthegedus @resir014 @scottdj92 @joaovieira @ajliv /types/ng-command/ @stephenlautier /types/ng-cordova/ @ksachdeva /types/ng-dialog/ @stephenlautier @@ -3001,30 +3202,33 @@ /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 /types/nodal/ @charrondev -/types/node/v4/ @eps1lon @Archcry -/types/node/v6/ @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry -/types/node/v7/ @parambirs @tellnes @WilcoBakker @eps1lon @KSXGitHub @Archcry -/types/node/v8/ @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/ @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/ @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 @ZaneHannanAU @ThomasdenH @eyqs @matthieusieben +/types/node/v0/ @Microsoft @DefinitelyTyped +/types/node/v4/ @Microsoft @DefinitelyTyped @eps1lon @Archcry +/types/node/v6/ @Microsoft @DefinitelyTyped @WilcoBakker @inlined @eps1lon @Alorel @KSXGitHub @Archcry +/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 @samuela /types/node-7z/ @erkie /types/node-array-ext/ @Beng89 /types/node-cache/ @chrootsu @dthunell @useltmann /types/node-calendar/ @luzianz /types/node-cleanup/ @agadar -/types/node-cron/ @maximelkin +/types/node-crate/ @gjednaszewski +/types/node-cron/ @maximelkin @burtek /types/node-dijkstra/ @nokutu /types/node-dir/ @panuhorsmalahti /types/node-dogstatsd/ @chrisbobo /types/node-emoji/ @jonestristand @styu /types/node-fetch/ @torstenwerner @nikcorg /types/node-fibers/ @caryhaynie -/types/node-forge/ @westy92 @flynetworks @a-k-g @rafal2228 @beenotung +/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 @@ -3044,6 +3248,7 @@ /types/node-pushnotifications/ @menushka /types/node-ral/ @ssddi456 /types/node-red/ @andersea @tbowmo +/types/node-redis-pubsub/ @renekeijzer /types/node-resque/ @gordey4doronin /types/node-rsa/ @alitaheri @xm /types/node-schedule/ @cyrilschumacher @flowpl @@ -3078,9 +3283,10 @@ /types/nodeunit/ @jedigo /types/noisejs/ @izmhr /types/nomnom/ @panopticoncentral +/types/nookies/ @andreasbergqvist /types/nopt/ @jbondc /types/normalize-package-data/ @jdxcode -/types/normalize-url/ @odin3 @BendingBender +/types/normalize-url/ @odin3 @BendingBender @mathieumg /types/notie/ @mateusdemboski /types/notify/ @hellochar /types/notifyjs/ @soundTricker @NateScarlet @@ -3091,13 +3297,13 @@ /types/nouislider/ @bleuarg @lagaffe /types/novnc-core/ @smithkl42 @BendingBender /types/npm/ @SomaticIT -/types/npm-package-arg/ @mgroenhoff +/types/npm-package-arg/ @mgroenhoff @OiYouYeahYou /types/npm-packlist/ @ajafff /types/npmlog/ @DanielMSchmidt @littlepiggy03 /types/ns-api/ @Archcry /types/nslog/ @unindented /types/nsqjs/ @cezaryrk -/types/nuka-carousel/ @Romic +/types/nuka-carousel/ @Romic @altaudio @matt-sungwook /types/number-is-nan/ @mhegazy /types/number-to-words/ @frederickfogerty /types/numeral/ @vbortone @BehindTheMath @klujanrosas @@ -3108,13 +3314,16 @@ /types/nvd3/ @PjMitchell /types/nw.gui/ @xperiments /types/nw.js/ @alirdn +/types/nwmatcher/ @woutervh- /types/o.js/ @IceOnFire @bradzacher @janhommes @jcchalte -/types/oauth/ @nonAlgebraic +/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 +/types/obj-str/ @saenglert /types/object-assign/ @chbrown /types/object-diff/ @rogierschouten /types/object-hash/ @misak113 @@ -3131,8 +3340,10 @@ /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 /types/offline-js/ @cgwrench /types/oibackoff/ @geoffreak /types/oidc-token-manager/ @rosieks @@ -3142,31 +3353,35 @@ /types/omggif/ @ffflorian /types/on-finished/ @czechboy0 @BendingBender /types/on-headers/ @jjeffery @BendingBender +/types/on-wake-up/ @ajafff /types/once/ @denis-sokolov @BendingBender /types/onesignal-cordova-plugin/ @broder /types/onetime/ @BendingBender /types/oniguruma/ @smhxx -/types/onoff/ @marcel-ernst +/types/onoff/ @marcel-ernst @Kallu609 /types/ontime/ @Hirse /types/open/ @Bartvds /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 +/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 @merufm @lance /types/optics-agent/ @crevil /types/optimist/ @soywiz @chbrown /types/optimize-css-assets-webpack-plugin/ @odnamrataizem /types/ora/v0/ @basarat @screendriver /types/ora/ @basarat @screendriver @BendingBender @azasypkin +/types/oracle__oraclejet/ @nolakara @jingxwu /types/oracledb/ @Bigous /types/orchestrator/ @tkQubo @TeamworkGuy2 /types/orderedmap/ @bradleyayers @@ -3189,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 @@ -3205,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 @@ -3216,9 +3432,11 @@ /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 +/types/p5/ @p5-types /types/package-json/ @jinwoo /types/packery/ @piraveen @hanssens /types/pad/ @mhegazy @@ -3226,16 +3444,18 @@ /types/paho-mqtt/ @amikhalev /types/pako/ @cappellin @calebegg /types/pangu/ @plantain-00 -/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af +/types/papaparse/ @torpedro @rainshen49 @jfloff @johnnyreilly @albertorestifo @BehindTheMath @3af @jliuhtonen /types/paper/ @clark-stevenson @Xakaloz @sebaswebdev @rfried /types/parallel-transform/ @djcsdy /types/paralleljs/ @jbaldwin +/types/parcel-bundler/ @pinage404 /types/parcel-env/ @fathyb /types/parent-package-json/ @sgmccli /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 @@ -3259,7 +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 @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 @@ -3275,14 +3498,16 @@ /types/passport-local/ @SomaticIT /types/passport-local-mongoose/ @linusbrolin /types/passport-naver/ @Park9eon @zerocho -/types/passport-oauth2/ @pasieronen @WangZishi +/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 /types/passport-unique-token/ @briman0094 @SomaticIT +/types/passport-vkontakte/ @soulthreads +/types/passport-windowsauth/ @forivall /types/password-hash/ @mugeso /types/password-hash-and-salt/ @alitaheri /types/path-exists/v1/ @shiwano @@ -3298,9 +3523,10 @@ /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 +/types/pdfmake/ @m1llen1um @radziksh @evolkmann /types/pdfobject/ @nielsboogaard /types/pebblekitjs/ @makotokw /types/peer-dial/ @RealTYPICAL @@ -3308,6 +3534,7 @@ /types/pegjs/ @vvakame @SrTobi @siegebell /types/pem/ @tony19 @DethAriel /types/pem-jwk/ @alessiopcc +/types/permit/ @jannikkeye /types/persona/ @Nycto /types/pet-finder-api/ @me /types/pg/v6/ @pspeter3 @@ -3339,12 +3566,14 @@ /types/picturefill/ @alaz /types/pidusage/ @cyrilschumacher @mx601595686 /types/pify/ @samverschueren @mad-mike @c7hm4r -/types/pigpio/ @manerfan -/types/pikaday/ @MidnightDesign @wake42 +/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 +/types/pino/ @psnider @BendingBender @screendriver @paambaati @alferpal @mortiy +/types/pino-http/ @screendriver /types/pino-multi-stream/ @JakeGinnivan /types/pinterest-sdk/ @adamburmister /types/pinyin/ @wanganjun @@ -3353,12 +3582,14 @@ /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 /types/playerframework/ @ricardosabino /types/playmusic/ @nickp10 /types/pleasejs/ @nakakura +/types/plist/ @higuri /types/plotly.js/ @chrisgervang @martinduparc @frederikaalund @taoqf @Dadstart @szechyjs @MercifulCode @soorajpudiyadath @jonfreedman @meganrm /types/plugapi/ @BNedry /types/plugin-error/ @rogierschouten @@ -3372,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 @@ -3380,6 +3617,13 @@ /types/popcorn/ @grapswiz /types/portscanner/ @douglasduteil /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 @@ -3393,7 +3637,7 @@ /types/pouchdb-adapter-node-websql/ @spaulg @geppy @fredgalvao /types/pouchdb-adapter-websql/ @spaulg @geppy @fredgalvao /types/pouchdb-browser/ @spaulg @geppy @fredgalvao -/types/pouchdb-core/ @spaulg @trubit @geppy @fredgalvao @TobiasBales @tiangolo +/types/pouchdb-core/ @spaulg @trubit @geppy @fredgalvao @TobiasBales @tiangolo @kmoe /types/pouchdb-find/ @trubit @tiangolo /types/pouchdb-http/ @spaulg @geppy @fredgalvao /types/pouchdb-mapreduce/ @spaulg @geppy @fredgalvao @@ -3429,20 +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 @danielpa9708 /types/prop-types/ @DovydasNavickas @ferdaber /types/proper-lockfile/ @qlonik /types/properties-reader/ @Goldsmith42 @@ -3462,7 +3709,7 @@ /types/prosemirror-tables/ @superchu @eshvedai @patsimm /types/prosemirror-transform/ @bradleyayers @davidka @timjb @patsimm /types/prosemirror-view/ @bradleyayers @davidka @timjb @patsimm -/types/proton-native/ @khanhas +/types/proton-native/ @khanhas @ltetzlaff /types/protractor-browser-logs/ @rokadias /types/protractor-helpers/ @johncant /types/protractor-http-mock/ @Crevil @@ -3475,15 +3722,17 @@ /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 +/types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick +/types/puppeteer-core/ @mtsmfm /types/pure-render-decorator/ @seansfkelley /types/purl/ @danfma /types/pusher-js/ @tkqubo @cainlevy @@ -3496,7 +3745,7 @@ /types/qhistory/ @Kovensky /types/qiniu-js/ @taoqf /types/qlik/ @RubenSlabbert @AginicX -/types/qlik-engineapi/ @konne +/types/qlik-engineapi/ @konne @richardison /types/qlik-visualizationextensions/ @konne /types/qr-image/ @taoqf /types/qrcode/ @plantain-00 @@ -3515,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/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 +/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 @@ -3541,23 +3799,28 @@ /types/raty/ @terrawheat /types/raven/ @scttcper @1999 @shreyjain1994 /types/raven-for-redux/ @chiubaka -/types/raygun4js/ @xt0rted @BenjaminHarding +/types/raygun/ @UberMouse +/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 -/types/rdf-js/ @rubensworks +/types/rdf-js/ @rubensworks @LaurensRietveld /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro -/types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @morcerf @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei +/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 @Kovensky /types/react-adal/ @dkorolev1 -/types/react-albus/ @sseppola -/types/react-alert/ @ssyrell +/types/react-albus/ @sseppola @conradreuter @kuirak +/types/react-alert/v2/ @ssyrell +/types/react-alert/ @g1eny0ung /types/react-alice-carousel/ @endigo /types/react-amplitude/ @rayzor65 /types/react-animate-on-scroll/ @ralbuque @@ -3568,7 +3831,9 @@ /types/react-autosuggest/ @nicolas-schmitt @pjo256 @robessog @tbayne @cdeutsch @rosskevin /types/react-avatar-editor/ @diogocorrea @gabsprates /types/react-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen -/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly +/types/react-better-password/ @mhuynh1 +/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 @@ -3576,15 +3841,17 @@ /types/react-bootstrap-table/v2/ @flaub @alelode @UJosue10 /types/react-bootstrap-table/ @flaub @alelode @UJosue10 @dawnmist @Ogglas /types/react-bootstrap-typeahead/ @Guymestef @radziksh @PaitoAnderson -/types/react-breadcrumbs/ @KostyaEsmukov +/types/react-breadcrumbs/ @guoyunhe /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 /types/react-circular-progressbar/ @lstanden /types/react-click-outside/ @screendriver +/types/react-close-on-escape/ @JamesAlias /types/react-codemirror/ @velveret @rudi-c /types/react-coinhive/ @sktbcbbs /types/react-collapse/ @Kimahriman @@ -3594,8 +3861,10 @@ /types/react-content-loader/ @alaatm @samwalshnz /types/react-copy-to-clipboard/ @mabels @BernabeFelix /types/react-copy-write/ @samhh @davej +/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 @@ -3606,16 +3875,18 @@ /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-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf +/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 /types/react-dnd-multi-backend/ @dawnmist @beeequeue /types/react-dnd-touch-backend/ @mleko @dawnmist @beeequeue +/types/react-document-meta/ @ulrichb /types/react-document-title/ @cleverguy25 /types/react-dom/v15/ @MartynasZilinskas /types/react-dom/ @MartynasZilinskas @theruther4d /types/react-dom-factories/ @jgoz +/types/react-draft-wysiwyg/ @imechZhangLY /types/react-dragtastic/ @nscarcella /types/react-dropzone/v2/ @matdube @LynxEyes @goblindegook @benbayard /types/react-dropzone/v3/ @matdube @LynxEyes @goblindegook @benbayard @LKay @@ -3625,12 +3896,13 @@ /types/react-event-listener/ @asvetliakov /types/react-fa/ @flaub @patsissons @LKay /types/react-facebook-login/ @apare @jankarres +/types/react-facebook-login-component/ @koss-lebedev /types/react-faux-dom/ @alitaheri @cleverguy25 @deviousm @hanai /types/react-file-input/ @dmitryrogozhny /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 @@ -3640,6 +3912,7 @@ /types/react-gateway/ @jsonunger /types/react-geosuggest/ @brmenchl /types/react-global-configuration/ @ryokik +/types/react-google-login-component/ @koss-lebedev /types/react-google-maps-loader/ @vasilysn /types/react-google-places-suggest/ @vasilysn /types/react-google-recaptcha/ @KoalaHuman @@ -3652,79 +3925,90 @@ /types/react-helmet/ @evanbb @isman-usoh @lith-light-g @sammkj @yuit /types/react-helmet-async/ @forabi /types/react-highlight/ @joshuakgoldberg -/types/react-highlight-words/ @mhegazy @diogodca +/types/react-highlight-words/ @mhegazy @diogodca @kellyrmilligan /types/react-highlighter/ @oizie /types/react-holder/ @isman-usoh /types/react-hot-loader/ @jacekjagiello @MartynasZilinskas @DovydasNavickas /types/react-hyperscript/ @tock203 -/types/react-i18next/v1/ @KostyaEsmukov -/types/react-i18next/v4/ @GiedriusGrabauskas @netanelgilad -/types/react-i18next/ @GiedriusGrabauskas @chnoch @beheh @whtsky /types/react-icon-base/ @apare @LKay /types/react-icons/ @apare @johnnyreilly @LKay /types/react-image-crop/ @danielasy +/types/react-image-fallback/ @8enSmith /types/react-image-gallery/ @adamwpc /types/react-imageloader/ @stephenjelfs +/types/react-images/ @KonstantinLukaschenko +/types/react-imgpro/ @echoulen /types/react-infinite/ @rhysd /types/react-infinite-calendar/ @christianchown -/types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork -/types/react-infinite-scroller/ @Lapanti @psrebniak +/types/react-infinite-scroll-component/ @sroy3 @burtek @davidkevork @JoshuaScript +/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 @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 +/types/react-is/ @AviVahl @christianchown /types/react-is-deprecated/ @seansfkelley -/types/react-joyride/ @kdy1 +/types/react-joyride/ @kdy1 @kamranayub /types/react-js-pagination/ @netoisc /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor -/types/react-jsonschema-form/ @iamdanfox @iplus26 @KurtPreston @phbou72 @LucianBuzzo +/types/react-jsonschema-form/ @iamdanfox @iplus26 @phbou72 @LucianBuzzo @sthenault @sbusch +/types/react-jss/ @eps1lon /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 /types/react-loader/ @artfuldev +/types/react-lottie/ @Kana00 @Ricki-BumbleDev /types/react-mailchimp-subscribe/ @osdiab /types/react-map-gl/ @rimig @fnberta /types/react-maskedinput/ @LKay @lavoaster @CarlosBonetti /types/react-mce/ @morphologue /types/react-mdl/ @bradzacher /types/react-measure/ @asvetliakov @marcfallows +/types/react-mentions/ @activescott /types/react-mixin/ @tkqubo -/types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz +/types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz @jpowell /types/react-motion/ @stepancar @asvetliakov @dimitarnestorov /types/react-motion-slider/ @asvetliakov /types/react-motion-ui-pack/ @jsonunger -/types/react-native/ @alloy @huhuanming @iRoachie @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam +/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel /types/react-native-android-taskdescription/ @christianchown /types/react-native-auth0/ @ascariandrea /types/react-native-autocomplete-input/ @ifiokjr /types/react-native-background-timer/ @chillkroeteTTS /types/react-native-bluetooth-serial/ @RodrigoAWeber -/types/react-native-calendars/ @Tyler-Zhang @DavidNorena +/types/react-native-calendars/ @Tyler-Zhang @DavidNorena @FabianMeul /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 +/types/react-native-google-signin/ @j-fro @bm-software @christianchown @echentw /types/react-native-htmlview/ @ifiokjr +/types/react-native-huawei-protected-apps/ @christianchown /types/react-native-i18n/ @VincentLanglet /types/react-native-indicators/ @ifiokjr /types/react-native-keep-awake/ @huhuanming @@ -3746,7 +4030,11 @@ /types/react-native-popup-dialog/ @PaitoAnderson @connectdotz @bm-software /types/react-native-push-notification/ @PaitoAnderson @tomSawkins /types/react-native-qrcode/ @plantain-00 +/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 /types/react-native-settings-list/ @MrLuje @@ -3756,6 +4044,7 @@ /types/react-native-sortable-list/ @sivolobov @RookY2K /types/react-native-sqlite-storage/ @dryganets @cavarzan /types/react-native-star-rating/ @iRoachie +/types/react-native-status-bar-height/ @fiznool /types/react-native-svg-charts/ @krzysztof-miemiec /types/react-native-svg-uri/ @iRoachie /types/react-native-swiper/ @CaiHuan @huhuanming @mhcgrq @@ -3764,11 +4053,12 @@ /types/react-native-text-input-mask/ @RodrigoAWeber /types/react-native-toast-native/ @bm-software /types/react-native-touch-id/ @huhuanming @gazaret @jinshin1013 +/types/react-native-uuid-generator/ @burtek /types/react-native-vector-icons/ @iRoachie @timwangdev /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 +/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 @@ -3776,12 +4066,14 @@ /types/react-notify-toast/ @klaascuvelier /types/react-numeric-input/ @heatherbooker @akx /types/react-onclickoutside/v5/ @LKay -/types/react-onclickoutside/ @LKay -/types/react-onsenui/ @salim7 @jemmyw +/types/react-onclickoutside/ @LKay @surgeboris +/types/react-onsenui/ @salim7 @jemmyw @lirbank +/types/react-outside-click-handler/ @zubivan /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 @@ -3793,8 +4085,9 @@ /types/react-qr-reader/ @davidkevork /types/react-radio-group/ @jsonunger /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 @@ -3806,10 +4099,10 @@ /types/react-responsive/ @asvetliakov @alechill @xaviergonz /types/react-rnd/ @Ragg- @fsubal @zyh825 /types/react-router/v2/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov -/types/react-router/v3/ @sergey-buturlakin @mrk21 @vasek17 @ngbrown @awendland @KostyaEsmukov @johnnyreilly @LKay @DovydasNavickas @ssorallen @gillchristian -/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 +/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 @@ -3828,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 @@ -3839,20 +4132,24 @@ /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 /types/react-swipe/ @DeividasBakanas /types/react-swipeable/ @GiedriusGrabauskas @mctep @horiuchi /types/react-swipeable-views/ @mxl @DeividasBakanas -/types/react-syntax-highlighter/ @NoHomey -/types/react-table/ @royxue @psakalo @Havret +/types/react-syntax-highlighter/ @NoHomey @ajgamble-milner +/types/react-table/ @royxue @psakalo @Havret @andys8 @Gelio /types/react-table-filter/ @gjsln -/types/react-tabs/ @danez +/types/react-tabs/ @danez @Equationist +/types/react-tag-autocomplete/ @jlismore /types/react-tag-input/ @Ogglas @jankarres @matthewberryman /types/react-tagcloud/ @wassname /types/react-tagsinput/ @mykter @@ -3862,6 +4159,7 @@ /types/react-tether/ @ryprice /types/react-text-mask/ @guilhermehubner @cavarzan @needpower /types/react-textarea-autosize/ @asvetliakov @zry656565 +/types/react-timeago/ @koss-lebedev /types/react-timeout/ @kerwynrg /types/react-toastify/ @icopp /types/react-toastr/ @shssoichiro @DanRegazzi @@ -3878,19 +4176,21 @@ /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 @gcangussu /types/react-webcam/ @squat /types/react-weui/ @tairan -/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz +/types/react-widgets/ @rogierschouten @sanyatuning @frodehansen2 @r3nya @MBillemaz @georg94 /types/react-widgets-moment/ @dawnmist /types/react-window/ @martynaskadisa +/types/react-window-size/ @jakejrichards /types/react-youtube/ @kgtkr /types/react-youtube-embed/ @charles-salmon /types/reactable/ @spielc /types/reactcss/ @chrisgervang @LKay /types/reactstrap/v4/ @alihammad @mfal @danilobjr @fabiopaiva -/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @KurtPreston @timc13 @patrickrgaffney @prabodht +/types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @timc13 @patrickrgaffney @prabodht /types/read/ @timjk /types/read-chunk/ @crispybee /types/read-package-tree/ @mgroenhoff @@ -3901,19 +4201,24 @@ /types/readline-sync/ @jonestristand /types/readline-transform/ @dex4er /types/reapop/ @Barrokgl +/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 +/types/recompose/ @iskandersierra @clayne11 @Pajn @lucasterra @brian-lives-outdoors @TiuSh /types/reconnect-core/ @thw0rted /types/reconnectingwebsocket/ @nguarracino +/types/recorder-js/ @higuri /types/recursive-readdir/v1/ @elisee /types/recursive-readdir/ @elisee @MicahZoltu -/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski +/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 @@ -3921,7 +4226,7 @@ /types/reduce-reducers/ @huy-nguyen /types/redux-action/ @newraina /types/redux-action-utils/ @tkqubo -/types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh +/types/redux-actions/ @jaysoo @alexgorbatchev @alechill @alexey-pelykh @7hi4g0 /types/redux-async-queue/ @andreiho /types/redux-auth-wrapper/v1/ @LKay /types/redux-auth-wrapper/ @LKay @@ -3931,15 +4236,16 @@ /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 +/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 /types/redux-form/v4/ @aikoven /types/redux-form/v6/ @carsonf @aikoven @LKay @bancek -/types/redux-form/ @carsonf @aikoven @LKay @bancek @alsiola @tehbi4 @huwmartin @ethanresnick @reggino @maddijoyce -/types/redux-immutable/ @oizie @sebald @gavingregory -/types/redux-immutable-state-invariant/ @remojansen @highflying +/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 @mihai-dinculescu /types/redux-infinite-scroll/ @silkyfray /types/redux-injectable-store/ @unindented /types/redux-localstorage/ @LKay @@ -3957,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 @@ -3980,13 +4287,15 @@ /types/relateurl/ @tkrotoff /types/relaxed-json/ @18steps /types/relay-runtime/ @voxmatt @alloy +/types/rellax/ @shermendev /types/remarkable/ @makepost /types/remote-redux-devtools/ @ColinEberhardt @unindented @mamodom @colindekker /types/remove-markdown/ @RagibHasin /types/rename/ @Aankhen /types/replace-ext/ @DeividasBakanas +/types/replacestream/ @dex4er /types/req-cwd/ @Alorel -/types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella +/types/request/ @soywiz @bonnici @Bartvds @joeskeen @ccurrens @lookfirst @mastermatt @josecolella @murbanowicz /types/request-as-curl/ @atd-schubert /types/request-ip/ @mrhen /types/request-promise/ @cglantschnig @joeskeen @AyaMorisawa @mastermatt @@ -4005,7 +4314,7 @@ /types/resolve/ @marionebl @ajafff /types/resolve-from/ @unional /types/resourcejs/ @shaunluttin -/types/response-time/ @urossmolnik @TonyPythoneer +/types/response-time/ @urossmolnik @TonyPythoneer @danmana /types/rest/ @Nemo157 /types/restangular/ @borisyankov /types/restful.js/ @tkqubo @@ -4038,22 +4347,26 @@ /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 +/types/rocksdb/ @MeirionHughes @danwbyrne /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 /types/route-parser/ @ianks @bobbuehler /types/routie/ @Adilson -/types/royalslider/ @csrakowski +/types/royalslider/ @csrakowski @sKopheK /types/rpio/ @DominikPalo @Pencl /types/rrc/ @DeividasBakanas /types/rsmq/ @MugeSo @@ -4103,17 +4416,26 @@ /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 /types/schema-registry/ @bonzzy /types/schwifty/ @ozum /types/scoped-http-client/ @mattvperry @rianadon /types/screenfull/ @icholy @lionelb @joelshepherd -/types/screeps/ @MarkoSulamagi @NhanHo @bryanbecker @resir014 @Arcath @apemanzilla +/types/screeps/ @MarkoSulamagi @NhanHo @bryanbecker @resir014 @Arcath @dmarcuse /types/screeps-profiler/ @ramblurr /types/scriptjs/ @ssttevee /types/scroll-into-view/ @zivni @@ -4126,7 +4448,8 @@ /types/scryptsy/ @micksatana /types/sdp-transform/ @loc /types/seamless/ @danmana -/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg +/types/seamless-immutable/ @alex3165 @xsburg @geirsagberg @RMHonor +/types/season/ @dex4er /types/secp256k1/ @anler /types/seed-random/ @l-jonas /types/seededshuffle/ @urish @@ -4169,33 +4492,38 @@ /types/send/ @MikeJerred /types/seneca/ @psnider @kevynb /types/sequelize/v3/ @samuelneff @codeanimal @drinchev @morpheusxaut @torhal -/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd @nrschultz @thomas-b +/types/sequelize/ @samuelneff @codeanimal @drinchev @babolivier @kukoo1 @oktapodia @morpheusxaut @TitaneBoy @zjy01 @nidzov @Raigen @todd @nrschultz @thomas-b @Antoine38660 /types/sequelize-cursor-pagination/ @pilagod /types/sequelize-fixtures/ @cschwarz /types/sequencify/ @npenin /types/sequester/ @Strate /types/serialize-error/ @thomasthiebaud -/types/serialize-javascript/ @lith-light-g +/types/serialize-javascript/ @lith-light-g @Pochodaydayup /types/serialport/v4/ @codefoster +/types/serialport/v6/ @codefoster @apearson /types/serialport/ @codefoster @apearson /types/serve-favicon/ @urossmolnik /types/serve-index/ @tkrotoff /types/serve-static/ @urossmolnik @LinusU /types/server/ @sant123 @iddan /types/server-destroy/ @gyszalai +/types/serverless/ @hassankhan /types/servicenow/ @bryceg /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 /types/shallowequal/ @seansfkelley /types/shapefile/ @DenisCarriere @Thw0rted /types/sharedb/ @soney /types/sharedworker/ @nakakura /types/sharepoint/ @gandjustas @andrei-markeev @baywet @teroarvola @dennispg -/types/sharp/ @lith-light-g @wooseopkim +/types/sharp/ @lith-light-g @wooseopkim @BTOdell /types/sheetify/ @toddself /types/shell-escape/ @nenadalm /types/shell-quote/ @jason0x43 @@ -4206,10 +4534,13 @@ /types/shipit-utils/ @cyrilschumacher /types/shopify-buy/ @openminder @straiforos @totemika /types/shortid/ @stpettersens @despairblue -/types/shot/ @AJamesPhillips +/types/shot/v3/ @AJamesPhillips @SimonSchick +/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 /types/siesta/ @bquarmby /types/sigmajs/ @qinfchen @@ -4224,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 @@ -4234,9 +4565,10 @@ /types/simplemde/ @Scalesoft /types/simplesmtp/ @rogierschouten /types/simplestorage.js/ @axelcostaspena @mxl +/types/sindresorhus__df/ @whatknight /types/single-line-log/ @ffflorian /types/single-spa-react/ @Garrett-Smith-iq -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg +/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 @@ -4253,41 +4585,49 @@ /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 /types/slackdown/ @nju33 /types/slackify-html/ @hypexr -/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil @isubasti +/types/slate/ @andykent @majelbstoat @JanLoebel @YangusKhan @kalley @Kornil @isubasti @sgreav /types/slate-base64-serializer/ @YangusKhan /types/slate-html-serializer/ @YangusKhan /types/slate-irc/ @elisee -/types/slate-plain-serializer/ @YangusKhan -/types/slate-react/ @andykent @majelbstoat @JanLoebel @PatrickSachs @YangusKhan @isubasti +/types/slate-plain-serializer/ @YangusKhan @mkiefel +/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 /types/snekfetch/ @ANekoIsFineToo @ShayBox @Dev-Yukine /types/snoowrap/ @vitosamson @TheAppleFreak +/types/snowball-stemmers/ @ryanvolum /types/snowboy/ @dolanmiu +/types/socket.io/v1/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io/ @progre @divillysausages @florentpoujol @KentarouTakeda @gigi @BrainMaestro /types/socket.io-client/ @progre @divillysausages @florentpoujol /types/socket.io-p2p/ @saenglert /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 @@ -4297,8 +4637,10 @@ /types/solidity-parser-antlr/ @LogvinovLeon @albrow /types/solr-client/ @liul85 /types/solution-center-communicator/ @dami-gg +/types/sonic-boom/ @alferpal /types/sort-array/ @mrmlnc -/types/sortablejs/ @Maw-Fox +/types/sort-object-keys/ @forivall +/types/sortablejs/ @Maw-Fox @maartenstaa /types/soundmanager2/ @elton2048 /types/soupbintcp/ @jewbre /types/source-list-map/ @e-cloud @@ -4315,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 @@ -4325,8 +4667,9 @@ /types/spotify-api/ @skovmand /types/spotify-web-playback-sdk/ @Festify @mraerino @NeoLegends /types/sprintf/ @soywiz @BendingBender -/types/sprintf-js/ @jasonswearingen @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 @@ -4334,8 +4677,8 @@ /types/squirejs/ @bradleyayers /types/srp/ @Patman64 /types/ssh-key-decrypt/ @BendingBender -/types/ssh2/ @tkQubo @rbuckton -/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 @@ -4346,6 +4689,8 @@ /types/stampit/v2/ @koresar /types/stampit/ @koresar @lummish /types/stamplay-js-sdk/ @ridermansb +/types/standard-error/ @roblabat +/types/standard-http-error/ @roblabat /types/starwars-names/ @claasahl /types/stat-mode/ @BendingBender /types/stats.js/ @gregolai @hberntsen @danvk @@ -4358,13 +4703,16 @@ /types/steam-totp/ @phenomax /types/steamid/ @Slessi /types/steed/ @Paul-Isache -/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause +/types/stellar-sdk/ @carl-foster @tristonj @pselden @maxbause @charlie-wasp /types/stemmer/ @will-ockmore /types/sticky-cluster/ @paustint +/types/stompit/ @DanielRose /types/stompjs/ @jimic @Dr4k4n -/types/stoppable/ @EricByers -/types/store/ @vbortone @harry0000 @Ky6uk +/types/stoppable/ @EricByers @jplusje +/types/storage-helper/ @ajafff +/types/store/ @vbortone @harry0000 @Ky6uk @igl00 /types/storybook-addon-jsx/ @jameslnewell +/types/storybook-readme/ @lonyele /types/storybook__addon-a11y/ @hyunseob /types/storybook__addon-actions/ @joscha @jicjjang /types/storybook__addon-backgrounds/ @hyunseob @@ -4374,11 +4722,12 @@ /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 /types/stream-chain/ @uhop /types/stream-csv-as-json/ @uhop @@ -4391,14 +4740,17 @@ /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 /types/strftime/ @cyrilschumacher /types/strict-uri-encode/ @hoishin /types/string/ @basp +/types/string-argv/ @vladimir-tikhonov /types/string-format/ @lal12 /types/string-hash/ @ethanrubio +/types/string-replace-webpack-plugin/ @pd4d10 /types/string-similarity/ @ragtime /types/string-template/ @TonyPythoneer /types/string-width/ @jacobbubu @@ -4407,25 +4759,31 @@ /types/strip-ansi/ @mhegazy /types/strip-bom/ @mhegazy /types/strip-json-comments/ @dmoonfire -/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger +/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr /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 /types/strophe/ @DavidKDeutsch +/types/strophe.js/ @DavidKDeutsch /types/structured-source/ @azu -/types/styled-components/ @Igorbek @Igmat +/types/styled-components/v3/ @Igorbek @Igmat +/types/styled-components/ @Igorbek @Igmat @lavoaster @Kovensky /types/styled-jsx/ @R1ZZU -/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster +/types/styled-react-modal/ @Lavoaster +/types/styled-system/ @maxdeviant @phobon @zephraph @damassi @alloy @maoueh @lavoaster @jschuler +/types/styled-theming/ @ArjanJ /types/stylelint/v7/ @alan-agius4 -/types/stylelint/ @alan-agius4 +/types/stylelint/ @alan-agius4 @filipsalpe /types/stylelint-webpack-plugin/ @bahlo +/types/stylenames/ @bengry /types/stylus/ @SomaticIT /types/subscribe-ui-event/ @wangcheng678 /types/subsume/ @BendingBender +/types/subtitle/ @jenglamlow /types/succinct/ @EnableSoftware /types/sudo-block/ @BendingBender /types/suitescript/ @darrenhillconsulting @@ -4433,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 @@ -4457,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 @@ -4466,7 +4824,7 @@ /types/swagger-parser/ @Tobias4872 @EricHenry /types/swagger-restify-mw/ @micmro /types/swagger-sails-hook/ @micmro -/types/swagger-schema-official/ @mohsen1 @bsouthga @nimerritt +/types/swagger-schema-official/ @mohsen1 @bsouthga @nimerritt @mauriedo /types/swagger-tools/ @bricka /types/swagger-ui-dist/ @haowen737 /types/swagger-ui-express/ @dmitryrogozhny @@ -4478,7 +4836,7 @@ /types/swig-email-templates/ @mrhen @micksatana /types/swipe/ @kant2002 /types/swiper/v3/ @sgaliano @lucax88x -/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam +/types/swiper/ @sgaliano @lucax88x @ematseruk @odahcam @jmca /types/swipeview/ @borisyankov /types/switchery/ @bgrieder @claylaut /types/swiz/ @jedigo @@ -4486,10 +4844,12 @@ /types/synaptic/ @ToastHawaii @austincummings /types/systeminformation/ @PixelcrabAT /types/systemjs/ @ludohenin @NathanWalker @GiedriusGrabauskas @aluanhaddad +/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 @@ -4500,6 +4860,7 @@ /types/tar-stream/ @glicht /types/task-graph-runner/ @mgroenhoff /types/tcp-ping/ @stegano +/types/tcp-port-used/ @gautejohan /types/teddy/ @lannonbr /types/tedious/ @rogierschouten @cjthompson @v-suhame /types/tedious-connection-pool/ @sandorfr @@ -4507,24 +4868,30 @@ /types/temp/ @DanielRosenwasser /types/temp-write/ @BendingBender /types/tempfile/ @SamVerschueren @BendingBender -/types/tempy/ @douglasduteil +/types/tempy/ @douglasduteil @maistho /types/terminal-menu/ @aravindarun +/types/tern/ @nkappler +/types/terser/ @JordiAnderl +/types/test-console/ @roberto @guidoux @gbmoretti /types/test-listen/ @stephenmathieson /types/testingbot-api/ @timbru31 /types/tether/ @adidahiya /types/tether-drop/ @adidahiya /types/tether-shepherd/ @mtgibbs /types/text-buffer/ @GlenCFL -/types/text-encoding/ @pine613 @mohsen1 +/types/text-encoding/ @pine @mohsen1 @nwmqpa /types/text-encoding-utf-8/ @trxcllnt /types/text-table/ @saadq /types/textarea-caret/ @shiftkey /types/textract/ @lal12 /types/textversionjs/ @aaronosher +/types/texzilla/ @m93a /types/tgfancy/ @Dabolus /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 +/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 @@ -4534,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 @@ -4541,10 +4909,13 @@ /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 /types/tingle.js/ @ajafff +/types/tiny-async-pool/ @krlwlfrt /types/tiny-secp256k1/ @eduhenke /types/tiny-slider-react/ @screendriver /types/tinycolor2/ @M-Zuber @geertjansen @nvh @Ailrun @@ -4564,20 +4935,21 @@ /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 /types/topojson-simplify/ @denisname @ricardo-mello /types/topojson-specification/ @denisname /types/toposort/ @danwbyrne +/types/torrent-search-api/ @ngirardin /types/torrent-stream/ @xstoudi /types/touch/ @mizunashi-mana @BendingBender /types/touch-events/ @kevinb7 /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 @@ -4587,6 +4959,7 @@ /types/travis-fold/ @andy-ms /types/trayballoon/ @korve /types/tress/ @sindilevich +/types/trianglify/ @unindented /types/trim/ @skysteve /types/triple-beam/ @danwbyrne /types/triplesec/ @threesquared @@ -4595,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 @@ -4646,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 @@ -4657,9 +5033,9 @@ /types/unzip/ @coding2012 /types/unzipper/ @s73obrien @natemara @bartje321 /types/update-notifier/v1/ @vvakame @nchen63 -/types/update-notifier/ @vvakame @nchen63 @bitjson +/types/update-notifier/ @vvakame @nchen63 @bitjson @grinich /types/uploadcare/ @jineshshah36 -/types/upng-js/ @plantain-00 +/types/upng-js/ @plantain-00 @pineapplemachine /types/uppercamelcase/ @plantain-00 /types/urbanairship-cordova/ @Justin-Credible /types/uri-templates/ @Bartvds @barnski @@ -4693,6 +5069,8 @@ /types/uuid-parse/ @screendriver /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 @@ -4708,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 @@ -4716,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 @@ -4732,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 @@ -4751,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 @@ -4760,6 +5139,7 @@ /types/w3c-web-usb/ @larsgk /types/waitme/ @totpero /types/wake_on_lan/ @SrTobi +/types/walk/ @poppa /types/wallabyjs/ @andrewconnell /types/wallpaper/ @BendingBender /types/wampy/ @KSDaemon @@ -4769,30 +5149,33 @@ /types/watchpack/ @e-cloud /types/waterline/ @arvitaly /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/web3/ @simon-jentzsch @nitzantomer @zurbo @yxliang01 @phra @naddison36 @icaroharry @linusnorton @jpeletier @anneau @matrushka @andrevmatos @levino @zlumer @archangel-irk +/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 /types/webcrypto/ @iislucas -/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 @phil-lgr +/types/webdriverio/ @nmalaguti @timbru31 @fsmedberg-tc @tanvirislam06 @daveparslow @phil-lgr /types/webfontloader/ @doskallemaskin /types/webgl-ext/ @zenmumbler /types/webgl2/ @nkemnitz @karhu /types/webidl2/ @saschanaz /types/webmidi/ @lostfictions -/types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @christophehurpeau -/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly +/types/webpack/v3/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @christophehurpeau @rwaskiewicz @kuehlein +/types/webpack/ @tkqubo @bumbleblym @bcherny @tommytroylin @mohsen1 @jcreamer898 @alan-agius4 @elliottsj @jason0x43 @dennispg @christophehurpeau @ZSkycat @johnnyreilly @rwaskiewicz @kuehlein /types/webpack-assets-manifest/ @FranklinWhale /types/webpack-bundle-analyzer/ @kryops /types/webpack-chain/ @eirikurn @psachs21 @@ -4816,9 +5199,11 @@ /types/webpack-serve/ @rynclark @Jokcy @ZSkycat /types/webpack-sources/ @e-cloud @chriseppstein /types/webpack-stream/ @iclanton @bumbleblym +/types/webpack-subresource-integrity/ @huan086 /types/webpack-validator/ @deevus /types/webpackbar/ @rynclark /types/webpagetest/ @ksm2 +/types/webprogbase-console-view/ @veetaha /types/webrtc/ @nakakura /types/webscopeio__react-textarea-autocomplete/ @michauzo /types/websequencediagrams/ @ffflorian @@ -4845,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 @@ -4864,6 +5250,7 @@ /types/wnumb/ @acoreyj /types/wonder.js/ @yyc-git /types/word-list-json/ @dovidm +/types/word2vector/ @renekeijzer /types/wordcloud/ @joeskeen /types/words-to-numbers/ @James-Frowen /types/workbox-sw/ @wessberg @@ -4896,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 @@ -4905,20 +5293,23 @@ /types/xsockets/ @pushplay /types/xxhashjs/ @mDibyo /types/yallist/ @BendingBender +/types/yaml/ @ikatyang @ColinBradley /types/yandex-maps/ @Delagen /types/yandex-money-sdk/ @chrootsu /types/yar/ @SimonSchick /types/yargs/v8/ @poelstra @mizunashi-mana @pushplay @jeffkenney /types/yargs/v10/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC /types/yargs/v11/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC -/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC +/types/yargs/ @poelstra @mizunashi-mana @pushplay @jeffkenney @JimiC @tkazec /types/yargs-interactive/ @szeck87 +/types/yargs-parser/ @milesj /types/yauzl/ @ffflorian /types/yauzl-promise/ @dlee-nvisia /types/yayson/ @Codesleuth -/types/yazl/ @taoqf +/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 @@ -4927,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 +/types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 /types/z-schema/ @pgonzal /types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp @@ -4943,6 +5334,7 @@ /types/zeromq/ @davemckeown @erikma @TitaneBoy /types/zip-webpack-plugin/ @blaise-io /types/zip.js/ @lgrignon +/types/zipcelx/ @aleburato /types/zipcodes/ @headdetect @dobesv /types/zipkin-context-cls/ @plantain-00 /types/zipkin-instrumentation-express/ @plantain-00 @@ -4952,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/.gitignore b/.gitignore index ac63b6f6b5..079ad27699 100644 --- a/.gitignore +++ b/.gitignore @@ -46,6 +46,7 @@ npm-debug.log .settings/launch.json .vs .vscode +.history # yarn yarn.lock diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000000..9cf9495031 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +package-lock=false \ No newline at end of file diff --git a/README.es.md b/README.es.md index c3cff967db..df675cbe41 100644 --- a/README.es.md +++ b/README.es.md @@ -22,15 +22,15 @@ Este es el método preferido. Solo está disponible para usuarios TypeScript 2.0 npm install --save-dev @types/node ``` -Los types deberían ser incluidos automaticamente por el compilador. +Los types deberían ser incluidos automáticamente por el compilador. Vea más en el [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/consumption.html). -Para un paquete NPM "foo", Estos `typings` estarán en "@types/foo". +Para un paquete NPM "foo", estos `typings` estarán en "@types/foo". Si no puedes encontrar tu paquete, búscalo en [TypeSearch](https://microsoft.github.io/TypeSearch/). Si aún no puedes encontrarlo, comprueba si el paquete ya [incluye](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) los typings. Esto es provisto usualmente en el campo `"types"` o `"typings"` en el `package.json`, -o solo busca por cualquier archivo ".d.ts" en el paquete e incluyelo manualmente con un `/// `. +o solo busca por cualquier archivo ".d.ts" en el paquete e inclúyelo manualmente con un `/// `. ### Otros métodos @@ -39,7 +39,7 @@ Estos pueden ser utilizados por TypeScript 1.0. * [Typings](https://github.com/typings/typings) * ~~[NuGet](http://nuget.org/packages?q=DefinitelyTyped)~~ (use las alternativas preferidas, la publicación DT type de nuget ha sido desactivada) -* Descarguelo manualmente desde la `master` branch de este repositorio +* Descárguelo manualmente desde la `master` branch de este repositorio Tal vez debas añadir manualmente las [referencias](http://www.typescriptlang.org/docs/handbook/triple-slash-directives.html). @@ -88,7 +88,7 @@ Primero, haz un [fork](https://guides.github.com/activities/forking/) en este re * `cd types/my-package-to-edit` * Haz cambios. Recuerda editar las pruebas. Si realiza cambios importantes, no olvide [actualizar una versión principal](#quiero-actualizar-un-paquete-a-una-nueva-versión-principal). -* También puede que quieras añadirte la sección "Definitions by" en el encabezado del paquete. +* También puede que quieras añadirle la sección "Definitions by" en el encabezado del paquete. - Esto hará que seas notificado (a través de tu nombre de usuario en GitHub) cada vez que alguien haga un pull request o issue sobre el paquete. - Haz esto añadiendo tu nombre al final de la línea, así como en `// Definitions by: Alice , Bob `. - O si hay más personas, puede ser multiline @@ -109,7 +109,7 @@ Si no lo hace, puedes hacerlo en el comentario asociado con el PR. Si eres el autor de la librería, o puedes hacer un pull request a la biblioteca, [bundle types](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) en vez de publicarlo en DefinitelyTyped. Si estás agregando typings para un paquete NPM, crea un directorio con el mismo nombre. -Si el paquete al que le estás agregando typings no es para NPM, asegurate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM. +Si el paquete al que le estás agregando typings no es para NPM, asegúrate de que el nombre que escojas no genere problemas con el nombre del paquete en NPM. (Puedes usar `npm info foo` para verificar la existencia del paquete `foo`.) Tu paquete debería tener esta estructura: @@ -126,7 +126,7 @@ Ve todas las opciones en [dts-gen](https://github.com/Microsoft/dts-gen). También puedes configurar el `tsconfig.json` para añadir nuevos archivos, para agregar un `"target": "es6"` (necesitado por las funciones asíncronas), para agregar a la `"lib"`, o para agregar la opción de compilación `"jsx"`. -Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrian ralentizar el proceso. +Los miembros de DefinitelyTyped frecuentemente monitorean nuevos PRs, pero ten en mente que la cantidad de PRs podrían ralentizar el proceso. Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js). @@ -135,7 +135,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy * Primero, sigue el consejo del [manual](http://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html). * Formatear: Ya sea utilizar todo en tabs, o siempre utiliza 4 espacios. -* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una funcion no escribe a sus parámetros. +* `function sum(nums: number[]): number`: Utiliza `ReadonlyArray` si una función no escribe a sus parámetros. * `interface Foo { new(): Foo; }`: Este define el tipo de objeto que esten nuevos. Probablemente quieras `declare class Foo { constructor(); }`. * `const Class: { new(): IClass; }`: @@ -146,7 +146,7 @@ Para un buen paquete de ejemplo, vea [base64-js](https://github.com/DefinitelyTy Un ejemplo donde un tipo de parámetro es aceptable: `function id(value: T): T;`. Un ejemplo donde no es aceptable: `function parseJson(json: string): T;`. Una excepción: `new Map()` está bien. -* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más especifico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`. +* Utilizando los tipos `Function` y `Object` casi nunca es una buena idea. En 99% de los casos es posible especificar un tipo más específico. Los ejemplos son `(x: number) => number` para [funciones](http://www.typescriptlang.org/docs/handbook/functions.html#function-types) y `{ x: number, y: number }` para objetos. Si no hay certeza en lo absoluto del tipo, [`any`](http://www.typescriptlang.org/docs/handbook/basic-types.html#any) es la opción correcta, no `Object`. Si el único hecho conocido sobre el tipo es que es un objecto, usa el tipo [`object`](https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-2.html#object-type), no `Object` o `{ [key: string]: any }`. * `var foo: string | any`: Cuando es usado `any` en un tipo de unión, el tipo resultante todavía es `any`. Así que mientras la porción `string` de este tipo de anotación puede _verse_ útil, de hecho, no ofrece ningún typechecking adicional más que un simple `any`. Dependiendo de la intención, una alternativa aceptable puede ser `any`, `string`, o `string | object`. @@ -204,11 +204,11 @@ Este script utiliza [dtslint](https://github.com/Microsoft/dtslint). #### ¿Cuál es exactamente la relación entre este repositorio y los paquetes de `@types` en NPM? -La `master` branch es automaticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher). +La `master` branch es automáticamente publicada en el alcance de los `@types` en NPM gracias a los [types-publisher](https://github.com/Microsoft/types-publisher). #### He enviado un pull request. ¿Cuánto tardará en ser merged? -Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprovados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor se paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan on los PRs abiertos. +Esto depende, pero la mayoría de los pull requests serán merged en alrededor de una semana. PRs que hayan sido aprobados por un autor listado en el encabezado de las definiciones usualmente son merged más rápidamente; PRs para nuevas definiciones tomarán más tiempo ya que requieren más revisiones de los mantenedores. Cada PR es revisado por un miembro de TypeScript o DefinitelyTyped antes de ser merged, por favor sé paciente debido a que factores humanos pueden causar retrasos. Revisa el [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) para ver el progreso mientras los mantenedores trabajan en los PRs abiertos. #### Mi PR ha sido merged; ¿cuándo será actualizado el paquete de `@types` NPM? @@ -216,12 +216,12 @@ Los paquetes NPM deberán ser actualizados en unas cuantas horas. Si ha pasado m #### Estoy escribiendo una definición que depende de otra definición. Debería utilizar `` o una import? -Si el modulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import. +Si el módulo al cual te estás refiriendo es un módulo externo (utiliza `export`), utilice una import. Si el módulo al cual te refieres es un módulo ambiente (utiliza `declare module`, o simplemente declara las globales), utilice ``. #### He notado que algunos paquetes aquí tienen `package.json`. -Normalmente no lo necesitaras. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso. +Normalmente no lo necesitarás. Cuando publicas un paquete normalmente nosotros automáticamente crearemos un `package.json` para eso. Un `package.json` puede ser incluido por el bien de especificar dependencias. Aquí tienen un [ejemplo](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/pikaday/package.json). No aceptamos otros campos, tales como `"description"`, para que sean definidos manualmente. Además, si necesitas referencia a una versión anterior de typings, debes hacerlo añadiendo `"dependencies": { "@types/foo": "x.y.z" }` al package.json. @@ -260,7 +260,7 @@ Cuando ya no sea un borrador, lo podremos eliminar desde DefinitelyType y hacer Si planeas continuar actualizando la versión anterior del paquete, puedes crear una subcarpeta con la versión actual p.ej. `v2`, y copia los archivos existentes. Si es así, necesitarás: 1. Actualiza las rutas relativas en `tsconfig.json` al igual que `tslint.json`. -2. Añadir reglas de mapeo de rutas para asegurart de que la prueba se está ejecutando contra la versión prevista. +2. Añadir reglas de mapeo de rutas para asegurarte de que la prueba se está ejecutando contra la versión prevista. Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/history/v2/tsconfig.json) se ve así: @@ -280,24 +280,24 @@ Por ejemplo [history v2 `tsconfig.json`](https://github.com/DefinitelyTyped/Defi } ``` -Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitaras mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior. +Si hay otros paquetes en DefinitelyTyped que son incompatibles con la nueva versión, necesitarás mapear las rutas a la versión anterior. También deberá hacer esto para los paquetes que dependen de paquetes que dependen de una version anterior. Por ejemplo, `react-router` depende de `history@2`, así que [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/tsconfig.json) tiene una ruta mapeada a "history": `[ "history/v2" ]`; transitivo así mismo, `react-router-bootstrap` (que depende de `react-router`) también añade una ruta mapeada en su [tsconfig.json](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router-bootstrap/tsconfig.json). -Además, `/// ` no trabajara con rutas mapeadas, así que las dependencias deberán utilizar `import`. +Además, `/// ` no trabajará con rutas mapeadas, así que las dependencias deberán utilizar `import`. #### ¿Cómo escribo definitions para paquetes que pueden ser usados globalmente y como un módulo? -El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), ademas [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada practicamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a travéz de una etiqueta script en una página web, o importada via require o imports estilo ES6. +El manual de TypeScript contiene excelente [información general para escribir definiciones](https://www.typescriptlang.org/docs/handbook/declaration-files/introduction.html), además [este archivo de definiciones de ejemplo](https://www.typescriptlang.org/docs/handbook/declaration-files/templates/global-modifying-module-d-ts.html) el cual muestra como crear una definición utilizando la sintaxis de módulo en ES6, asi como también especificando objetos que son disponibles en el alcance global. Esta técnica es demostrada prácticamente en la [definición para big.js](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/big.js/index.d.ts), el cual es una librería que puede ser cargada globalmente a través de una etiqueta script en una página web, o importada vía require o imports estilo ES6. -Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas un propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js. +Para probar como puede ser usada tu definición cuando se refieren globalmente o como un módulo importado, crea una carpeta `test`, y coloca dos archivos de prueba en él. nombra uno `YourLibraryName-global.test.ts` y el otro `YourLibraryName-module.test.ts`. El archivo de prueba _global_ debe ejercer la definición de acuerdo como va a ser usado en un script cargado en una página web donde la librería estará disponible en el alcance global - en este escenario no debes de especificar la sentencia de import. El archivo _módulo_ de prueba debe de ejercer la definición de acuerdo a como va a ser utilizado cuando sea importado (incluyendo las sentencias `import`). Si especificas una propiedad `files` en tu archivo tsconfig.json, asegurate de incluir ambos archivos de prueba. Un [ejemplo práctico de esto](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/big.js/test) es también disponible en la definición de big.js. Por favor tenga en cuenta que no es necesario para ejercer plenamente la definición en cada archivo de prueba - Es suficiente con probar solo los elementos globalmente accesibles en la prueba de archivos globales y ejercer la definición en el módulo del archivo de prueba, o viceversa. #### ¿Qué pasa con paquetes scoped? -Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guion bajo. +Types para un paquete scoped `@foo/bar` deberán ir en `types/foo__bar`. tenga en cuenta el doble guión bajo. Cuando `dts-gen` es utilizado como scaffold en un paquete scoped, las propiedades `paths` deberán ser adaptadas manualmente en el paquete generado `tsconfig.json` para referenciar correctamente el paquete scoped: diff --git a/README.md b/README.md index 9a31d73da1..eba170c493 100644 --- a/README.md +++ b/README.md @@ -336,3 +336,6 @@ This project is licensed under the MIT license. Copyrights on the definition files are respective of each contributor listed at the beginning of each definition file. [![Analytics](https://ga-beacon.appspot.com/UA-47495295-4/borisyankov/DefinitelyTyped)](https://github.com/igrigorik/ga-beacon) + +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.types-publisher-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=13) Are packages being published to npm in less than 10,000 seconds on average? +[![Build Status](https://typescript.visualstudio.com/TypeScript/_apis/build/status/sandersn.typescript-bot-watchdog)](https://typescript.visualstudio.com/TypeScript/_build/latest?definitionId=14) Has typescript-bot been active on DefinitelyTyped in the last two hours? diff --git a/notNeededPackages.json b/notNeededPackages.json index 968192123b..c64738aa8d 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -144,6 +144,12 @@ "sourceRepoURL": "https://github.com/Azure/azure-mobile-apps-node/", "asOfVersion": "3.0.0" }, + { + "libraryName": "@babel/parser", + "typingsPackageName": "babel__parser", + "sourceRepoURL": "https://github.com/babel/babel", + "asOfVersion": "7.1.0" + }, { "libraryName": "BabylonJS", "typingsPackageName": "babylonjs", @@ -396,6 +402,12 @@ "sourceRepoURL": "https://github.com/MikeMcl/decimal.js", "asOfVersion": "7.4.0" }, + { + "libraryName": "deepmerge", + "typingsPackageName": "deepmerge", + "sourceRepoURL": "git@github.com:KyleAMathews/deepmerge.git", + "asOfVersion": "2.2.0" + }, { "libraryName": "delay", "typingsPackageName": "delay", @@ -534,6 +546,12 @@ "sourceRepoURL": "https://github.com/code-chris/extended-listbox", "asOfVersion": "4.0.1" }, + { + "libraryName": "fast-diff", + "typingsPackageName": "fast-diff", + "sourceRepoURL": "https://github.com/jhchen/fast-diff", + "asOfVersion": "1.2.0" + }, { "libraryName": "JSON-Patch", "typingsPackageName": "fast-json-patch", @@ -618,6 +636,18 @@ "sourceRepoURL": "https://github.com/mikedeboer/node-github", "asOfVersion": "7.1.0" }, + { + "libraryName": "gitlab", + "typingsPackageName": "gitlab", + "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", @@ -924,12 +954,24 @@ "sourceRepoURL": "https://github.com/blakeembrey/lower-case-first", "asOfVersion": "1.0.1" }, + { + "libraryName": "mali", + "typingsPackageName": "mali", + "sourceRepoURL": "https://github.com/malijs/mali", + "asOfVersion": "0.9.2" + }, { "libraryName": "maquette", "typingsPackageName": "maquette", "sourceRepoURL": "http://maquettejs.org/", "asOfVersion": "2.1.6" }, + { + "libraryName": "maxmind", + "typingsPackageName": "maxmind", + "sourceRepoURL": "https://github.com/runk/node-maxmind", + "asOfVersion": "2.0.5" + }, { "libraryName": "mendixmodelsdk", "typingsPackageName": "mendixmodelsdk", @@ -966,6 +1008,12 @@ "sourceRepoURL": "https://github.com/mweststrate/mobservable-react", "asOfVersion": "1.0.0" }, + { + "libraryName": "Mobx Cookie", + "typingsPackageName": "mobx-cookie", + "sourceRepoURL": "https://github.com/will-stone/mobx-cookie", + "asOfVersion": "1.1.1" + }, { "libraryName": "Moment", "typingsPackageName": "moment", @@ -1194,6 +1242,12 @@ "sourceRepoURL": "https://github.com/react-ga/react-ga", "asOfVersion": "2.3.0" }, + { + "libraryName": "react-i18next", + "typingsPackageName": "react-i18next", + "sourceRepoURL": "https://github.com/i18next/react-i18next", + "asOfVersion": "8.1.0" + }, { "libraryName": "react-monaco-editor", "typingsPackageName": "react-monaco-editor", @@ -1608,6 +1662,12 @@ "sourceRepoURL": "https://github.com/ansman/validate.js", "asOfVersion": "0.11.0" }, + { + "libraryName": "vega", + "typingsPackageName": "vega", + "sourceRepoURL": "https://github.com/vega/vega", + "asOfVersion": "3.2.0" + }, { "libraryName": "vso-node-api", "typingsPackageName": "vso-node-api", 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/a11y-dialog/a11y-dialog-tests.ts b/types/a11y-dialog/a11y-dialog-tests.ts new file mode 100644 index 0000000000..3df694fcdd --- /dev/null +++ b/types/a11y-dialog/a11y-dialog-tests.ts @@ -0,0 +1,30 @@ +import A11yDialog = require('a11y-dialog'); + +const dialogEl = new A11yDialog(document.getElementById("test")); +const dialogElTwo = new A11yDialog(document.getElementById("test"), document.getElementById("testContainer")); +const dialogElThree = new A11yDialog(document.getElementById("test"), "dummy-element"); + +dialogEl.show(); +dialogEl.hide(); +dialogElTwo.destroy(); +dialogElThree.create(); + +// Test out interfaces that extends Element. +dialogEl.on("show", (el: HTMLElement) => { + el.textContent; +}); + +// Test out element and event. +dialogEl.on("create", (el: HTMLElement, evt) => { + el.textContent; + + evt.target; +}); + +dialogEl.on('hide', () => { + const t = 5; +}); + +dialogEl.off("show", (el: HTMLElement) => { + el.textContent; +}); diff --git a/types/a11y-dialog/index.d.ts b/types/a11y-dialog/index.d.ts new file mode 100644 index 0000000000..105aaa70e7 --- /dev/null +++ b/types/a11y-dialog/index.d.ts @@ -0,0 +1,31 @@ +// Type definitions for a11y-dialog 5.2 +// Project: https://github.com/edenspiekermann/a11y-dialog +// Definitions by: Yuto +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +type DialogEvents = "show" | "hide" | "destroy" | "create"; +declare class A11yDialog { + constructor(el: Element | null, containers?: NodeList | Element | string | null); + /** + * Shows the dialog. + */ + show(): void; + /** + * Hides the dialog. + */ + hide(): void; + /** + * Unbind click listeners from dialog openers and closers and remove all bound custom event listeners registered with `.on()` + */ + destroy(): void; + /** + * Bind click listeners to dialog openers and closers. + */ + create(el?: Element | null, containers?: NodeList | Element | string | null): void; + + on(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void; + off(evt: DialogEvents, callback: (dialogElement: any, event: Event) => void): void; +} + +export = A11yDialog; diff --git a/types/a11y-dialog/tsconfig.json b/types/a11y-dialog/tsconfig.json new file mode 100644 index 0000000000..a27d99d6bf --- /dev/null +++ b/types/a11y-dialog/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", + "a11y-dialog-tests.ts" + ] +} \ No newline at end of file diff --git a/types/a11y-dialog/tslint.json b/types/a11y-dialog/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/a11y-dialog/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file 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/gitlab/tsconfig.json b/types/accept/tsconfig.json similarity index 94% rename from types/gitlab/tsconfig.json rename to types/accept/tsconfig.json index f1297faf67..cb192697d5 100644 --- a/types/gitlab/tsconfig.json +++ b/types/accept/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "gitlab-tests.ts" + "accept-tests.ts" ] } diff --git a/types/babel__parser/tslint.json b/types/accept/tslint.json similarity index 100% rename from types/babel__parser/tslint.json rename to types/accept/tslint.json diff --git a/types/aframe/test/aframe-io-tests.ts b/types/aframe/test/aframe-io-tests.ts index 77fe716390..1120b50be8 100644 --- a/types/aframe/test/aframe-io-tests.ts +++ b/types/aframe/test/aframe-io-tests.ts @@ -533,9 +533,10 @@ AFRAME.registerComponent('audioanalyser-waveform', { rings.forEach(function transformRing(ring: THREE.Line, index: number) { var normLevel; normLevel = levels[RINGCOUNT - index - 1] + 0.01; // Avoid scaling by 0. - (ring.material as THREE.LineBasicMaterial).color.setHSL(colors[index], 1, normLevel); - ring.material.linewidth = normLevel * 3; - ring.material.opacity = normLevel; + const lineMaterial = ring.material as THREE.LineBasicMaterial; + lineMaterial.color.setHSL(colors[index], 1, normLevel); + lineMaterial.linewidth = normLevel * 3; + lineMaterial.opacity = normLevel; ring.scale.z = normLevel; }); }, diff --git a/types/agenda/index.d.ts b/types/agenda/index.d.ts index 75246ecda3..37b9ce6b2c 100644 --- a/types/agenda/index.d.ts +++ b/types/agenda/index.d.ts @@ -64,7 +64,7 @@ declare class Agenda extends EventEmitter { defaultConcurrency(value: number): this; /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is * 0 for no max. * @param value The value to set. */ @@ -189,7 +189,7 @@ declare namespace Agenda { defaultLockLimit?: number; /** - * Takes a number shich specifies the max number jobs that can be locked at any given moment. By default it is + * Takes a number which specifies the max number jobs that can be locked at any given moment. By default it is * 0 for no max. */ lockLimit?: number; diff --git a/types/ajv-errors/index.d.ts b/types/ajv-errors/index.d.ts index fed9e4585f..3b5c2d2322 100644 --- a/types/ajv-errors/index.d.ts +++ b/types/ajv-errors/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/epoberezkin/ajv-errors // Definitions by: Afshawn Lotfi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 import { Ajv } from "ajv"; diff --git a/types/ale-url-parser/ale-url-parser-tests.ts b/types/ale-url-parser/ale-url-parser-tests.ts new file mode 100644 index 0000000000..2a5d9fe632 --- /dev/null +++ b/types/ale-url-parser/ale-url-parser-tests.ts @@ -0,0 +1,22 @@ +import { parse, stringify } from 'ale-url-parser'; + +let url; +let urlObject; + +url = stringify({}); +console.log(url); + +url = stringify({ + protocol: 'protocol', + host: 'host', + path: ['foo', 'bar', 'baz'], + hash: 'hash', + query: { + foo: 1, + bar: [2, '3'] + } +}); +console.log(url); + +urlObject = parse('//any.dom.ain.co.m/foo/bar?test=1&test=2#hash'); +console.log(urlObject); diff --git a/types/ale-url-parser/index.d.ts b/types/ale-url-parser/index.d.ts new file mode 100644 index 0000000000..31b2d2fd03 --- /dev/null +++ b/types/ale-url-parser/index.d.ts @@ -0,0 +1,29 @@ +// Type definitions for ale-url-parser 0.10 +// Project: https://github.com/msn0/ale-url-parser#readme +// Definitions by: Michał Jezierski +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export interface QueryParams { + [key: string]: any; +} + +export interface UrlObject { + protocol?: string; + host?: string; + path?: string[]; + query?: QueryParams; + hash?: string; +} + +/** + * Parse url string into url object. + * @return UrlObject + */ +export function parse(url: string): UrlObject; + +/** + * Stringify url object into url string. + * @return string + */ +export function stringify(urlObject: UrlObject): string; diff --git a/types/ale-url-parser/tsconfig.json b/types/ale-url-parser/tsconfig.json new file mode 100644 index 0000000000..2d18200901 --- /dev/null +++ b/types/ale-url-parser/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", + "ale-url-parser-tests.ts" + ] +} diff --git a/types/deepmerge/tslint.json b/types/ale-url-parser/tslint.json similarity index 100% rename from types/deepmerge/tslint.json rename to types/ale-url-parser/tslint.json diff --git a/types/algoliasearch/algoliasearch-tests.ts b/types/algoliasearch/algoliasearch-tests.ts index b148e84599..cbd98d253a 100644 --- a/types/algoliasearch/algoliasearch-tests.ts +++ b/types/algoliasearch/algoliasearch-tests.ts @@ -21,6 +21,7 @@ let _algoliaResponse: Response = { processingTimeMS: 32, query: '', params: '', + index: '', }; let _clientOptions: ClientOptions = { @@ -103,7 +104,7 @@ let _algoliaQueryParameters: QueryParameters = { filters: '', attributesToRetrieve: [''], restrictSearchableAttributes: [''], - facets: '', + facets: [''], facetingAfterDistinct: true, maxValuesPerFacet: 2, attributesToHighlight: [''], @@ -121,28 +122,29 @@ let _algoliaQueryParameters: QueryParameters = { typoTolerance: false, allowTyposOnNumericTokens: false, ignorePlurals: false, - disableTypoToleranceOnAttributes: '', + disableTypoToleranceOnAttributes: [''], aroundLatLng: '', aroundLatLngViaIP: '', aroundRadius: 0, aroundPrecision: 0, minimumAroundRadius: 0, insideBoundingBox: [[0]], - queryType: '', + queryType: 'prefixAll', insidePolygon: [[0]], - removeWordsIfNoResults: '', + removeWordsIfNoResults: 'firstWords', advancedSyntax: false, optionalWords: [''], removeStopWords: [''], disableExactOnAttributes: [''], - exactOnSingleWordQuery: '', - alternativesAsExact: true, + exactOnSingleWordQuery: 'attribute', + alternativesAsExact: ["ignorePlurals"], distinct: 0, getRankingInfo: false, numericAttributesToIndex: [''], + numericAttributesForFiltering: [''], numericFilters: [''], - tagFilters: '', - facetFilters: '', + tagFilters: [''], + facetFilters: [''], analytics: false, analyticsTags: [''], synonyms: true, @@ -172,8 +174,38 @@ index.partialUpdateObjects([{}], false).then(() => {}); let indexName : string = index.indexName; // complete copy -client.copyIndex('from', 'to').then(()=>{}) -client.copyIndex('from', 'to', ()=> {}) +client.copyIndex('from', 'to').then(()=>{}); +client.copyIndex('from', 'to', ()=> {}); // with scope -client.copyIndex('from', 'to', ['settings']).then(()=>{}) -client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}) +client.copyIndex('from', 'to', ['settings']).then(()=>{}); +client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}); + +// Browsing +const browser = index.browseAll(); +index.browseAll('query'); +index.browseAll('', { + filters: 'dog', +}); + +let hits: Object[] = []; + +browser.on('result', function onResult(content) { + hits = hits.concat(content.hits); +}); + +browser.on('end', function onEnd() { + const _message = `We got ${hits.length} hits` +}); + +browser.on('error', function onError(err) { + throw err; +}); + +browser.stop(); + +index.browse("", { + advancedSyntax: false, + attributesToRetrieve: ['dogs'] +}); +client.copyIndex('from', 'to', ['settings']).then(()=>{}); +client.copyIndex('from', 'to', ['synonyms', 'rules'], ()=> {}); diff --git a/types/algoliasearch/index.d.ts b/types/algoliasearch/index.d.ts index a0bb0e0e45..04291996ba 100644 --- a/types/algoliasearch/index.d.ts +++ b/types/algoliasearch/index.d.ts @@ -1,11 +1,14 @@ -// Type definitions for algoliasearch-client-js 3.27.0 +// Type definitions for algoliasearch-client-js 3.30.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene // Aurélien Hervé // Samuel Vaillant +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.8 + +type Omit = Pick> declare namespace algoliasearch { /** @@ -611,6 +614,11 @@ declare namespace algoliasearch { options: SearchForFacetValues.Parameters, cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -620,7 +628,7 @@ declare namespace algoliasearch { * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string, parameters?: BrowseParameters): Promise; /** * Browse an index from a cursor * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -638,7 +646,7 @@ declare namespace algoliasearch { * Browse an entire index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browseAll(): Promise; + browseAll(query?: string, parameters?: BrowseParameters): Browser; /** * Clear an index content * https://github.com/algolia/algoliasearch-client-js#clear-index---clearindex @@ -966,6 +974,22 @@ declare namespace algoliasearch { query: string; processingTimeMS: number; } + type BrowseParameters = Omit< + QueryParameters, + | "typoTolerance" + | "distinct" + | "facets" + | "getRankingInfo" + | "attributesToHighlight" + | "attributesToSnippet" + > + interface Browser { + on(type: "error", cb: (err: Error) => void): void + on(type: "end", cb: () => void): void + on(type: "stop", cb: () => void): void + on(type: "result", cb: (content: BrowseResponse) => void): void + stop(): void + } /** * Describes a synonym object */ @@ -1099,120 +1123,121 @@ declare namespace algoliasearch { userToken?: string; } interface QueryParameters { + /** + * Query string used to perform the search + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/query/ + */ + query?: string; + /** + * Filter the query with numeric, facet or/and tag filters + * default: "" + * https://www.algolia.com/doc/api-reference/api-parameters/filters/ + */ + filters?: string; + /** + * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. + * default: * + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/ + */ + attributesToRetrieve?: string[]; + /** + * List of attributes you want to use for textual search + * default: attributeToIndex + * https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/ + */ + restrictSearchableAttributes?: string[]; + /** + * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facets/ + */ + facets?: string[]; /** - * Query string used to perform the search - * default: '' - * https://github.com/algolia/algoliasearch-client-js#query - */ - query?: string; - /** - * Filter the query with numeric, facet or/and tag filters - * default: "" - * https://github.com/algolia/algoliasearch-client-js#filters - */ - filters?: string; - /** - * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. - * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve - */ - attributesToRetrieve?: string[]; - /** - * List of attributes you want to use for textual search - * default: attributeToIndex - * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes - */ - restrictSearchableAttributes?: string[]; - /** - * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes - * default: "" - * https://github.com/algolia/algoliasearch-client-js#facets - */ - facets?: string | string[]; - /** * Force faceting to be applied after de-duplication (via the Distinct setting). - * When using the distinct setting in combination with faceting, facet counts may be higher than expected. - * This is because the engine, by default, computes faceting before applying de-duplication (distinct). + * When using the distinct setting in combination with faceting, facet counts may be higher than expected. + * This is because the engine, by default, computes faceting before applying de-duplication (distinct). * When facetingAfterDistinct is set to true, the engine calculates faceting after the de-duplication has been applied. * default "" + * https://www.algolia.com/doc/api-reference/api-parameters/facetingAfterDistinct/ */ facetingAfterDistinct?: boolean; /** * Limit the number of facet values returned for each facet. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + * default: 100 + * https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/ */ maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/ */ attributesToHighlight?: string[]; /** * Default list of attributes to snippet alongside the number of words to return * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/ */ attributesToSnippet?: string[]; /** * Specify the string that is inserted before the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/ */ highlightPreTag?: string; /** * Specify the string that is inserted after the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/ */ highlightPostTag?: string; /** * String used as an ellipsis indicator when a snippet is truncated. * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + * https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/ */ snippetEllipsisText?: string; /** * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + * https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/ */ restrictHighlightAndSnippetArrays?: boolean; /** * Pagination parameter used to select the number of hits per page * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage + * https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/ */ hitsPerPage?: number; /** * Pagination parameter used to select the page to retrieve. * default: 0 - * https://github.com/algolia/algoliasearch-client-js#page + * https://www.algolia.com/doc/api-reference/api-parameters/page/ */ page?: number; /** * Offset of the first hit to return * default: null - * https://github.com/algolia/algoliasearch-client-js#offset + * https://www.algolia.com/doc/api-reference/api-parameters/offset/ */ offset?: number; /** * Number of hits to return. * default: null - * https://github.com/algolia/algoliasearch-client-js#length + * https://www.algolia.com/doc/api-reference/api-parameters/length/ */ length?: number; /** * The minimum number of characters needed to accept one typo. * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/ */ minWordSizefor1Typo?: number; /** * The minimum number of characters needed to accept two typo. * fault: 8 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/ */ minWordSizefor2Typos?: number; /** @@ -1222,62 +1247,62 @@ declare namespace algoliasearch { * 'false' The typo tolerance is disabled. All results with typos will be hidden. * 'min' Only keep results with the minimum number of typos * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/ */ typoTolerance?: boolean; /** * If set to false, disables typo tolerance on numeric tokens (numbers). * default: - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + * https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/ */ allowTyposOnNumericTokens?: boolean; /** * If set to true, plural won't be considered as a typo * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + * https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/ */ ignorePlurals?: boolean; /** * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/ */ - disableTypoToleranceOnAttributes?: string; + disableTypoToleranceOnAttributes?: string[]; /** * Search for entries around a given location * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/ */ aroundLatLng?: string; /** * Search for entries around a given latitude/longitude automatically computed from user IP address. * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/ */ aroundLatLngViaIP?: string; /** * Control the radius associated with a geo search. Defined in meters. * default: null * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area - * https://github.com/algolia/algoliasearch-client-js#aroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/ */ aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null - * https://github.com/algolia/algoliasearch-client-js#aroundprecision + * https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/ */ aroundPrecision?: number; /** * Define the minimum radius used for a geo search when aroundRadius is not set. * default: null - * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/ */ minimumAroundRadius?: number; /** * Search entries inside a given area defined by the two extreme points of a rectangle * default: null - * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + * https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/ */ insideBoundingBox?: number[][]; /** @@ -1286,13 +1311,13 @@ declare namespace algoliasearch { * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype + * https://www.algolia.com/doc/api-reference/api-parameters/queryType/ */ - queryType?: any; + queryType?: "prefixAll"|"prefixLast"|"prefixNone"; /** * Search entries inside a given area defined by a set of points * defauly: '' - * https://github.com/algolia/algoliasearch-client-js#insidepolygon + * https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/ */ insidePolygon?: number[][]; /** @@ -1302,19 +1327,19 @@ declare namespace algoliasearch { * 'firstWords' When a query does not return any results, the first word will be added as optional * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + * https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/ */ - removeWordsIfNoResults?: string; + removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional"; /** * Enables the advanced query syntax * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + * https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/ */ advancedSyntax?: boolean; /** * A string that contains the comma separated list of words that should be considered as optional when found in the query * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords + * https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/ */ optionalWords?: string[]; /** @@ -1322,13 +1347,13 @@ declare namespace algoliasearch { * default: false * true|false: enable or disable stop words for all 41 supported languages; or * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords + * https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/ */ - removeStopWords?: string[]; + removeStopWords?: boolean|string[]; /** * List of attributes on which you want to disable the computation of exact criteria * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + * https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/ */ disableExactOnAttributes?: string[]; /** @@ -1337,81 +1362,90 @@ declare namespace algoliasearch { * 'none': no exact on single word query * 'word': exact set to 1 if the query word is found in the record * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + * https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/ */ - exactOnSingleWordQuery?: string; + exactOnSingleWordQuery?: "attribute"|"none"|"word"; /** * Specify the list of approximation that should be considered as an exact match in the ranking formula * default: ['ignorePlurals', 'singleWordSynonym'] * 'ignorePlurals': alternative words added by the ignorePlurals feature * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + * https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/ */ - alternativesAsExact?: any; + alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">; /** * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct + * https://www.algolia.com/doc/api-reference/api-parameters/distinct/ */ - distinct?: any; + distinct?: number|boolean; /** * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. * default: false - * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + * https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/ */ getRankingInfo?: boolean; /** + * @deprecated Use `numericAttributesForFiltering` instead * All numerical attributes are automatically indexed as numerical filters * default: '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ */ numericAttributesToIndex?: string[]; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ + */ + numericAttributesForFiltering?: string[]; /** * @deprecated please use filters instead * A string that contains the comma separated list of numeric filters you want to apply. - * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + * https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/ */ numericFilters?: string[]; /** * @deprecated + * * Filter the query by a set of tags. - * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/ */ - tagFilters?: string; + tagFilters?: string[]; /** - * @deprecated * Filter the query by a set of facets. - * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ */ - facetFilters?: string | string[] + facetFilters?: string[]|string[][]; /** * If set to false, this query will not be taken into account in the analytics feature. * default true - * https://github.com/algolia/algoliasearch-client-js#analytics + * https://www.algolia.com/doc/api-reference/api-parameters/analytics/ */ analytics?: boolean; /** * If set, tag your query with the specified identifiers - * default: null - * https://github.com/algolia/algoliasearch-client-js#analyticstags + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/ */ analyticsTags?: string[]; /** * If set to false, the search will not use the synonyms defined for the targeted index. * default: true - * https://github.com/algolia/algoliasearch-client-js#synonyms + * https://www.algolia.com/doc/api-reference/api-parameters/synonyms/ */ synonyms?: boolean; /** * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. * default: true - * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + * https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/ */ replaceSynonymsInHighlight?: boolean; /** * Configure the precision of the proximity ranking criterion * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity + * https://www.algolia.com/doc/api-reference/api-parameters/minProximity/ */ minProximity?: number; @@ -1464,7 +1498,7 @@ declare namespace algoliasearch { interface Task { taskID: number; createdAt: string; - objectID?: string; + objectID?: string; } interface TaskStatus { @@ -1747,42 +1781,42 @@ declare namespace algoliasearch { interface Response { /** * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hits: any[]; /** * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ page: number; /** * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbHits: number; /** * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbPages: number; /** * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hitsPerPage: number; /** * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ processingTimeMS: number; /** * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ query: string; /** * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ params: string; facets?: { @@ -1796,6 +1830,16 @@ declare namespace algoliasearch { sum: number, }; }; + /** + * The index name is only set when searching multiple indices. + * https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response + */ + index?: string; + /** + * The cursor is only set when browsing the index. + * https://www.algolia.com/doc/api-reference/api-methods/browse/ + */ + cursor?: string; } interface MultiResponse { diff --git a/types/algoliasearch/lite/index.d.ts b/types/algoliasearch/lite/index.d.ts index 4f068d5647..ce58d6a428 100644 --- a/types/algoliasearch/lite/index.d.ts +++ b/types/algoliasearch/lite/index.d.ts @@ -1,12 +1,15 @@ -// Type definitions for algoliasearch-client-js 3.27.0 +// Type definitions for algoliasearch-client-js 3.30.0 // Project: https://github.com/algolia/algoliasearch-client-js // Definitions by: Baptiste Coquelle // Haroen Viaene // Aurélien Hervé // Samuel Vaillant // Claas Brüggemann +// Kai Eichinger // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.8 + +type Omit = Pick> declare namespace algoliasearch { /** @@ -130,6 +133,11 @@ declare namespace algoliasearch { options: SearchForFacetValues.Parameters, cb: (err: Error, res: SearchForFacetValues.Response) => void ): void; + /** + * Browse an index + * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse + */ + browse(query: string, parameters: BrowseParameters, cb: (err: Error, res: BrowseResponse) => void): void; /** * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -139,7 +147,7 @@ declare namespace algoliasearch { * Browse an index * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse */ - browse(query: string): Promise; + browse(query: string, parameters?: BrowseParameters): Promise; /** * Browse an index from a cursor * https://github.com/algolia/algoliasearch-client-js#backup--export-an-index---browse @@ -194,114 +202,122 @@ declare namespace algoliasearch { query: string; processingTimeMS: number; } - + type BrowseParameters = Omit< + QueryParameters, + | "typoTolerance" + | "distinct" + | "facets" + | "getRankingInfo" + | "attributesToHighlight" + | "attributesToSnippet" + > interface QueryParameters { /** * Query string used to perform the search * default: '' - * https://github.com/algolia/algoliasearch-client-js#query + * https://www.algolia.com/doc/api-reference/api-parameters/query/ */ query?: string; /** * Filter the query with numeric, facet or/and tag filters * default: "" - * https://github.com/algolia/algoliasearch-client-js#filters + * https://www.algolia.com/doc/api-reference/api-parameters/filters/ */ filters?: string; /** * A string that contains the list of attributes you want to retrieve in order to minimize the size of the JSON answer. * default: * - * https://github.com/algolia/algoliasearch-client-js#attributestoretrieve + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToRetrieve/ */ attributesToRetrieve?: string[]; /** * List of attributes you want to use for textual search * default: attributeToIndex - * https://github.com/algolia/algoliasearch-client-js#restrictsearchableattributes + * https://www.algolia.com/doc/api-reference/api-parameters/restrictSearchableAttributes/ */ restrictSearchableAttributes?: string[]; /** * You can use facets to retrieve only a part of your attributes declared in attributesForFaceting attributes - * default: "" - * https://github.com/algolia/algoliasearch-client-js#facets + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facets/ */ - facets?: string; + facets?: string[]; /** * Limit the number of facet values returned for each facet. - * default: "" - * https://github.com/algolia/algoliasearch-client-js#maxvaluesperfacet + * default: 100 + * https://www.algolia.com/doc/api-reference/api-parameters/maxValuesPerFacet/ */ maxValuesPerFacet?: number; /** * Default list of attributes to highlight. If set to null, all indexed attributes are highlighted. * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestohighlight + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToHighlight/ */ attributesToHighlight?: string[]; /** * Default list of attributes to snippet alongside the number of words to return * default: null - * https://github.com/algolia/algoliasearch-client-js#attributestosnippet + * https://www.algolia.com/doc/api-reference/api-parameters/attributesToSnippet/ */ attributesToSnippet?: string[]; /** * Specify the string that is inserted before the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightpretag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPreTag/ */ highlightPreTag?: string; /** * Specify the string that is inserted after the highlighted parts in the query result * default: - * https://github.com/algolia/algoliasearch-client-js#highlightposttag + * https://www.algolia.com/doc/api-reference/api-parameters/highlightPostTag/ */ highlightPostTag?: string; /** * String used as an ellipsis indicator when a snippet is truncated. * default: … - * https://github.com/algolia/algoliasearch-client-js#snippetellipsistext + * https://www.algolia.com/doc/api-reference/api-parameters/snippetEllipsisText/ */ snippetEllipsisText?: string; /** * If set to true, restrict arrays in highlights and snippets to items that matched the query at least partially else return all array items in highlights and snippets * default: false - * https://github.com/algolia/algoliasearch-client-js#restricthighlightandsnippetarrays + * https://www.algolia.com/doc/api-reference/api-parameters/restrictHighlightAndSnippetArrays/ */ restrictHighlightAndSnippetArrays?: boolean; /** * Pagination parameter used to select the number of hits per page * default: 20 - * https://github.com/algolia/algoliasearch-client-js#hitsperpage + * https://www.algolia.com/doc/api-reference/api-parameters/hitsPerPage/ */ hitsPerPage?: number; /** * Pagination parameter used to select the page to retrieve. * default: 0 - * https://github.com/algolia/algoliasearch-client-js#page + * https://www.algolia.com/doc/api-reference/api-parameters/page/ */ page?: number; /** * Offset of the first hit to return * default: null - * https://github.com/algolia/algoliasearch-client-js#offset + * https://www.algolia.com/doc/api-reference/api-parameters/offset/ */ offset?: number; /** * Number of hits to return. * default: null - * https://github.com/algolia/algoliasearch-client-js#length + * https://www.algolia.com/doc/api-reference/api-parameters/length/ */ length?: number; /** * The minimum number of characters needed to accept one typo. * default: 4 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor1typo + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor1Typo/ */ minWordSizefor1Typo?: number; /** * The minimum number of characters needed to accept two typo. * fault: 8 - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/minWordSizefor2Typos/ */ minWordSizefor2Typos?: number; /** @@ -311,62 +327,62 @@ declare namespace algoliasearch { * 'false' The typo tolerance is disabled. All results with typos will be hidden. * 'min' Only keep results with the minimum number of typos * 'strict' Hits matching with 2 typos are not retrieved if there are some matching without typos. - * https://github.com/algolia/algoliasearch-client-js#minwordsizefor2typos + * https://www.algolia.com/doc/api-reference/api-parameters/typoTolerance/ */ typoTolerance?: boolean; /** * If set to false, disables typo tolerance on numeric tokens (numbers). * default: - * https://github.com/algolia/algoliasearch-client-js#allowtyposonnumerictokens + * https://www.algolia.com/doc/api-reference/api-parameters/allowTyposOnNumericTokens/ */ allowTyposOnNumericTokens?: boolean; /** * If set to true, plural won't be considered as a typo * default: false - * https://github.com/algolia/algoliasearch-client-js#ignoreplurals + * https://www.algolia.com/doc/api-reference/api-parameters/ignorePlurals/ */ ignorePlurals?: boolean; /** * List of attributes on which you want to disable typo tolerance - * default: "" - * https://github.com/algolia/algoliasearch-client-js#disabletypotoleranceonattributes + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/disableTypoToleranceOnAttributes/ */ - disableTypoToleranceOnAttributes?: string; + disableTypoToleranceOnAttributes?: string[]; /** * Search for entries around a given location * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlng + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLng/ */ aroundLatLng?: string; /** * Search for entries around a given latitude/longitude automatically computed from user IP address. * default: "" - * https://github.com/algolia/algoliasearch-client-js#aroundlatlngviaip + * https://www.algolia.com/doc/api-reference/api-parameters/aroundLatLngViaIP/ */ aroundLatLngViaIP?: string; /** * Control the radius associated with a geo search. Defined in meters. * default: null * You can specify aroundRadius=all if you want to compute the geo distance without filtering in a geo area - * https://github.com/algolia/algoliasearch-client-js#aroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/aroundRadius/ */ aroundRadius?: number | 'all'; /** * Control the precision of a geo search * default: null - * https://github.com/algolia/algoliasearch-client-js#aroundprecision + * https://www.algolia.com/doc/api-reference/api-parameters/aroundPrecision/ */ aroundPrecision?: number; /** * Define the minimum radius used for a geo search when aroundRadius is not set. * default: null - * https://github.com/algolia/algoliasearch-client-js#minimumaroundradius + * https://www.algolia.com/doc/api-reference/api-parameters/minimumAroundRadius/ */ minimumAroundRadius?: number; /** * Search entries inside a given area defined by the two extreme points of a rectangle * default: null - * https://github.com/algolia/algoliasearch-client-js#insideboundingbox + * https://www.algolia.com/doc/api-reference/api-parameters/insideBoundingBox/ */ insideBoundingBox?: number[][]; /** @@ -375,13 +391,13 @@ declare namespace algoliasearch { * 'prefixAll' All query words are interpreted as prefixes. This option is not recommended. * 'prefixLast' Only the last word is interpreted as a prefix (default behavior). * 'prefixNone' No query word is interpreted as a prefix. This option is not recommended. - * https://github.com/algolia/algoliasearch-client-js#querytype + * https://www.algolia.com/doc/api-reference/api-parameters/queryType/ */ - queryType?: any; + queryType?: "prefixAll"|"prefixLast"|"prefixNone"; /** * Search entries inside a given area defined by a set of points * defauly: '' - * https://github.com/algolia/algoliasearch-client-js#insidepolygon + * https://www.algolia.com/doc/api-reference/api-parameters/insidePolygon/ */ insidePolygon?: number[][]; /** @@ -391,19 +407,19 @@ declare namespace algoliasearch { * 'firstWords' When a query does not return any results, the first word will be added as optional * 'allOptional' When a query does not return any results, a second trial will be made with all words as optional * 'none' No specific processing is done when a query does not return any results - * https://github.com/algolia/algoliasearch-client-js#removewordsifnoresults + * https://www.algolia.com/doc/api-reference/api-parameters/removeWordsIfNoResults/ */ - removeWordsIfNoResults?: string; + removeWordsIfNoResults?: "none"|"lastWords"|"firstWords"|"allOptional"; /** * Enables the advanced query syntax * default: false - * https://github.com/algolia/algoliasearch-client-js#advancedsyntax + * https://www.algolia.com/doc/api-reference/api-parameters/advancedSyntax/ */ advancedSyntax?: boolean; /** * A string that contains the comma separated list of words that should be considered as optional when found in the query * default: [] - * https://github.com/algolia/algoliasearch-client-js#optionalwords + * https://www.algolia.com/doc/api-reference/api-parameters/optionalWords/ */ optionalWords?: string[]; /** @@ -411,13 +427,13 @@ declare namespace algoliasearch { * default: false * true|false: enable or disable stop words for all 41 supported languages; or * a list of language ISO codes (as a comma-separated string) for which stop words should be enable - * https://github.com/algolia/algoliasearch-client-js#removestopwords + * https://www.algolia.com/doc/api-reference/api-parameters/removeStopWords/ */ - removeStopWords?: string[]; + removeStopWords?: boolean|string[]; /** * List of attributes on which you want to disable the computation of exact criteria * default: [] - * https://github.com/algolia/algoliasearch-client-js#disableexactonattributes + * https://www.algolia.com/doc/api-reference/api-parameters/disableExactOnAttributes/ */ disableExactOnAttributes?: string[]; /** @@ -426,81 +442,90 @@ declare namespace algoliasearch { * 'none': no exact on single word query * 'word': exact set to 1 if the query word is found in the record * 'attribute': exact set to 1 if there is an attribute containing a string equals to the query - * https://github.com/algolia/algoliasearch-client-js#exactonsinglewordquery + * https://www.algolia.com/doc/api-reference/api-parameters/exactOnSingleWordQuery/ */ - exactOnSingleWordQuery?: string; + exactOnSingleWordQuery?: "attribute"|"none"|"word"; /** * Specify the list of approximation that should be considered as an exact match in the ranking formula * default: ['ignorePlurals', 'singleWordSynonym'] * 'ignorePlurals': alternative words added by the ignorePlurals feature * 'singleWordSynonym': single-word synonym (For example "NY" = "NYC") * 'multiWordsSynonym': multiple-words synonym - * https://github.com/algolia/algoliasearch-client-js#alternativesasexact + * https://www.algolia.com/doc/api-reference/api-parameters/alternativesAsExact/ */ - alternativesAsExact?: any; + alternativesAsExact?: Array<"ignorePlurals"|"singleWordSynonym"|"multiWordsSynonym">; /** * If set to 1, enables the distinct feature, disabled by default, if the attributeForDistinct index setting is set. - * https://github.com/algolia/algoliasearch-client-js#distinct + * https://www.algolia.com/doc/api-reference/api-parameters/distinct/ */ - distinct?: any; + distinct?: number|boolean; /** * If set to true, the result hits will contain ranking information in the _rankingInfo attribute. * default: false - * https://github.com/algolia/algoliasearch-client-js#getrankinginfo + * https://www.algolia.com/doc/api-reference/api-parameters/getRankingInfo/ */ getRankingInfo?: boolean; /** + * @deprecated Use `numericAttributesForFiltering` instead * All numerical attributes are automatically indexed as numerical filters * default: '' - * https://github.com/algolia/algoliasearch-client-js#numericattributestoindex + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ */ numericAttributesToIndex?: string[]; + /** + * All numerical attributes are automatically indexed as numerical filters + * default: '' + * https://www.algolia.com/doc/api-reference/api-parameters/numericAttributesForFiltering/ + */ + numericAttributesForFiltering?: string[]; /** * @deprecated please use filters instead * A string that contains the comma separated list of numeric filters you want to apply. - * https://github.com/algolia/algoliasearch-client-js#numericfilters-deprecated + * https://www.algolia.com/doc/api-reference/api-parameters/numericFilters/ */ numericFilters?: string[]; /** * @deprecated + * * Filter the query by a set of tags. - * https://github.com/algolia/algoliasearch-client-js#tagfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/tagFilters/ */ - tagFilters?: string; + tagFilters?: string[]; /** - * @deprecated * Filter the query by a set of facets. - * https://github.com/algolia/algoliasearch-client-js#facetfilters-deprecated + * Default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/facetFilters/ */ - facetFilters?: string; + facetFilters?: string[]|string[][]; /** * If set to false, this query will not be taken into account in the analytics feature. * default true - * https://github.com/algolia/algoliasearch-client-js#analytics + * https://www.algolia.com/doc/api-reference/api-parameters/analytics/ */ analytics?: boolean; /** * If set, tag your query with the specified identifiers - * default: null - * https://github.com/algolia/algoliasearch-client-js#analyticstags + * default: [] + * https://www.algolia.com/doc/api-reference/api-parameters/analyticsTags/ */ analyticsTags?: string[]; /** * If set to false, the search will not use the synonyms defined for the targeted index. * default: true - * https://github.com/algolia/algoliasearch-client-js#synonyms + * https://www.algolia.com/doc/api-reference/api-parameters/synonyms/ */ synonyms?: boolean; /** * If set to false, words matched via synonym expansion will not be replaced by the matched synonym in the highlighted result. * default: true - * https://github.com/algolia/algoliasearch-client-js#replacesynonymsinhighlight + * https://www.algolia.com/doc/api-reference/api-parameters/replaceSynonymsInHighlight/ */ replaceSynonymsInHighlight?: boolean; /** * Configure the precision of the proximity ranking criterion * default: 1 - * https://github.com/algolia/algoliasearch-client-js#minproximity + * https://www.algolia.com/doc/api-reference/api-parameters/minProximity/ */ minProximity?: number; @@ -530,42 +555,42 @@ declare namespace algoliasearch { interface Response { /** * Contains all the hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hits: any[]; /** * Current page - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ page: number; /** * Number of total hits matching the query - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbHits: number; /** * Number of pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ nbPages: number; /** * Number of hits per pages - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ hitsPerPage: number; /** * Engine processing time (excluding network transfer) - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ processingTimeMS: number; /** * Query used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ query: string; /** * GET parameters used to perform the search - * https://github.com/algolia/algoliasearch-client-js#response-format + * https://www.algolia.com/doc/api-reference/api-methods/search/?language=javascript#response */ params: string; facets?: { @@ -579,6 +604,16 @@ declare namespace algoliasearch { sum: number, }; }; + /** + * The index name is only set when searching multiple indices. + * https://www.algolia.com/doc/api-reference/api-methods/multiple-queries/?language=javascript#response + */ + index?: string; + /** + * The cursor is only set when browsing the index. + * https://www.algolia.com/doc/api-reference/api-methods/browse/ + */ + cursor?: string; } interface MultiResponse { diff --git a/types/ali-app/ali-app-tests.ts b/types/ali-app/ali-app-tests.ts new file mode 100644 index 0000000000..a42301aed1 --- /dev/null +++ b/types/ali-app/ali-app-tests.ts @@ -0,0 +1,2153 @@ +(() => { + // https://docs.alipay.com/mini/api/ui-navigate + my.navigateTo({ + url: 'new_page?count=100' + }); + // test.js + Page({ + onLoad(query: any) { + my.alert({ + content: JSON.stringify(query), + }); + } + }); + my.redirectTo({ + url: 'new_page?count=100' + }); + // 注意:调用 navigateTo 跳转时,调用该方法的页面会被加入堆栈, + // 而 redirectTo 方法则不会。见下方示例代码 + + // 此处是one页面 + my.navigateTo({ + url: 'two?pageId=10000' + }); + + // 此处是two页面 + my.navigateTo({ + url: 'one?pageId=99999' + }); + + // 在three页面内 navigateBack,将返回one页面 + my.navigateBack({ + delta: 2 + }); + my.reLaunch({ + url: '/page/index' + }); + my.setNavigationBar({ + title: '你好', + backgroundColor: '#108ee9', + success() { + my.alert({ + content: '设置成功', + }); + }, + fail() { + my.alert({ + content: '设置是失败', + }); + }, + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-tabbar + my.switchTab({ + url: '/home' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-feedback + my.alert({ + title: '亲', + content: '您本月的账单已出', + buttonText: '我知道了', + success: () => { + my.alert({ + title: '用户点击了「我知道了」', + }); + }, + }); + my.confirm({ + title: '温馨提示', + content: '您是否想查询快递单号:1234567890', + confirmButtonText: '马上查询', + cancelButtonText: '暂不需要', + success: (result) => { + my.alert({ + title: `${result.confirm}`, + }); + }, + }); + my.prompt({ + title: '标题单行', + message: '说明当前状态、提示用户解决方案,最好不要超过两行。', + placeholder: '给朋友留言', + okButtonText: '确定', + cancelButtonText: '取消', + success: (result) => { + my.alert({ + title: JSON.stringify(result), + }); + }, + }); + my.showToast({ + type: 'success', + content: '操作成功', + duration: 3000, + success: () => { + my.alert({ + title: 'toast 消失了', + }); + }, + }); + my.hideToast(); + my.showLoading({ + content: '加载中...', + delay: 1000, + }); + + my.hideLoading(); + + Page({ + onLoad() { + my.showLoading(); + const that = this; + setTimeout(() => { + my.hideLoading({ + page: that, // 防止执行时已经切换到其它页面,page指向不准确 + }); + }, 4000); + } + }); + my.showNavigationBarLoading(); + my.hideNavigationBarLoading(); + my.showActionSheet({ + title: '支付宝-ActionSheet', + items: ['菜单一', '菜单二', '菜单三', '菜单四', '菜单五'], + badges: [ + { index: 0, type: 'none' }, + { index: 1, type: 'point' }, + { index: 2, type: 'num', text: '99' }, + { index: 3, type: 'text', text: '推荐' }, + { index: 4, type: 'more' }], + cancelButtonText: '取消好了', + success: (res) => { + const btn = res.index === -1 ? '取消' : `第${res.index}个`; + my.alert({ + title: `你点了${btn}按钮` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-pulldown + Page({ + onPullDownRefresh() { + my.stopPullDownRefresh(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-contact + my.choosePhoneContact({ + success: (res) => { + my.alert({ + content: `姓名:${res.name}\n号码:${res.mobile}` + }); + } + }); + my.chooseAlipayContact({ + count: 2, + success: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseAlipayContact response: ' + JSON.stringify(res) + }); + } + }); + my.chooseContact({ + chooseType: 'multi', // 多选模式 + includeMe: true, // 包含自己 + includeMobileContactMode: 'known', // 仅包含双向手机通讯录联系人,也即双方手机通讯录都存有对方号码的联系人 + multiChooseMax: 3, // 最多能选择三个联系人 + multiChooseMaxTips: '超过选择的最大人数了', + success: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + content: 'chooseContact : ' + JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-city + my.chooseCity({ + cities: [ + { + city: '朝阳区', + adCode: '110105', + spell: 'chaoyang' + }, + { + city: '海淀区', + adCode: '110108', + spell: 'haidian' + }, + { + city: '丰台区', + adCode: '110106', + spell: 'fengtai' + }, + { + city: '东城区', + adCode: '110101', + spell: 'dongcheng' + }, + { + city: '西城区', + adCode: '110102', + spell: 'xicheng' + }, + { + city: '房山区', + adCode: '110111', + spell: 'fangshan' + } + ], + hotCities: [ + { + city: '朝阳区', + adCode: '110105' + }, + { + city: '海淀区', + adCode: '110108' + }, + { + city: '丰台区', + adCode: '110106' + } + ], + success: (res) => { + my.alert({ + content: `${res.city}:${res.adCode}` + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-date + my.datePicker({ + format: 'yyyy-MM-dd', + currentDate: '2012-12-12', + startDate: '2012-12-10', + endDate: '2012-12-15', + success: (res) => { + my.alert({ + content: res.date, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-animation + const animation = my.createAnimation({ + transformOrigin: "top right", + duration: 3000, + timeFunction: "ease-in-out", + delay: 100, + }); + Page({ + data: { + animationInfo: {} + }, + onShow() { + const animation = my.createAnimation({ + duration: 1000, + timeFunction: 'ease-in-out', + }); + + this.animation = animation; + + animation.scale(3, 3).rotate(60).step(); + + this.setData({ + animationInfo: animation.export() + }); + + setTimeout(() => { + animation.translate(35).step(); + this.setData({ + animationInfo: animation.export(), + }); + }, 1500); + }, + rotateAndScale(this: my.Page) { + // 旋转同时放大 + this.animation.rotate(60).scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateThenScale(this: my.Page) { + // 先旋转后放大 + this.animation.rotate(60).step(); + this.animation.scale(3, 3).step(); + this.setData({ + animationInfo: this.animation.export(), + }); + }, + rotateAndScaleThenTranslate(this: my.Page) { + // 先旋转同时放大,然后平移 + this.animation.rotate(60).scale(3, 3).step(); + this.animation.translate(100, 100).step({ duration: 2000 }); + this.setData({ + animationInfo: this.animation.export() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-canvas + const ctx = my.createCanvasContext('awesomeCanvas'); + ctx.toTempFilePath({ + success() { }, + }); + + ctx.setTextAlign("left"); + ctx.fillText("Hello world", 0, 100); + + ctx.setTextBaseline("top"); + ctx.fillText("Hello world", 0, 100); + + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(50, 50, 100, 175); + ctx.draw(); + + ctx.setFillStyle('red'); + ctx.setShadow(15, 45, 45, 'yellow'); + ctx.fillRect(20, 20, 100, 175); + ctx.draw(); + + const grd = ctx.createLinearGradient(10, 10, 150, 10); + grd.addColorStop(0, 'yellow'); + grd.addColorStop(1, 'blue'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + grd.addColorStop(0.36, 'orange'); + grd.addColorStop(0.56, 'cyan'); + grd.addColorStop(0.63, 'yellow'); + grd.addColorStop(0.76, 'blue'); + grd.addColorStop(0.54, 'green'); + grd.addColorStop(1, 'purple'); + grd.addColorStop(0.4, 'red'); + + ctx.setFillStyle(grd); + ctx.fillRect(20, 20, 250, 180); + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.lineTo(250, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(20, 35); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(20); + ctx.moveTo(20, 50); + ctx.lineTo(250, 55); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(25); + ctx.moveTo(20, 80); + ctx.lineTo(250, 85); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(150, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(20); + ctx.moveTo(20, 70); + ctx.lineTo(250, 80); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(25, 80); + ctx.lineTo(250, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(35, 47); + ctx.lineTo(230, 120); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.moveTo(20, 30); + ctx.lineTo(150, 70); + ctx.lineTo(20, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(20); + ctx.moveTo(100, 20); + ctx.lineTo(280, 80); + ctx.lineTo(100, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(20); + ctx.moveTo(60, 25); + ctx.lineTo(180, 80); + ctx.lineTo(90, 100); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(15); + ctx.moveTo(130, 70); + ctx.lineTo(250, 50); + ctx.lineTo(230, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.draw(); + + ctx.rect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.fillRect(20, 20, 250, 80); + ctx.setFillStyle('blue'); + ctx.draw(); + + ctx.setStrokeStyle('blue'); + ctx.strokeRect(20, 20, 250, 80); + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(250, 10, 250, 200); + ctx.setFillStyle('yellow'); + ctx.fillRect(0, 0, 150, 200); + ctx.clearRect(10, 10, 150, 75); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(200, 20); + ctx.lineTo(200, 200); + ctx.fill(); + ctx.draw(); + + ctx.rect(20, 20, 110, 40); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 30, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 80, 150, 40); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 10); + ctx.lineTo(150, 150); + ctx.stroke(); + ctx.draw(); + + ctx.rect(10, 10, 100, 30); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 50); + + ctx.setStrokeStyle('yellow'); + ctx.strokeRect(15, 75, 200, 35); + + ctx.rect(20, 200, 150, 30); + + ctx.setStrokeStyle('red'); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('yellow'); + ctx.fillRect(20, 170, 150, 40); + + ctx.rect(10, 100, 100, 30); + + ctx.setFillStyle('red'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 20); + ctx.lineTo(150, 150); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); + + ctx.rect(20, 20, 150, 50); + ctx.closePath(); + + ctx.beginPath(); + ctx.rect(20, 50, 150, 40); + + ctx.setFillStyle('red'); + ctx.fillRect(20, 80, 120, 30); + + ctx.rect(20, 150, 150, 40); + + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.lineTo(150, 15); + + ctx.moveTo(20, 55); + ctx.lineTo(120, 60); + ctx.stroke(); + ctx.draw(); + + ctx.moveTo(20, 20); + ctx.rect(20, 20, 80, 30); + ctx.lineTo(120, 80); + ctx.stroke(); + ctx.draw(); + + ctx.arc(200, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('#CCCCCC'); + ctx.fill(); + + ctx.beginPath(); + ctx.moveTo(50, 65); + ctx.lineTo(170, 80); + ctx.moveTo(200, 35); + ctx.lineTo(200, 235); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.setFontSize(12); + ctx.setFillStyle('yellow'); + ctx.fillText('0', 165, 78); + ctx.fillText('0.6*PI', 96, 148); + ctx.fillText('1*PI', 15, 57); + ctx.fillText('1.7*PI', 94, 20); + + ctx.beginPath(); + ctx.arc(200, 85, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(200, 35, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(450, 60, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(150, 35, 50, 0, 1.8 * Math.PI); + ctx.setStrokeStyle('#666666'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 25, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(20, 100, 2, 0, 2 * Math.PI); + ctx.arc(200, 100, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('yellow'); + ctx.setFontSize(14); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 100); + ctx.lineTo(150, 75); + + ctx.moveTo(250, 30); + ctx.lineTo(250, 80); + ctx.lineTo(70, 75); + ctx.setStrokeStyle('#EEEEEE'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.bezierCurveTo(30, 150, 250, 150, 180, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.beginPath(); + ctx.arc(30, 30, 2, 0, 2 * Math.PI); + ctx.setFillStyle('red'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(250, 20, 2, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + + ctx.beginPath(); + ctx.arc(30, 200, 2, 0, 2 * Math.PI); + ctx.setFillStyle('green'); + ctx.fill(); + + ctx.setFillStyle('black'); + ctx.setFontSize(12); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.lineTo(30, 150); + ctx.lineTo(250, 30); + ctx.setStrokeStyle('#AAAAAA'); + ctx.stroke(); + + ctx.beginPath(); + ctx.moveTo(30, 30); + ctx.quadraticCurveTo(30, 150, 250, 25); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); + + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + ctx.scale(3, 3); + ctx.strokeRect(15, 15, 30, 25); + + ctx.draw(); + + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + ctx.rotate(30 * Math.PI / 180); + ctx.strokeRect(200, 20, 180, 150); + + ctx.draw(); + + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + ctx.translate(30, 30); + ctx.strokeRect(20, 20, 250, 80); + + ctx.draw(); + + ctx.setFontSize(14); + ctx.fillText('14', 20, 20); + ctx.setFontSize(22); + ctx.fillText('22', 40, 40); + ctx.setFontSize(30); + ctx.fillText('30', 60, 60); + ctx.setFontSize(38); + ctx.fillText('38', 90, 90); + + ctx.draw(); + + ctx.setFontSize(42); + ctx.fillText('Hello', 30, 30); + ctx.fillText('alipay', 200, 200); + + ctx.draw(); + + ctx.drawImage('https://img.alicdn.com/tfs/TB1GvVMj2BNTKJjy0FdXXcPpVXa-520-280.jpg', 2, 2, 250, 80); + ctx.draw(); + + ctx.setFillStyle('yellow'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('red'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); + + ctx.setLineDash([5, 15, 25]); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.transform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.rotate(45 * Math.PI / 180); + ctx.setFillStyle('red'); + ctx.fillRect(70, 0, 100, 30); + + ctx.setTransform(1, 1, 0, 1, 0, 0); + ctx.setFillStyle('#000'); + ctx.fillRect(0, 0, 100, 100); + + ctx.draw(); + + ctx.save(); + ctx.setFillStyle('red'); + ctx.fillRect(20, 20, 250, 80); + + ctx.restore(); + ctx.fillRect(60, 60, 155, 130); + + ctx.draw(); + + ctx.setFillStyle('blue'); + ctx.fillRect(20, 20, 180, 80); + ctx.draw(); + ctx.fillRect(60, 60, 250, 120); + ctx.draw(true); + + ctx.font = 'italic bold 50px cursive'; + const { width } = ctx.measureText('hello world'); + console.log(width); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-map + Page({ + onReady() { + // 使用 my.createMapContext 获取 map 上下文 + this.mapCtx = my.createMapContext('userMap'); + }, + getCenterLocation(this: my.Page) { + (this.mapCtx as my.MapContext).getCenterLocation({ + success(res) { + console.log(res.longitude); + console.log(res.latitude); + } + }); + }, + moveToLocation() { + this.mapCtx.moveToLocation(); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ui-hidekeyboard + my.hideKeyboard(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scroll + my.pageScrollTo({ + scrollTop: 100 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/selector-query + Page({ + onReady() { + my.createSelectorQuery() + .select('#non-exists').boundingClientRect() + .select('#one').boundingClientRect() + .selectAll('.all').boundingClientRect() + .select('#scroll').scrollOffset() + .selectViewport().boundingClientRect() + .selectViewport().scrollOffset().exec((ret) => { + console.log(JSON.stringify(ret, null, 2)); + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/ewdxl3 + my.multiLevelSelect({ + title: 'nihao', // 级联选择标题 + list: [ + { + name: "杭州市", // 条目名称 + subList: [ + { + name: "西湖区", + subList: [ + { + name: "古翠街道" + }, + { + name: "文新街道" + } + ] + }, + { + name: "上城区", + subList: [ + { + name: "延安街道" + }, + { + name: "龙翔桥街道" + } + ] + } + ]// 级联子数据列表 + } + ]// 级联数据列表 + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-authorize + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.alert({ + content: res.authCode, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/userinfo + my.getAuthCode({ + scopes: 'auth_user', + success: (res) => { + my.getAuthUserInfo({ + success: (userInfo) => { + my.alert({ + content: userInfo.nickName + }); + my.alert({ + content: userInfo.avatar + }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/openapi-pay + my.tradePay({ + tradeNO: '201711152100110410533667792', // 调用统一收单交易创建接口(alipay.trade.create),获得返回字段支付宝交易号trade_no + success: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + content: JSON.stringify(res), + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/pay-sign + my.paySignCenter({ + // tslint:disable-next-line:max-line-length + signStr: 'biz_content%3D%257B%2522access_params%2522%253A%257B%2522channel%2522%253A%2522ALIPAYAPP%2522%257D%252C%2522external_agreement_no%2522%253A%2522xidong___2317%2522%252C%2522external_logon_id%2522%253A%252213852852877%2522%252C%2522personal_product_code%2522%253A%2522GENERAL_WITHHOLDING_P%2522%252C%2522product_code%2522%253A%2522GENERAL_WITHHOLDING%2522%252C%2522sign_scene%2522%253A%2522INDUSTRY%257CCARRENTAL%2522%252C%2522third_party_type%2522%253A%2522PARTNER%2522%257D%26sign%3Df3pjBDTRftOwXWnCqAMAnkBfGTFlcMmZI8hEgmV6uREZRXVDuLsSjD8WO%252FeZ1fjDG8GqVO9t1AN7q6yCUHKX%252Bw%252FE7efXwpVDWldr4iVuXDtNd3UJDJUiRJhIm6b73czWacVzm1XIery%252F2DyKI2y08tBf5NNWuQCC3d%252FITxziTl8%253D%26timestamp%3D2017-06-27%2B14%253A44%253A00%26sign_type%3DRSA%26notify_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26charset%3DUTF-8%26app_id%3D2017060101317939%26method%3Dalipay.user.agreement.page.sign%26return_url%3Dhttp%253A%252F%252Fapi.test.alipay.net%252Fatinterface%252Freceive_notify.htm%26version%3D1.0', + success: (res) => { + my.alert({ + title: 'success', // alert框的标题 + content: JSON.stringify(res) + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert框的标题 + content: JSON.stringify(res) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/card-voucher-ticket + my.openCardList(); + my.openMerchantCardList({ partnerId: '2088xxxxx' }); + // 传入passId来打开 + my.openCardDetail({ passId: "11xxxxx" }); + my.openVoucherList(); + my.openMerchantVoucherList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openVoucherDetail({ + partnerId: "2018xxxx", + serialNumber: "20170921" + }); + // 传入passId来打开 + my.openKBVoucherDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openKBVoucherDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); + my.openTicketList(); + my.openMerchantTicketList({ partnerId: '2088xxxx' }); + // 传入passId来打开 + my.openTicketDetail({ passId: "20170921" }); + + // 传入partnerId 和 serialNumber来打开 + my.openTicketDetail({ + partnerId: "2088xxxx", + serialNumber: "20170921" + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/add-card-auth + my.addCardAuth({ + url: '从 openapi 接口获取到的 url', + success: (res) => { + my.alert({ content: '授权成功' }); + }, + fail: (res) => { + my.alert({ content: '授权失败' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zm-service + my.startZMVerify({ + bizNo: 'your-biz-no', + success: (res) => { + my.alert({ title: 'success:' + JSON.stringify(res) }); + }, + fail: (res) => { + my.alert({ title: 'fail: ' + JSON.stringify(res) }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/zmcreditborrow + my.zmCreditBorrow({ + credit_biz: "", + out_order_no: "", + borrow_shop_name: "", + goods_name: "", + product_code: "w1010100000000002858", + rent_unit: "HOUR_YUAN", + rent_amount: "0.10", + deposit_amount: "0.50", + deposit_state: "Y", + invoke_return_url: "", + invoke_type: "TINYAPP", + borrow_time: "2017-04-27 10:01:01", + expiry_time: "2017-05-27 10:01:01", + rent_info: "2hour-free", + success: (res) => { + try { + const { resultStatus, result } = res; + switch (resultStatus) { + case '9000': + const callbackData = result.callbackData; + const decodedCallbackData = decodeURIComponent(callbackData); + const json = JSON.parse(decodedCallbackData.match(/{.*}/)!.toString()); + const jsonStr = JSON.stringify(json, null, 4); + if (json.success === true || json.success === 'true') { + // 创建订单成功, 此时可以跳转到订单详情页面 + my.alert({ content: '下单成功: ' + jsonStr }); + } else { + // 创建订单失败, 请提示用户创建失败 + my.alert({ content: '下单失败: ' + jsonStr }); + } + // (this as any as my.Page).setData({ + // callbackData, + // decodedCallbackData, + // parsedJSON: jsonStr, + // }); + break; + case '6001': + // 用户点击返回, 取消此次服务, 此时可以给提示 + my.alert({ content: '取消' }); + break; + default: + break; + } + } catch (error) { + // 异常, 请在这里提示用户稍后重试 + my.alert({ + content: '异常' + JSON.stringify(error, null, 4) + }); + } + }, + fail: (error) => { + // 调用接口失败, 请在这里提示用户稍后重试 + my.alert({ + content: '调用失败' + JSON.stringify(error, null, 4) + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/templatemessage +})(); + +(() => { + // https://docs.alipay.com/mini/api/text-identification + my.textRiskIdentification({ + content: '加我支付宝', + type: ['keyword', '0', '1', '2', '3'], + success: (res) => { + my.alert({ + title: 'ok', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + fail: (res) => { + my.alert({ + title: 'fail', // alert 框的标题 + content: JSON.stringify(res), + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/open-miniprogram + my.navigateToMiniProgram({ + appId: 'xxxx', + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.navigateBackMiniProgram({ + extraData: { + data1: "test" + }, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/webview-context + Page({ + onLoad() { + this.webViewContext = my.createWebViewContext('web-view-1'); + }, + // 接收来自H5的消息 + onMessage(e: any) { + console.log(e); // {'sendToMiniProgram': '0'} + // 向H5发送消息 + this.webViewContext.postMessage({ sendToWebView: '1' }); + } + }); + // H5的js代码中需要先定义my.onMessage 用于接收来自小程序的消息。 + my.onMessage = (e) => { + console.log(e); // {'sendToWebView': '1'} + }; + // H5想小程序发送消息 + my.postMessage({ sendToMiniProgram: '0' }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/media-image + const img = null as any as HTMLImageElement; + my.chooseImage({ + count: 2, + success: (res) => { + img.src = res.apFilePaths[0]; + }, + }); + my.previewImage({ + current: 2, + urls: [ + 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1pfG4IFXXXXc6XXXXXXXXXXXX.jpg', + 'https://img.alicdn.com/tps/TB1h9xxIFXXXXbKXXXXXXXXXXXX.jpg' + ], + }); + my.saveImage({ + url: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg' + }); + my.compressImage({ + apFilePaths: ['https://resource/apmlcc0ed184daffc5a0d8da86b2f518cf7b.image'], + // level: 1, + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + // 网络图片路径 + my.getImageInfo({ + src: 'https://img.alicdn.com/tps/TB1sXGYIFXXXXc5XpXXXXXXXXXX.jpg', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + + // apFilePath + my.chooseImage({ + success: (res) => { + my.getImageInfo({ + src: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + }, + }); + + // 相对路径 + my.getImageInfo({ + src: 'image/api.png', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/storage + my.setStorage({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + }, + success() { + my.alert({ content: '写入成功' }); + } + }); + my.setStorageSync({ + key: 'currentCity', + data: { + cityName: '杭州', + adCode: '330100', + spell: ' hangzhou', + } + }); + my.getStorage({ + key: 'currentCity', + success(res) { + my.alert({ content: '获取成功:' + res.data.cityName }); + }, + fail(res) { + my.alert({ content: res.errorMessage }); + } + }); + const res = my.getStorageSync({ key: 'currentCity' }); + my.alert({ + content: JSON.stringify(res.data), + }); + my.removeStorage({ + key: 'currentCity', + success() { + my.alert({ content: '删除成功' }); + } + }); + my.removeStorageSync({ + key: 'currentCity', + }); + my.clearStorage(); + my.clearStorageSync(); + my.getStorageInfo({ + success(res) { + console.log(res.keys); + console.log(res.currentSize); + console.log(res.limitSize); + } + }); + const res1 = my.getStorageInfoSync(); + console.log(res1.keys); + console.log(res1.currentSize); + console.log(res1.limitSize); +})(); + +(() => { + // https://docs.alipay.com/mini/api/file + my.chooseImage({ + success: (res) => { + my.saveFile({ + apFilePath: res.apFilePaths[0], + success: (res) => { + console.log(JSON.stringify(res)); + }, + }); + }, + }); + my.getFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + digestAlgorithm: 'sha1', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileInfo({ + apFilePath: 'https://resource/apml953bb093ebd2834530196f50a4413a87.video', + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + console.log(JSON.stringify(res)); + } + }); + my.getSavedFileList({ + success: (res) => { + my.removeSavedFile({ + apFilePath: res.fileList[0].apFilePath, + success: (res) => { + console.log('remove success'); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/location + my.getLocation({ + success(res) { + my.hideLoading(); + console.log(res); + /* that对象为Page可以设置数据刷新界面 + that.setData({ + hasLocation: true, + location: formatLocation(res.longitude, res.latitude) + }) + */ + }, + fail() { + my.hideLoading(); + my.alert({ title: '定位失败' }); + }, + }); + my.openLocation({ + longitude: '121.549697', + latitude: '31.227250', + name: '支付宝', + address: '杨高路地铁站', + }); + my.chooseLocation({ + success: (res) => { + console.log(res); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network + my.httpRequest({ + url: 'http://httpbin.org/post', + method: 'POST', + data: { + from: '支付宝', + production: 'AlipayJSAPI', + }, + dataType: 'json', + success(res) { + my.alert({ content: 'success' }); + }, + fail(res) { + my.alert({ content: 'fail' }); + }, + complete(res) { + my.hideLoading(); + my.alert({ content: 'complete' }); + } + }); + my.uploadFile({ + url: '请使用自己服务器地址', + fileType: 'image', + fileName: 'file', + filePath: '...', + success: (res) => { + my.alert({ + content: '上传成功' + }); + }, + }); + my.downloadFile({ + url: 'http://img.alicdn.com/tfs/TB1x669SXXXXXbdaFXXXXXXXXXX-520-280.jpg', + success({ apFilePath }) { + my.previewImage({ + urls: [apFilePath], + }); + }, + fail(res) { + my.alert({ + content: res.errorMessage || res.error, + }); + }, + }); + my.connectSocket({ + url: 'test.php', + data: {}, + header: { + 'content-type': 'application/json' + }, + method: 'GET' + }); + my.connectSocket({ + url: 'test.php', + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketOpen(this.callback); + }, + onUnload() { + my.offSocketOpen(this.callback); + }, + callback() { + }, + }); + my.connectSocket({ + url: '开发者的服务器地址' + }); + + my.onSocketOpen(() => { + console.log('WebSocket 连接已打开!'); + }); + + my.onSocketError(() => { + console.log('WebSocket 连接打开失败,请检查!'); + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onSocketError(this.callback); + }, + onUnload() { + my.offSocketError(this.callback); + }, + callback() { + my.sendSocketMessage({ + data: this.data.toSendMessage, // 需要发送的内容 + success: (res) => { + my.alert({ content: '数据发送!' + this.data.toSendMessage }); + }, + }); + }, + }); + my.connectSocket({ + url: '服务器地址' + }); + + my.onSocketMessage((res) => { + console.log('收到服务器内容:' + res.data); + }); + my.onSocketOpen(() => { + my.closeSocket(); + }); + + my.onSocketClose(() => { + console.log('WebSocket 已关闭!'); + }); + Page({ + // onLoad() { + onLaunch() { + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketClose(() => { + my.alert({ content: '连接已关闭!' }); + this.setData({ + sendMessageAbility: false, + closeLinkAbility: false, + }); + }); + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketOpen(() => { + my.alert({ content: '连接已打开!' }); + this.setData({ + sendMessageAbility: true, + closeLinkAbility: true, + }); + }); + + my.onSocketError((res) => { + my.alert({ content: 'WebSocket 连接打开失败,请检查!' + res }); + }); + + // 注意: 回调方法的注册在整个小程序启动阶段只要做一次,调多次会有多次回调 + my.onSocketMessage((res) => { + my.alert({ content: '收到数据!' + JSON.stringify(res) }); + }); + }, + connect_start() { + my.connectSocket({ + url: '服务器地址', // 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名 + success: (res) => { + my.showToast({ + content: 'success', // 文字内容 + }); + }, + fail: () => { + my.showToast({ + content: 'fail', // 文字内容 + }); + } + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/can-i-use + my.canIUse('getFileInfo'); + my.canIUse('closeSocket.object.code'); + my.canIUse('getLocation.object.type'); + my.canIUse('getSystemInfo.return.brand'); + my.canIUse('lifestyle'); + my.canIUse('button.open-type.share'); +})(); + +(() => { + // https://docs.alipay.com/mini/api/sdk-version + console.log(my.SDKVersion); +})(); + +(() => { + // https://docs.alipay.com/mini/api/system-info + Page({ + data: { + systemInfo: {} + }, + getSystemInfoPage(this: my.Page) { + my.getSystemInfo({ + success: (res) => { + this.setData({ + systemInfo: res + }); + } + }); + }, + }); + Page({ + data: { + systemInfo: {} + }, + getSystemInfoSyncPage(this: my.Page) { + this.setData({ + systemInfo: my.getSystemInfoSync() + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/network-status + Page({ + data: { + hasNetworkType: false + }, + getNetworkType(this: my.Page) { + my.getNetworkType({ + success: (res) => { + this.setData({ + hasNetworkType: true, + networkType: res.networkType + }); + } + }); + }, + clear(this: my.Page) { + this.setData({ + hasNetworkType: false, + networkType: '' + }); + }, + }); + my.onNetworkStatusChange((res) => { + console.log(JSON.stringify(res)); + }); + my.offNetworkStatusChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/clipboard + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handlePaste(this: my.Page) { + my.getClipboard({ + success: ({ text }) => { + this.setData({ copy: text }); + }, + }); + }, + }); + Page({ + data: { + text: '3.1415926', + copy: '', + }, + + handleCopy() { + my.setClipboard({ + text: this.data.text, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/shake + Page({ + watchShake() { + my.watchShake({ + success() { + console.log('动起来了'); + my.alert({ title: '动起来了 o.o' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/vibrate + Page({ + vibrate() { + my.vibrate({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateLong() { + my.vibrateLong({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); + Page({ + vibrateShort() { + my.vibrateShort({ + success: () => { + my.alert({ title: '震动起来了' }); + } + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/macke-call + Page({ + makePhoneCall() { + my.makePhoneCall({ number: '95888' }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/get-server-time + // getServerTime(){ + // my.getServerTime({ + // success: (res) => { + // my.alert({ + // title: res.time, + // }); + // }, + // }); + // }; +})(); + +(() => { + // https://docs.alipay.com/mini/api/user-capture-screen + my.onUserCaptureScreen(() => { + my.alert({ + content: '收到用户截屏事件' + }); + }); + my.offUserCaptureScreen(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/screen-brightness + my.setKeepScreenOn({ + keepScreenOn: true, + success: (res) => { + }, + fail: (res) => { + }, + }); + my.getScreenBrightness({ + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); + my.setScreenBrightness({ + brightness: 0.5, + success: (res) => { + console.log(JSON.stringify(res)); + }, + fail: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/show-auth-guide + my.showAuthGuide({ + authType: 'LBSSERVICE' + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/scan + Page({ + scan() { + my.scan({ + type: 'qr', + success: (res) => { + my.alert({ title: res.code }); + }, + }); + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-intro + // 初始化 + my.openBluetoothAdapter({ + success: (res) => { + console.log(res); + } + }); + // 注册发现事件 + my.onBluetoothDeviceFound({ + success: (res) => { + const device = res.devices[0]; + // 连接发现的设备 + my.connectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + // 停止搜索 + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + // 注册连接事件 + my.onBLEConnectionStateChanged({ + success: (res) => { + console.log(res); + if (res.connected) { + // 开始读写notify等操作 + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + } + } + }); + // 注册接收read或notify的数据 + my.onBLECharacteristicValueChange({ + success: (res) => { + console.log(res); + } + }); + // 开始搜索 + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 断开连接 + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + // 注销事件 + my.offBluetoothDeviceFound(); + my.offBLEConnectionStateChanged(); + my.offBLECharacteristicValueChange(); + + // 退出蓝牙模块 + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/bluetooth-api + my.openBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.closeBluetoothAdapter({ + success: (res) => { + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothAdapterState({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.startBluetoothDevicesDiscovery({ + services: ['fff0'], + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.stopBluetoothDevicesDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getConnectedBluetoothDevices({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + const deviceId = 'test'; + const serviceId = 'test'; + const characteristicId = 'test'; + my.connectBLEDevice({ + // 这里的 deviceId 需要在上面的 getBluetoothDevices 或 onBluetoothDeviceFound 接口中获取 + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.disconnectBLEDevice({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.writeBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + value: 'fffe', + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.readBLECharacteristicValue({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.notifyBLECharacteristicValueChange({ + deviceId, + serviceId, + characteristicId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceServices({ + deviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + my.getBLEDeviceCharacteristics({ + deviceId, + serviceId, + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBluetoothDeviceFound(this.callback); + }, + onUnload() { + my.offBluetoothDeviceFound(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBluetoothDeviceFound(); + Page({ + onLoad() { + this.callback = this.callback.bind(this); + my.onBLECharacteristicValueChange(this.callback); + }, + onUnload() { + my.offBLECharacteristicValueChange(this.callback); + }, + callback(res: any) { + console.log(res); + }, + }); + my.offBLECharacteristicValueChange(); + my.offBLEConnectionStateChanged(); + my.offBluetoothAdapterStateChange(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/yqleyc + my.startBeaconDiscovery({ + uuids: ['uuid1', 'uuid2'], + success: (res) => { + console.log(res); + }, + fail: () => { + }, + complete: () => { + } + }); + + my.stopBeaconDiscovery({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.getBeacons({ + success: (res) => { + console.log(res); + }, + fail: (res) => { + }, + complete: (res) => { + } + }); + + my.onBeaconUpdate({ + success: (res) => { + }, + }); + + my.onBeaconServiceChange({ + success: (res) => { + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/data-safe + Page({ + data: { + inputValue: '', + outputValue: '', + }, + onInput(this: my.Page, e: any) { + this.setData({ inputValue: e.detail.value }); + }, + onEncrypt(this: my.Page) { + my.rsa({ + action: 'encrypt', + // 设置公钥 + // tslint:disable-next-line:max-line-length + key: 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDKmi0dUSVQ04hL6GZGPMFK8+d6\nGzulagP27qSUBYxIJfE04KT+OHVeFFb6K+8nWDea5mkmZrIgp022zZVDgdWPNM62\n3ouBwHlsfm2ekey8PpQxfXaj8lhM9t8rJlC4FEc0s8Qp7Q5/uYrowQbT9m6t7BFK\n3egOO2xOKzLpYSqfbQIDAQAB', + text: this.data.inputValue, + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + onDecrypt(this: my.Page) { + my.rsa({ + action: 'decrypt', + text: this.data.inputValue, + // 设置私钥 + // tslint:disable-next-line:prefer-template + key: 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAMqaLR1RJVDTiEvo\n' + + 'ZkY8wUrz53obO6VqA/bupJQFjEgl8TTgpP44dV4UVvor7ydYN5rmaSZmsiCnTbbN\n' + + 'lUOB1Y80zrbei4HAeWx+bZ6R7Lw+lDF9dqPyWEz23ysmULgURzSzxCntDn+5iujB\n' + + 'BtP2bq3sEUrd6A47bE4rMulhKp9tAgMBAAECgYBjsfRLPdfn6v9hou1Y2KKg+F5K\n' + + 'ZsY2AnIK+6l+sTAzfIAx7e0ir7OJZObb2eyn5rAOCB1r6RL0IH+MWaN+gZANNG9g\n' + + 'pXvRgcZzFY0oqdMZDuSJjpMTj7OEUlPyoGncBfvjAg0zdt9QGAG1at9Jr3i0Xr4X\n' + + '6WrFhtfVlmQUY1VsoQJBAPK2Qj/ClkZNtrSDfoD0j083LcNICqFIIGkNQ+XeuTwl\n' + + '+Gq4USTyaTOEe68MHluiciQ+QKvRAUd4E1zeZRZ02ikCQQDVscINBPTtTJt1JfAo\n' + + 'wRfTzA0Lvgig136xLLeQXREcgq1lzgkf+tGyUGYoy9BXsV0mOuYAT9ldja4jhJeq\n' + + 'cEulAkEAuSJ5KjV9dyb0RIFAz5C8d8o5KAodwaRIxJkPv5nCZbT45j6t9qbJxDg8\n' + + 'N+vghDlHI4owvl5wwVlAO8iQBy8e8QJBAJe9CVXFV0XJR/n/XnER66FxGzJjVi0f\n' + + '185nOlFARI5CHG5VxxT2PUCo5mHBl8ctIj+rQvalvGs515VQ6YEVDCECQE3S0AU2\n' + + 'BKyFVNtTpPiTyRUWqig4EbSXwjXdr8iBBJDLsMpdWsq7DCwv/ToBoLg+cQ4Crc5/\n5DChU8P30EjOiEo=', + success: (result) => { + this.setData({ outputValue: result.text }); + }, + fail(e) { + my.alert({ + content: e.errorMessage || e.error, + }); + }, + }); + }, + }); +})(); + +(() => { + // https://docs.alipay.com/mini/api/share_app + Page({ + onShareAppMessage() { + return { + title: '小程序示例', + desc: '小程序官方示例Demo,展示已支持的接口能力及组件。', + path: 'page/component/component-pages/view/view?param=123' + }; + }, + }); + + my.hideShareMenu(); +})(); + +(() => { + // https://docs.alipay.com/mini/api/report + my.reportAnalytics('purchase', { + status: 200, + reason: 'ok' + }); +})(); diff --git a/types/ali-app/index.d.ts b/types/ali-app/index.d.ts new file mode 100644 index 0000000000..82f7b2bf27 --- /dev/null +++ b/types/ali-app/index.d.ts @@ -0,0 +1,3265 @@ +// Type definitions for ali-app 1.0 +// Project: https://docs.alipay.com/mini/api/overview (Does not have to be to GitHub, but prefer linking to a source code repository rather than to a project website.) +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// 公共部分 +declare namespace my { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: any; + /** 开发者服务器返回的 HTTP 状态码 */ + status: number; + /** 开发者服务器返回的 HTTP Response Header */ + headers: object; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + apFilePath: string; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion +} + +// 界面 +declare namespace my { + //#region 导航栏 https://docs.alipay.com/mini/api/ui-navigate + interface NavigateToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 保留当前页面,跳转到应用内的某个页面,使用wx.navigateBack可以返回到原页面。 + * + * 注意:为了不让用户在使用小程序时造成困扰, + * 我们规定页面路径只能是五层,请尽量避免多层级的交互方式。 + */ + function navigateTo(options: NavigateToOptions): void; + + interface RedirectToOptions extends BaseOptions { + /** 需要跳转的应用内页面的路径 */ + url: string; + } + /** + * 关闭当前页面,跳转到应用内的某个页面。 + */ + function redirectTo(options: RedirectToOptions): void; + + interface NavigateBackOptions extends BaseOptions { + /** 返回的页面数,如果 delta 大于现有打开的页面数,则返回到首页 */ + delta: number; + } + /** + * 关闭当前页面,返回上一级或多级页面。可通过 getCurrentPages 获取当前的页面栈信息,决定需要返回几层。 + */ + function navigateBack(options?: NavigateBackOptions): void; + + interface ReLaunchOptions extends BaseOptions { + /** + * 需要跳转的应用内页面路径 , 路径后可以带参数。 + * 参数与路径之间使用?分隔,参数键与参数值用=相连,不同参数用&分隔 + * 如 'path?key=value&key2=value2',如果跳转的页面路径是 tabBar 页面则不能带参数 + */ + url: string; + } + /** + * 关闭所有页面,打开到应用内的某个页面。 + */ + function reLaunch(options?: ReLaunchOptions): void; + + interface SetNavigationBarOptions extends BaseOptions { + /** 页面标题 */ + title: string; + /** 图片连接地址,必须是https,请使用3x高清图片。若设置了image则title参数失效 */ + image: string; + /** 导航栏背景色,支持十六进制颜色值 */ + backgroundColor: string; + /** 导航栏底部边框颜色,支持十六进制颜色值。若设置了 backgroundColor,则borderBottomColor 不会生效,默认会和 backgroundColor 颜色一样 */ + borderBottomColor: string; + /** 是否重置导航栏为支付宝默认配色,默认 false */ + reset: boolean; + } + /** + * 动态设置当前页面的标题。 + */ + function setNavigationBar(options: Partial): void; + + /** + * 显示导航栏 loading + */ + function showNavigationBarLoading(): void; + + /** 隐藏导航栏 loading。 */ + function hideNavigationBarLoading(): void; + //#endregion + + //#region TabBar https://docs.alipay.com/mini/api/ui-tabbar + interface SwitchTabOptions extends BaseOptions { + /** + * 需要跳转的 tabBar 页面的路径 + * (需在 app.json 的 tabBar 字段定义的页面),路径后不能带参数 + */ + url: string; + } + /** + * 跳转到指定 tabBar 页面,并关闭其他所有非 tabBar 页面 + */ + function switchTab(options: SwitchTabOptions): void; + //#endregion + + //#region 交互反馈 https://docs.alipay.com/mini/api/ui-feedback + + interface AlertOptions extends BaseOptions { + /** alert框的标题 */ + title: string; + /** alert框的内容 */ + content: string; + /** 按钮文字,默认确定 */ + buttonText: string; + } + function alert(options: Partial): void; + + interface ConfirmOptions extends BaseOptions { + /** confirm框的标题 */ + title: string; + /** confirm框的内容 */ + content: string; + /** 确认按钮文字,默认‘确定’ */ + confirmButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { confirm: boolean; }): void; + } + function confirm(options: Partial): void; + + interface PromptOptions extends BaseOptions { + /** prompt框标题 */ + title?: string; + /** prompt框文本,默认‘请输入内容’ */ + message?: string; + /** 输入框内的提示文案 */ + placeholder?: string; + /** message对齐方式,可用枚举left/center/right,iOS ‘center’, android ‘left’ */ + align?: 'left' | 'center' | 'right' | string; + /** 确认按钮文字,默认‘确定’ */ + okButtonText: string; + /** 确认按钮文字,默认‘取消’ */ + cancelButtonText: string; + success(result: { ok: boolean; inputValue: string; }): void; + } + function prompt(options: PromptOptions): void; + + interface ToastOptions extends BaseOptions { + /** + * 文字内容 + */ + content: string; + /** toast 类型,展示相应图标,默认 none,支持 success / fail / exception / none’。其中 exception 类型必须传文字信息 */ + type?: 'none' | 'success' | 'fail' | 'exception' | string; + /** + * 显示时长,单位为 ms,默认 2000 + */ + duration?: number; + } + /** + * 显示消息提示框 + */ + function showToast(options: Partial): void; + function hideToast(): void; + + interface LoadingOptions extends BaseOptions { + /** + * loading的文字内容 + */ + content?: string; + /** + * 延迟显示,单位 ms,默认 0。如果在此时间之前调用了 my.hideLoading 则不会显示 + */ + delay?: number; + } + /** + * 显示加载提示 + */ + function showLoading(options?: LoadingOptions): void; + interface HideLoadingOptions { + /** + * 体指当前page实例,某些场景下,需要指明在哪个page执行hideLoading。 + */ + page: any; + } + /** + * 隐藏消息提示框 + */ + function hideLoading(options?: HideLoadingOptions): void; + + interface Badge { + /** 需要飘红的选项的索引,从0开始 */ + index: number; + /** + * 飘红类型,支持 none(无红点)/ point(纯红点) / num(数字红点)/ text(文案红点)/ more(...) + * + */ + type: 'none' | 'point' | 'num' | 'text' | 'more' | string; + + /** + * 自定义飘红文案: + * + * 1、type为none/point/more时本文案可不填 + * 2、type为num时本文案为小数或<=0均不显示, >100 显示"..." + */ + text: string; + } + interface ActionSheetOptions extends BaseOptions { + /** 菜单标题 */ + title?: string; + /** + * 菜单按钮文字数组 + */ + items: string[]; + /** + * 取消按钮文案。默认为‘取消’。注:Android平台此字段无效,不会显示取消按钮。 + */ + cancelButtonText?: string; + /** + * (iOS特殊处理)指定按钮的索引号,从0开始,使用场景:需要删除或清除数据等类似场景,默认红色 + */ + destructiveBtnIndex?: number; + /** + * 需飘红选项的数组,数组内部对象字段见下表 + */ + badges?: Array>; + /** + * 接口调用成功的回调函数 + */ + success?(res: { + /** + * 用户点击的按钮,从上到下的顺序,从0开始 + */ + index: number; + }): void; + } + /** + * 显示操作菜单 + */ + function showActionSheet(options: ActionSheetOptions): void; + //#endregion + + //#region 下拉刷新 https://docs.alipay.com/mini/api/ui-pulldown + /** + * Page 实现的接口对象 + */ + interface PageOptions { + /** + * 下拉刷新 + * 在 Page 中定义 onPullDownRefresh 处理函数,监听该页面用户下拉刷新事件。 + * 需要在页面对应的 .json 配置文件中配置 "pullRefresh": true 选项,才能开启下拉刷新事件。 + * 当处理完数据刷新后,调用 my.stopPullDownRefresh 可以停止当前页面的下拉刷新。 + */ + onPullDownRefresh?(this: Page): void; + } + /** + * 停止当前页面的下拉刷新。 + */ + function stopPullDownRefresh(): void; + //#endregion + + //#region 联系人 https://docs.alipay.com/mini/api/ui-contact + interface ChoosePhoneContactOptions extends BaseOptions { + success(result: { + name: string; // 选中的联系人姓名 + mobile: string; // 选中的联系人手机号 + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 选择本地系统通信录中某个联系人的电话。 + */ + function choosePhoneContact(options: ChoosePhoneContactOptions): void; + + interface ChooseAlipayContactOptions extends BaseOptions { + /** 单次最多选择联系人个数,默认 1,最大 10 */ + count: number; + success(result: { + realName: string; // 账号的真实姓名 + mobile: string; // 账号对应的手机号码 + email: string; // 账号的邮箱 + avatar: string; // 账号的头像链接 + userId: string; // 支付宝账号唯一 userId + }): void; + /** + * 10 没有权限 + * 11 用户取消操作(或设备未授权使用通讯录) + */ + fail?(error: 10 | 11): void; + } + /** + * 唤起支付宝通讯录,选择一个或者多个支付宝联系人。 + */ + function chooseAlipayContact(options: ChooseAlipayContactOptions): void; + + interface ContactsDic { + /** + * 支付宝账号唯一 userId + */ + userId: string; + /** + * 账号的头像链接 + */ + avatar: string; + /** + * 账号对应的手机号码 + */ + mobile: string; + /** + * 账号的真实姓名 + */ + realName: string; + /** + * 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + */ + displayName: string; // 账号的显示名称:也即支付宝设置的备注名称,默认为朋友圈里面的昵称 + } + interface ChooseContactOptions extends BaseOptions { + /** 选择类型,值为single(单选)或者 multi(多选) */ + chooseType: 'single' | 'multi' | string; + /** 包含手机通讯录联系人的模式:默认为不包含(none)、或者仅仅包含双向通讯录联系人(known)、或者包含手机通讯录联系人(all) */ + includeMobileContactMode?: 'none' | 'known' | 'all' | string; + /** 是否包含自己 */ + includeMe?: boolean; + /** 最大选择人数,仅 chooseType 为 multi 时才有效 */ + multiChooseMax?: number; + /** 多选达到上限的文案,仅 chooseType 为 multi 时才有效 */ + multiChooseMaxTips?: string; + + success(result: { + contactsDicArray: ContactsDic[]; + }): void; + } + /** + * 唤起选人组件,默认只包含支付宝联系人,可以通过修改参数包含手机通讯录联系人或者双向通讯录联系人。 + */ + function chooseContact(options: ChooseContactOptions): void; + //#endregion + + //#region 选择城市 https://docs.alipay.com/mini/api/ui-city + interface City { + city: string; // 城市名 + adCode: string; // 行政区划代码 + spell?: string; // 城市名对应拼音拼写,方便用户搜索 + } + interface ChooseCityOptions extends BaseOptions { + showLocatedCity: boolean; // 是否显示当前定位城市,默认 false + showHotCities: boolean; // 是否显示热门城市,默认 true + cities: City[]; // 自定义城市列表,列表内对象字段见下表 + hotCities: City[]; // 自定义热门城市列表,列表内对象字段见下表 + success(result: { city: string; adCode: string; }): void; + } + /** + * 打开城市选择列表 + * + * 如果用户没有选择任何城市直接点击了返回,将不会触发回调函数。 + */ + function chooseCity(options: Partial): void; + //#endregion + + //#region 选择日期 https://docs.alipay.com/mini/api/ui-date + interface DatePickerOptions extends BaseOptions { + /** + * 返回的日期格式, + * 1. yyyy-MM-dd(默认) + * 2. HH:mm + * 3. yyyy-MM-dd HH:mm + * 4. yyyy-MM (最低基础库:1.1.1, 可用 canIUse('datePicker.object.format.yyyy-MM') 判断) + * 5. yyyy (最低基础库:1.1.1,可用 canIUse('datePicker.object.format.yyyy') 判断) + */ + format: 'yyyy-MM-dd' | 'HH:mm' | 'yyyy-MM-dd HH:mm' | 'yyyy-MM' | 'yyyy'; + /** 初始选择的日期时间,默认当前时间 */ + currentDate: string; + /** 最小日期时间 */ + startDate: string; + /** 最大日期时间 */ + endDate: string; + success(result: { date: string; }): void; + /** 11 用户取消操作 */ + fail(error: 11): void; + } + /** + * 打开日期选择列表 + */ + function datePicker(optiosn: Partial): void; + //#endregion + + //#region 动画 https://docs.alipay.com/mini/api/ui-animation + type TimingFunction = + | "linear" + | "ease" + | "ease-in" + | "ease-in-out" + | "ease-out" + | "step-start" + | "step-end"; + interface CreateAnimationOptions { + /** 动画持续时间,单位ms,默认值 400 */ + duration: number; + /** 定义动画的效果,默认值"linear",有效值:"linear","ease","ease-in","ease-in-out","ease-out","step-start","step-end" */ + timeFunction: TimingFunction; + /** 动画持续时间,单位 ms,默认值 0 */ + delay: number; + /** 设置transform-origin,默认为"50% 50% 0" */ + transformOrigin: string; + } + interface Animator { + actions: AnimationAction[]; + } + interface AnimationAction { + animates: Animate[]; + option: AnimationActionOption; + } + interface AnimationActionOption { + transformOrigin: string; + transition: AnimationTransition; + } + interface AnimationTransition { + delay: number; + duration: number; + timingFunction: TimingFunction; + } + interface Animate { + type: string; + args: any[]; + } + /** + * 创建动画实例 animation。调用实例的方法来描述动画,最后通过动画实例的export方法将动画数据导出并传递给组件的animation属性。 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + function createAnimation(options: Partial): Animation; + /** 动画实例可以调用以下方法来描述动画,调用结束后会返回自身,支持链式调用的写法。 */ + interface Animation { + /** + * 调用动画操作方法后要调用 step() 来表示一组动画完成, + * 可以在一组动画中调用任意多个动画方法, + * 一组动画中的所有动画会同时开始, + * 一组动画完成后才会进行下一组动画。 + * @param options 指定当前组动画的配置 + */ + step(options?: CreateAnimationOptions): void; + /** + * 导出动画操作 + * + * 注意: export 方法每次调用后会清掉之前的动画操作 + */ + export(): Animator; + /** 透明度,参数范围 0~1 */ + opacity(value: number): Animation; + /** 颜色值 */ + backgroundColor(color: string): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + width(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + height(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + top(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + left(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + bottom(length: number): Animation; + /** 长度值,如果传入 Number 则默认使用 px,可传入其他自定义单位的长度值 */ + right(length: number): Animation; + /** deg的范围-180~180,从原点顺时针旋转一个deg角度 */ + rotate(deg: number): Animation; + /** deg的范围-180~180,在X轴旋转一个deg角度 */ + rotateX(deg: number): Animation; + /** deg的范围-180~180,在Y轴旋转一个deg角度 */ + rotateY(deg: number): Animation; + /** deg的范围-180~180,在Z轴旋转一个deg角度 */ + rotateZ(deg: number): Animation; + /** 同transform-function rotate3d */ + rotate3d(x: number, y: number, z: number, deg: number): Animation; + /** + * 一个参数时,表示在X轴、Y轴同时缩放sx倍数; + * 两个参数时表示在X轴缩放sx倍数,在Y轴缩放sy倍数 + */ + scale(sx: number, sy?: number): Animation; + /** 在X轴缩放sx倍数 */ + scaleX(sx: number): Animation; + /** 在Y轴缩放sy倍数 */ + scaleY(sy: number): Animation; + /** 在Z轴缩放sy倍数 */ + scaleZ(sz: number): Animation; + /** 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 */ + scale3d(sx: number, sy: number, sz: number): Animation; + /** + * 一个参数时,表示在X轴偏移tx,单位px; + * 两个参数时,表示在X轴偏移tx,在Y轴偏移ty,单位px。 + */ + translate(tx: number, ty?: number): Animation; + /** + * 在X轴偏移tx,单位px + */ + translateX(tx: number): Animation; + /** + * 在Y轴偏移tx,单位px + */ + translateY(ty: number): Animation; + /** + * 在Z轴偏移tx,单位px + */ + translateZ(tz: number): Animation; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz,单位px + */ + translate3d(tx: number, ty: number, tz: number): Animation; + /** + * 参数范围-180~180; + * 一个参数时,Y轴坐标不变,X轴坐标延顺时针倾斜ax度; + * 两个参数时,分别在X轴倾斜ax度,在Y轴倾斜ay度 + */ + skew(ax: number, ay?: number): Animation; + /** 参数范围-180~180;Y轴坐标不变,X轴坐标延顺时针倾斜ax度 */ + skewX(ax: number): Animation; + /** 参数范围-180~180;X轴坐标不变,Y轴坐标延顺时针倾斜ay度 */ + skewY(ay: number): Animation; + /** + * 同transform-function matrix + */ + matrix( + a: number, + b: number, + c: number, + d: number, + tx: number, + ty: number + ): Animation; + /** 同transform-function matrix3d */ + matrix3d( + a1: number, + b1: number, + c1: number, + d1: number, + a2: number, + b2: number, + c2: number, + d2: number, + a3: number, + b3: number, + c3: number, + d3: number, + a4: number, + b4: number, + c4: number, + d4: number + ): Animation; + } + //#endregion + + //#region 画布 https://docs.alipay.com/mini/api/ui-canvas + interface ToTempFilePathOptions extends BaseOptions { + x: number; // 画布 x 轴起点,默认为 0 + y: number; // 画布 y 轴起点,默认为 0 + width: number; // 画布宽度,默认为 canvas 宽度 - x + height: number; // 画布高度,默认为 canvas 高度 - y + destWidth: number; // 输出的图片宽度,默认为 width + destHeight: number; // 输出的图片高度,默认为 height + } + type Color = string | number[] | number | CanvasAction; + + interface CanvasAction { + /** + * 创建一个颜色的渐变点。 + * 小于最小 stop 的部分会按最小 stop 的 color 来渲染,大于最大 stop 的部分会按最大 stop 的 color 来渲染。 + * + * @param stop 渐变点位置,值必须在 [0,1] 范围内 + * @param color 颜色值 + */ + addColorStop(stop: number, color: Color): void; + } + + interface TextMetrics { + width: number; + } + + interface ConvasContext { + font: string; + /** + * 把当前画布的内容导出生成图片,并返回文件路径。 + */ + toTempFilePath(options?: Partial): void; + /** + * textAlign 是 Canvas 2D API 描述绘制文本时,文本的对齐方式的属性。注意,该对齐是基于 + * CanvasRenderingContext2D.fillText 方法的x的值。所以如果 textAlign="center",那么该文本将画在 x-50%*width + */ + setTextAlign(textAlign: 'left' | 'right' | 'center' | 'start' | 'end'): void; + /** + * textBaseline 是 Canvas 2D API 描述绘制文本时,当前文本基线的属性。 + */ + setTextBaseline(textBaseline: 'top' | 'hanging' | 'middle' | 'alphabetic' | 'ideographic' | 'bottom'): void; + /** + * 设置填充色。 + * + * 如果没有设置 fillStyle,则默认颜色为 black。 + */ + setFillStyle(color: Color): void; + /** + * 设置边框颜色。 + * + * 如果没有设置 strokeStyle,则默认颜色为 black。 + */ + setStrokeStyle(color: Color): void; + /** + * 设置阴影样式。 + * 如果没有设置,offsetX 的默认值为 0, offsetY 的默认值为 0, blur 的默认值为 0,color 的默认值为 black。 + * @param offsetX 阴影相对于形状水平方向的偏移 + * @param offsetY 阴影相对于形状竖直方向的偏移 + * @param blur 0~100 阴影的模糊级别,值越大越模糊 + * @param color 阴影颜色 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: Color): void; + + /** + * 创建一个线性的渐变色。 + * + * @param x0 起点 x 坐标 + * @param y0 起点 y 坐标 + * @param x1 终点 x 坐标 + * @param y1 终点 y 坐标 + */ + createLinearGradient(x0: number, y0: number, x1: number, y1: number): CanvasAction; + + /** + * 创建一个圆形的渐变色。 + * 起点在圆心,终点在圆环。 + * 需要使用 addColorStop() 来指定渐变点,至少需要两个。 + * @param x 圆心 x 坐标 + * @param y 圆心 y 坐标 + * @param r 圆半径 + * @returns + */ + createCircularGradient(x: number, y: number, r: number): CanvasAction; + + /** + * 设置线条的宽度。 + * @param lineWidth 线条宽度,单位为 px + */ + setLineWidth(lineWidth: number): void; + + /** + * 设置线条的端点样式。 + * + * @param lineCap 线条的结束端点样式 + */ + setLineCap(lineCap: 'round' | 'butt' | 'square'): void; + + /** + * 设置线条的交点样式。 + * + * @param lineJoin 线条的结束交点样式 + */ + setLineJoin(lineJoin: 'round' | 'bevel' | 'miter'): void; + + /** + * 设置最大斜接长度,斜接长度指的是在两条线交汇处内角和外角之间的距离。 当 setLineJoin() 为 miter 时才有效。超过最大倾斜长度的,连接处将以 lineJoin 为 bevel 来显示 + * + * @param miterLimit 最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + + /** + * 创建一个矩形。 + * + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + rect(x: number, y: number, width: number, height: number): void; + + /** + * 填充矩形。 + * 用 setFillStyle() 设置矩形的填充色,如果没设置则默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + fillRect(x: number, y: number, width: number, height: number): void; + + /** + * 画一个矩形(非填充)。 + * 用 setFillStroke() 设置矩形线条的颜色,如果没设置默认是 black。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + strokeRect(x: number, y: number, width: number, height: number): void; + + /** + * 清除画布上在该矩形区域内的内容。 + * clearRect 并非画一个白色的矩形在地址区域,而是清空,为了有直观感受,可以对 canvas 加了一层背景色。 + * @param x 矩形左上角的 x 坐标 + * @param y 矩形左上角的 y 坐标 + * @param width 矩形路径宽度 + * @param height 矩形路径高度 + */ + clearRect(x: number, y: number, width: number, height: number): void; + + /** + * 对当前路径中的内容进行填充。默认的填充色为黑色。 + * + */ + fill(): void; + + /** + * 画出当前路径的边框。默认 black。 + * stroke() 描绘的的路径是从 beginPath() 开始计算,但是不会将 strokeRect() 包含进去 + */ + stroke(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * 如果关闭路径后没有调用 fill() 或者 stroke() 并开启了新的路径,那之前的路径将不会被渲染。 + */ + beginPath(): void; + + /** + * 关闭一个路径 + * 关闭路径会连接起点和终点。 + * + */ + closePath(): void; + + /** + * 把路径移动到画布中的指定点,不创建线条。 + * 用 stroke() 方法来画线条 + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + moveTo(x: number, y: number): void; + + /** + * lineTo 方法增加一个新点,然后创建一条从上次指定点到目标点的线。 + * 用 stroke() 方法来画线条 + * + * @param x 目标位置 x 坐标 + * @param y 目标位置 y 坐标 + */ + lineTo(x: number, y: number): void; + + /** + * 画一条弧线。 + * 创建一个圆可以用 arc() 方法指定其实弧度为0,终止弧度为 2 * Math.PI。 + * + * @param x + * @param y + * @param r + * @param sAngle + * @param eAngle + */ + arc(x: number, y: number, r: number, sAngle: number, eAngle: number): void; + + /** + * 创建三次方贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cp1x + * @param cp1y + * @param cp2x + * @param cp2y + * @param x + * @param y + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + + /** + * 将当前创建的路径设置为当前剪切路径。 + * + */ + clip(): void; + + /** + * 创建二次贝塞尔曲线路径。 + * 曲线的起始点为路径中前一个点。 + * @param cpx 贝塞尔控制点 x 坐标 + * @param cpy 贝塞尔控制点 y 坐标 + * @param x 结束点 x 坐标 + * @param y 结束点 y 坐标 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + + /** + * 在调用scale方法后,之后创建的路径其横纵坐标会被缩放。多次调用scale,倍数会相乘。 + * + * @param scaleWidth 横坐标缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + * @param scaleHeight 纵坐标轴缩放倍数 (1 = 100%,0.5 = 50%,2 = 200%) + */ + scale(scaleWidth: number, scaleHeight: number): void; + + /** + * 以原点为中心,原点可以用 translate方法修改。顺时针旋转当前坐标轴。多次调用rotate,旋转的角度会叠加。 + * + * @param rotate 旋转角度,以弧度计(degrees * Math.PI/180;degrees 范围为0~360) + */ + rotate(rotate: number): void; + + /** + * 对当前坐标系的原点(0, 0)进行变换,默认的坐标系原点为页面左上角。 + * + * @param x 水平坐标平移量 + * @param y 竖直坐标平移量 + */ + translate(x: number, y: number): void; + + /** + * 设置字体大小。 + * + * @param fontSize 字号 + */ + setFontSize(fontSize: number): void; + + /** + * 在画布上绘制被填充的文本。 + * + * @param text 文本 + * @param x 绘制文本的左上角 x 坐标 + * @param y 绘制文本的左上角 y 坐标 + */ + fillText(text: string, x: number, y: number): void; + + /** + * 绘制图像,图像保持原始尺寸。 + * + * @param imageResource 图片资源, 只支持线上 cdn 地址或离线包地址,线上 cdn 需返回头 Access-Control-Allow-Origin: * + * @param x 图像左上角 x 坐标 + * @param y 图像左上角 y 坐标 + * @param width 图像宽度 + * @param height 图像高度 + */ + drawImage(imageResource: string, x: number, y: number, width: number, height: number): void; + + /** + * 设置全局画笔透明度。 + * + * @param alpha 透明度,0 表示完全透明,1 表示不透明 范围 [0, 1] + */ + setGlobalAlpha(alpha: number): void; + + /** + * 设置虚线的样式 + * + * @param segments 一组描述交替绘制线段和间距(坐标空间单位)长度的数字。 如果数组元素的数量是奇数, 数组的元素会被复制并重复。例如, [5, 15, 25] 会变成 [5, 15, 25, 5, 15, 25]。 + */ + setLineDash(segments: number[]): void; + + /** + * 使用矩阵多次叠加当前变换的方法,矩阵由方法的参数进行描述。你可以缩放、旋转、移动和倾斜上下文。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + transform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 使用单位矩阵重新设置(覆盖)当前的变换并调用变换的方法,此变换由方法的变量进行描述。 + * + * @param scaleX 水平缩放 + * @param skewX 水平倾斜 + * @param skewY 垂直倾斜 + * @param scaleY 垂直缩放 + * @param translateX 水平移动 + * @param translateY 垂直移动 + */ + setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; + + /** + * 保存当前的绘图上下文。 + * + */ + save(): void; + + /** + * 恢复之前保存的绘图上下文。 + */ + restore(): void; + + /** + * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中。 + * 绘图上下文需要由 my.createCanvasContext(canvasId) 来创建。 + * @param [reserve] 本次绘制是否接着上一次绘制,即 reserve 参数为 false 时则在本次调用 drawCanvas绘制之前 native 层应先清空画布再继续绘制;若 reserver 参数为true 时,则保留当前画布上的内容,本次调用drawCanvas绘制的内容覆盖在上面,默认 false + */ + draw(reserve?: boolean): void; + + measureText(text: string): TextMetrics; + } + /** + * 创建 canvas 绘图上下文 + * + * 该绘图上下文只作用于对应 canvasId 的 + */ + function createCanvasContext(canvasId: string): ConvasContext; + //#endregion + + //#region 地图 https://docs.alipay.com/mini/api/ui-map + interface GetCenterLocationOptions extends BaseOptions { + success?(res: { longitude: string; latitude: string; }): void; + } + + interface MapContext extends BaseOptions { + /** + * 获取当前地图中心的经纬度,返回 gcj02 坐标系的值,可以用于 my.openLocation + * + * @param options + */ + getCenterLocation(options: GetCenterLocationOptions): void; + /** + * 将地图中心移动到当前定位点,需要配合 map 组件的 show-location 使用 + */ + moveToLocation(): void; + } + + /** + * 创建并返回一个 map 上下文对象 mapContext。 + * + * @param mapId + * @returns + */ + function createMapContext(mapId: string): MapContext; + + //#endregion + + //#region 键盘 https://docs.alipay.com/mini/api/ui-hidekeyboard + /** + * 隐藏键盘 + * + */ + function hideKeyboard(): void; + //#endregion + + //#region 滚动 https://docs.alipay.com/mini/api/scroll + interface PageScrollToOptions { + scrollTop: number; // 滚动到页面的目标位置,单位 px + } + + /** + * 滚动到页面的目标位置 + * + * @param options + */ + function pageScrollTo(options: PageScrollToOptions): void; + //#endregion + + //#region 节点查询 https://docs.alipay.com/mini/api/selector-query + interface RectArea { + /** 节点的左边界坐标 */ + left: number; + /** 节点的右边界坐标 */ + right: number; + /** 节点的上边界坐标 */ + top: number; + /** 节点的下边界坐标 */ + bottom: number; + /** 节点的宽度 */ + width: number; + /** 节点的高度 */ + height: number; + } + interface NodesRefRect extends RectArea { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + } + interface NodeRefOffset { + /** 节点的ID */ + id: string; + /** 节点的dataset */ + dataset: any; + /** 节点的水平滚动位置 */ + scrollLeft: number; + /** 节点的竖直滚动位置 */ + scrollTop: number; + } + interface NodesRef { + /** + * 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位。 + * 其功能类似于DOM的getBoundingClientRect。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的位置用 + * left、right、top、bottom、width、height字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后 + * 节点信息会在callback中返回。 + */ + boundingClientRect( + callback?: (rect: T) => void + ): SelectorQuery; + /** + * 添加节点的滚动位置查询请求,以像素为单位。 + * 节点必须是scroll-view或者viewport。 + * 返回值是nodesRef对应的selectorQuery。 + * 返回的节点信息中,每个节点的滚动位置用scrollLeft、scrollHeight字段描述。 + * 如果提供了callback回调函数,在执行selectQuery的exec方法后,节点信息会在callback中返回。 + */ + scrollOffset(callback?: (rect: NodeRefOffset) => void): SelectorQuery; + // /** + // * 获取节点的相关信息,需要获取的字段在fields中指定。 + // * 返回值是nodesRef对应的selectorQuery。 + // */ + // fields( + // fields: NodeRefFieldsOptions, + // callback?: (result: any) => void + // ): SelectorQuery; + } + /** + * SelectorQuery对象实例 + */ + interface SelectorQuery { + // /** + // * 将选择器的选取范围更改为自定义组件component内 + // * (初始时,选择器仅选取页面范围的节点,不会选取任何自定义组件中的节点 + // * @version 1.6.0 + // */ + // in(component: Component): SelectorQuery; + /** + * 在当前页面下选择第一个匹配选择器selector的节点,返回一个NodesRef对象实例,可以用于获取节点信息。 + * selector类似于CSS的选择器,但仅支持下列语法。 + * + ID选择器:#the-id + * + class选择器(可以连续指定多个):.a-class.another-class + * + 子元素选择器:.the-parent > .the-child + * + 后代选择器:.the-ancestor .the-descendant + * + 跨自定义组件的后代选择器:.the-ancestor >>> .the-descendant + * + 多选择器的并集:#a-node, .some-other-nodes + */ + select(selector: string): NodesRef; + /** + * 在当前页面下选择匹配选择器selector的节点,返回一个NodesRef对象实例。 + * 与selectorQuery.selectNode(selector)不同的是,它选择所有匹配选择器的节点。 + */ + selectAll(selector: string): NodesRef; + /** + * 选择显示区域,可用于获取显示区域的尺寸、滚动位置等信息 + * 返回一个NodesRef对象实例。 + */ + selectViewport(): NodesRef; + /** + * 执行所有的请求 + * 请求结果按请求次序构成数组,在callback的第一个参数中返回。 + */ + exec(callback?: (result: any[]) => void): void; + } + /** + * 获取一个节点查询对象 SelectorQuery。 + * + * @param page 可以指定 page 属性,默认为当前页面 + * @returns + */ + function createSelectorQuery(page?: any): SelectorQuery; + //#endregion + + //#region 级联选择 https://docs.alipay.com/mini/api/ewdxl3 + interface MultiLevelSelectItem { + name: string; + subList?: MultiLevelSelectItem[]; + } + interface MultiLevelSelectOptions extends BaseOptions { + title?: string; // 标题 + list?: MultiLevelSelectItem[]; // 选择数据列表 + name?: string; // 条目名称 + subList?: MultiLevelSelectItem[]; // 子条目列表 + success?(res: { + success: boolean; // 是否选择完成,取消返回false + result: MultiLevelSelectItem[]; // 选择的结果,如[{“name”:”杭州市”},{“name”:”上城区”},{“name”:”古翠街道”}] + }): void; + } + + function multiLevelSelect(options?: MultiLevelSelectOptions): void; + //#endregion +} + +// 开放接口 +declare namespace my { + //#region 用户授权 https://docs.alipay.com/mini/api/openapi-authorize + interface GetAuthCodeOptions extends BaseOptions { + scopes?: string | string[]; // 授权类型,默认 auth_base。支持 auth_base(静默授权)/ auth_user(主动授权) / auth_zhima(芝麻信用) + success?(res: { + authCode: string; // 授权码 + authErrorScope: { + [scope: string]: number; + }; // 失败的授权类型,key是授权失败的 scope,value 是对应的错误码 + authSucessScope: string[]; // 成功的授权 scope + }): void; + } + /** + * 获取授权码。 + * 详细用户授权接入参考 [指引](https://docs.alipay.com/mini/introduce/auth)。 + */ + function getAuthCode(options: GetAuthCodeOptions): void; + //#endregion + + //#region 客户端获取会员信息 https://docs.alipay.com/mini/api/userinfo + interface GetAuthUserInfoOptions extends BaseOptions { + success?(res: { + nickName: string; // 用户昵称 + avatar: string; // 用户头像链接 + }): void; + } + /** + * 客户端获取会员信息 + * 获取会员信息首先需要获取用户授权,详细会员信息获取参考[指引](https://docs.alipay.com/mini/introduce/auth),采用 jsapi 调用的方式。 + */ + function getAuthUserInfo(options: GetAuthUserInfoOptions): void; + //#endregion + + //#region 小程序唤起支付 https://docs.alipay.com/mini/api/openapi-pay + interface TradePayOptions extends BaseOptions { + tradeNO?: string; // 接入小程序支付时传入此参数。此参数为支付宝交易号 + success?(res: { + // resultCode | 描述 + // -----------|------ + // 9000 | 订单支付成功 + // 8000 | 正在处理中 + // 4000 | 订单支付失败 + // 6001 | 用户中途取消 + // 6002 | 网络连接出错 + // 6004 | 支付结果未知(有可能已经支付成功),请查询商户订单列表中订单的支付状态 + // 99 | 用户点击忘记密码导致快捷界面退出(only iOS) + resultCode: string; + }): void; + } + /** + * 发起支付。 + * 详细接入支付方式参考[指引](https://docs.alipay.com/mini/introduce/pay)。 + * @param options + */ + function tradePay(options: TradePayOptions): void; + //#endregion + + //#region 支付代扣签约 https://docs.alipay.com/mini/api/pay-sign + interface PaySignCenterOptions extends BaseOptions { + signStr: string; // 签约字符串 + } + + /** + * 签约中心 + * + * 返回码 | 含义 + * ------|------ + * 7000 | 协议签约成功 + * 7001 | 签约结果未知(有可能已经签约成功),请根据外部签约号查询签约状态 + * 7002 | 协议签约失败 + * 6001 | 用户中途取消 + * 6002 | 网络连接错误 * @param options + */ + function paySignCenter(options: PaySignCenterOptions): void; + //#endregion + + //#region 小程序二维码 https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/api/openapi-qrcode + // @see https://docs.alipay.com/mini/introduce/qrcode + //#endregion + + //#region 跳转支付宝卡包 https://docs.alipay.com/mini/api/card-voucher-ticket + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openCardList(): void; + interface OpenMerchantCardList extends BaseOptions { + partnerId: string; // 商户编号 + } + + /** + * 打开支付宝卡列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * @param options + */ + function openMerchantCardList(options: OpenMerchantCardList): void; + + interface OpenCardDetailOptions extends BaseOptions { + passId: string; // 卡实例Id + } + /** + * 打开当前用户的某张卡的详情页 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * passId获取方式: + * 1)通过alipass创建的卡 + * 调用alipay.pass.instance.add(支付宝pass新建卡券实例接口)接口,在出参“result”中可获取 + * 2)通过会员卡创建的卡 + * 调用alipay.marketing.card.query(会员卡查询)接口,在schema_url中可获取,具体参数为“p=xxx”,xxx即为passId。 + */ + function openCardDetail(options: OpenCardDetailOptions): void; + + /** + * 打开支付宝券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + * + * @param options + */ + function openVoucherList(): void; + + interface OpenMerchantVoucherListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开当前用户的某个商户的券列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantVoucherList(options: OpenMerchantVoucherListOptions): void; + + interface OpenVoucherDetailOptions1 extends BaseOptions { + passId: string; // 券实例Id,调用券发放接口可以获取该参数(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号,以 2088 为开头(如果传入了passId则不需传入) + serialNumber: string; // 序列号,调用新建卡券模板可以获取该参数(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(非口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openVoucherDetail(options: OpenVoucherDetailOptions1 | OpenVoucherDetailOptions2): void; + + interface OpenKBVoucherDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需传入) + } + interface OpenKBVoucherDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需传入) + serialNumber: string; // 序列号(如果传入了passId则不需传入) + } + /** + * 打开当前用户的某张券的详情页(口碑) + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openKBVoucherDetail(options: OpenKBVoucherDetailOptions1 | OpenKBVoucherDetailOptions2): void; + + /** + * 打开支付宝票列表。 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketList(): void; + + interface OpenMerchantTicketListOptions extends BaseOptions { + partnerId: string; // 商户编号 + } + /** + * 打开某个商户的票列表 + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openMerchantTicketList(options: OpenMerchantTicketListOptions): void; + + interface OpenTicketDetailOptions1 extends BaseOptions { + passId: string; // 卡实例Id(如果传入了partnerId和serialNumber则不需要传入passId) + } + interface OpenTicketDetailOptions2 extends BaseOptions { + partnerId: string; // 商户编号(如果传入了passId则不需要传入partnerId) + serialNumber: string; // 序列号(如果传入了passId则不需要传入serialNumber) + } + /** + * 打开当前用户的某张票的详情页 + * + * 有关支付宝卡包详细功能,见[支付宝卡包产品介绍](https://docs.alipay.com/mini/introduce/voucher) + */ + function openTicketDetail(options: OpenTicketDetailOptions1 | OpenTicketDetailOptions2): void; + //#endregion + + //#region 会员开卡授权 https://docs.alipay.com/mini/api/add-card-auth + interface AddCardAuthResult { + success: true | boolean; // true 表示领卡成功 + resultStatus: string; // 9000 表示成功 + result: { + app_id: string; // 应用id + auth_code: string; // 授权码,用于换取authtoken + state: string; // 授权的state + scope: string; // 授权scope + template_id: string; // 会员卡模板Id + request_id: string; // 会员卡表单信息请求Id + out_string: string; // 会员卡领卡链接透传参数 + }; + } + interface AddCardAuthResult { + success: false | boolean; // false 表示领卡失败 + /** + * 失败的错误码 + * 领卡失败 code 说明 + * 名称 | 类型 | 说明 + * -----|-----|----- + * JSAPI_SERVICE_TERMINATED | String | 用户取消 + * JSAPI_PARAM_INVALID | String | url 为空或非法参数 + * JSAPI_SYSTEM_ERROR | String | 系统错误 + */ + code: string; + } + interface AddCardAuthOptions extends BaseOptions { + /** + * 开卡授权的页面地址,从alipay.marketing.card.activateurl.apply接口获取 + */ + url: string; + success?(res: AddCardAuthResult): void; + } + /** + * 小程序唤起会员开卡授权页面,小程序接入会员卡[点此查看](https://docs.alipay.com/mini/introduce/card) + */ + function addCardAuth(options: AddCardAuthOptions): void; + //#endregion + + //#region 芝麻认证 https://docs.alipay.com/mini/api/zm-service + interface StartZMVerifyOptions extends BaseOptions { + bizNo: string; // 认证标识 + success?(res: { + token: string; // 认证标识 + passed: string; // 认证是否通过 + reason?: string; // 认证不通过原因 + }): void; + } + /** + * 芝麻认证接口,调用此接口可以唤起芝麻认证页面并进行人脸身份验证。 + * 有关芝麻认证的产品和接入介绍,详见 [芝麻认证](https://docs.alipay.com/mini/introduce/zm-verify)。 + * 需要通过蚂蚁开发平台,调用certification.initialize接口进行[认证初始化](https://docs.alipay.com/zmxy/271/105914)。获得biz_no 后,方能通过以下接口激活芝麻认证小程序。 + */ + function startZMVerify(options: StartZMVerifyOptions): void; + //#endregion + + //#region 信用借还 https://docs.alipay.com/mini/api/zmcreditborrow + interface ZMCreditBorrowOptions extends BaseOptions { + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+随机数 + * + */ + out_order_no: string; + /** + * 信用借还的产品码,传入固定值:w1010100000000002858 + */ + product_code: string; + /** + * 物品名称,最长不能超过14个汉字 + */ + goods_name: string; + /** + * 租金单位,租金+租金单位组合才具备实际的租金意义。 + * 取值定义如下: + * DAY_YUAN: 元 / 天 + * HOUR_YUAN: 元 / 小时 + * YUAN: 元 + * YUAN_ONCE: 元 / 次 + */ + rent_unit: string; + /** + * 租金,租金 + 租金单位组合才具备实际的租金意义。 + * > 0.00元,代表有租金 + * = 0.00元,代表无租金,免费借用 + * 注:参数传值必须 >= 0,传入其他值会报错参数非法 + */ + rent_amount: string; + /** + * 押金,金额单位:元。 + * 注:不允许免押金的用户按此金额支付押金;当物品丢失时,赔偿金额不得高于该金额。 + */ + deposit_amount: string; + /** + * 该字段目前默认传Y; + * 是否支持当借用用户信用不够(不准入)时,可让用户支付押金借用: + * Y: 支持 + * N: 不支持 + * 注:支付押金的金额等同于deposit_amount。 + */ + deposit_state?: string; // 该字段目前默认传Y; + /** + * 回调到商户的小程序schema地址。说明:商户的回调地址可以在商户后台里进行配置,服务端回调时,首先根据参数:invoke_type 查询是否有对应的配置地址,如果有,则使用已定义的地址,否则,使用该字段定义的地址执行回调; + * 参考表格下方的说明一; + * 小程序回调地址参考表格下方的说明三; + * 说明一: + * 支付宝商户账号登录我的商家服务打开入口链接; + * 商家服务中选择“您可能需要->信用借还”或者点击链接; + * 场景ID配置->配置新ID,选择对应的业务类型、服务类目和联盟,将生成的场景ID作为credit_biz的值传入即可; + * 回调地址配置->设置小程序回调地址,注意:若设置了该回调地址,则接口my.zmCreditBorrow中的入参invoke_return_url将会失效,以该处设置为准; + * 说明三: + * 小程序回调地址示例一:alipays://platformapi/startapp?appId=1999; + * 小程序回调地址示例二:alipays://platformapi/startapp?appId=1999&page=pages/map; + */ + invoke_return_url?: string; + /** + * 商户访问蚂蚁的对接模式,默认传TINYAPP: + * TINYAPP:回跳至小程序地址; + * WINDOWS:支付宝服务窗,默认值; + */ + invoke_type?: 'TINYAPP' | 'TINYAPP' | 'WINDOWS' | string; + /** + * 信用业务服务,注意:该字段不能为空,且必须根据说明的指引配置商户专属的场景ID,商户自助接入时,登录后台可配置场景ID,将后台配置的场景ID作为该字段的输入; + * 参考说明一自助进行配置; + */ + credit_biz: string; + /** + * 商户订单创建的起始借用时间,格式:YYYY - MM - DD HH: MM: SS。如果不传入或者为空,则认为订单创建起始时间为调用此接口时的时间。 + */ + borrow_time?: string; + /** + * 到期时间,不允许为空,请根据实际业务合理设置该值,格式:YYYY - MM - DD HH: MM: SS,是指最晚归还时间,表示借用用户如果超过此时间还未完结订单(未归还物品或者未支付租金)将会进入逾期状态,芝麻会给借用用户发送催收提醒;需要晚于borrow_time。 + */ + expiry_time: string; + /** + * 借用用户的手机号码,可选字段。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + mobile_no?: string; + /** + * 物品借用地点的描述,便于用户知道物品是在哪里借的。可为空 + * + */ + borrow_shop_name?: string; + /** + * 租金的结算方式,非必填字段,默认是支付宝租金结算支付 merchant:表示商户自行结算,信用借还不提供租金支付能力; alipay:表示使用支付宝支付功能,给用户提供租金代扣及赔偿金支付能力; + * + */ + rent_settle_type?: 'merchant' | 'alipay' | string; + /** + * 商户请求状态上下文。商户发起借用服务时,需要在借用结束后返回给商户的参数,格式:json; + * 如果json的某一项值包含中文,请使用encodeURIComponent对该值进行编码; + * @example + * var ext = { + * name: encodeURIComponent('名字') + * }; + * var obj = { + * invoke_state: JSON.stringify(ext) + * } + */ + invoke_state?: string; + /** + * 租金信息描述, 长度不超过14个汉字,只用于页面展示给C端用户,除此之外无其他意义。 + */ + rent_info?: string; + /** + * 借用用户的真实姓名,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + name?: string; + /** + * 借用用户的真实身份证号,非必填字段。但name和cert_no必须同时非空,或者同时为空,一旦传入会对用户身份进行校验。 + */ + cert_no?: string; + /** + * 借用用户的收货地址,可选字段,最大长度128。推荐商户传入此值,会将此手机号码与用户身份信息进行匹配验证,防范欺诈风险。 + */ + address?: string; + success?(res: { + /** + * 6001 用户取消了业务流程 + * 6002 网络异常 + * 9000 成功 + * 4000 系统异常 + */ + resultStatus: '6001' | '6002' | '9000' | '4000' | string; + result: { + /** + * 商户发起借用服务时传入的参数,需要在借用结束后返回给商户的参数 + * @example + * {"user_name":"john"} + */ + invoke_state: string; + /** + * 外部订单号,需要唯一,由商户传入,芝麻内部会做幂等控制,格式为:yyyyMMddHHmmss+4位随机数 + * @example + * 201610010000283627 + */ + out_order_no: string; + /** + * 芝麻信用借还订单号 + * @example + * 10020027631 + */ + order_no: string; + /** + * 是否准入:Y:准入;N:不准入(该字段目前无实际意义) + */ + admit_state: 'Y' | 'N' | string; + /** + * 物品借用/租赁者的用户id + * @example + * 2088202924240029 + */ + user_id: string; + callbackData: any; // todo only in example + } + }): void; + } + function zmCreditBorrow(options: ZMCreditBorrowOptions): void; + //#endregion + + //#region 文本风险识别 https://docs.alipay.com/mini/api/text-identification + type TextRiskIdentificationType = 'keyword' | '0' | '1' | '2' | '3' | string; + interface TextRiskIdentificationOptions extends BaseOptions { + /** + * 需要进行风险识别的文本内容 + */ + content: string; + /** + * 识别类型:keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType[]; + success?(res: { + result: { + /** + * 目标内容文本识别到的类型,keyword 表示关键词、0 表示广告、1表示涉政、2表示涉黄、3表示低俗辱骂 + */ + type: TextRiskIdentificationType; + /** + * 仅当识别命中了 type 为 keyword 时,才会返回该字段 + */ + hitKeywords?: string[]; + /** + * 识别命中得分,最高分100分。仅当识别没有命中 keyword ,但入参中包含了广告或涉政或涉黄时,才会返回该字段 + */ + score?: string; + }; + fail?(res: { + /** + * 识别错误码 + */ + error: string; + /** + * 识别错误消息 + */ + errorMessage: string; + }): void; + }): void; + } + /** + * 文本风险识别, **支付宝客户端10.1.10及以上版本支持。**详细接入参考[指引](https://docs.alipay.com/mini/introduce/text-identification) + */ + function textRiskIdentification(options: TextRiskIdentificationOptions): void; + //#endregion + + //#region 小程序跳转 https://docs.alipay.com/mini/api/open-miniprogram + interface NavigateToMiniProgramOptions extends BaseOptions { + /** + * 要跳转的目标小程序appId + */ + appId: string; + /** + * 打开的页面路径,如果为空则打开首页 + */ + path?: string; + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch() ,App.onShow() 中获取到这份数据 + */ + extraData?: any; + /** + * 要打开的小程序版本,有效值 develop(开发版),trial(体验版),release(正式版) ,仅在当前小程序为开发版或体验版时此参数有效;如果当前小程序是正式版,则打开的小程序必定是正式版。默认值 release + */ + envVersion?: 'develop' | 'trial' | 'release' | string; + } + /** + * 跳转到其他小程序。详细接入参考[指引](https://docs.alipay.com/mini/introduce/open-miniprogram) + * @param options + */ + function navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; + interface NavigateBackMiniProgramOptions extends BaseOptions { + /** + * 需要传递给目标小程序的数据,目标小程序可在 App.onLaunch(),App.onShow() 中获取到这份数据 + */ + extraData?: any; + } + /** + * 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功 + */ + function navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; + //#endregion + + //#region webview组件控制 https://docs.alipay.com/mini/api/webview-context + interface WebViewContext { + postMessage(param: any): void; + } + /** + * 创建并返回 web-view 上下文 webViewContext 对象。 + * + * @param webviewId 要创建的web-view所对应的id属性 + */ + function createWebViewContext(webviewId: string): WebViewContext; + //#endregion +} + +// 多媒体 +declare namespace my { + //#region 图片 https://docs.alipay.com/mini/api/media-image + type ImageSourceType = "album" | "camera"; + interface ChooseImageOptions extends BaseOptions { + /** 最大可选照片数,默认1张 */ + count: number; + /** 相册选取或者拍照,默认 [‘camera’,‘album’] */ + sourceType: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: { + /** + * 图片文件描述 + */ + apFilePaths: string[]; + }): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: Partial): void; + + interface PreviewImageOptions extends BaseOptions { + /** 当当前显示图片索引,默认 0 */ + current?: number; + /** 要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + + interface SaveImageOptions extends BaseOptions { + /** + * 要保存的图片链接 + */ + url: string; + success?(res: { errMsg: string }): void; + } + /** + * 保存在线图片到手机相册。 + */ + function saveImage(options: SaveImageOptions): void; + + interface CompressImageOptions extends BaseOptions { + /** + * 要压缩的图片地址数组 + */ + apFilePaths: string[]; + /** + * 压缩级别,支持 0 ~ 4 的整数,默认 4。详见「compressLevel表 说明表」 + * compressLevel表 + * compressLevel | 说明 + * --------------|----- + * 0 | 低质量 + * 1 | 中等质量 + * 2 | 高质量 + * 3 | 不压缩 + * 4 | 根据网络适应 + */ + compressLevel?: 0 | 1 | 2 | 3 | 4; + success?(res: { + /** + * 压缩后的路径数组 + */ + apFilePaths: string[]; + }): void; + } + /** + * 压缩图片。扫码体验: + */ + function compressImage(options: CompressImageOptions): void; + + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片路径,目前支持: + * - 网络图片路径 + * - apFilePath路径 + * - 相对路径 + */ + src: string; + success?(res: { + width: number; // 图片宽度(单位px) + height: number; // 图片高度(单位px) + path: string; // 图片本地路径 + }): void; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + //#endregion +} + +// 缓存 +declare namespace my { + //#region 缓存 https://docs.alipay.com/mini/api/storage + interface SetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 需要存储的内容 */ + data: any; + } + /** + * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的数据。 + * 这是异步接口。 + */ + function setStorage(options: SetStorageOptions): void; + + /** + * 同步将数据存储在本地缓存中指定的 key 中。 + * 这是同步接口。 + * + * @param key 本地缓存中的指定的 key + * @param data 需要存储的内容 + */ + function setStorageSync(options: { key: string; data: any; }): void; + + interface GetStorageOptions extends BaseOptions { + /** 本地缓存中的指定的 key */ + key: string; + /** 接口调用的回调函数,res = {data: key对应的内容} */ + success(res: DataResponse): void; + } + /** + * 获取缓存数据。 + * 这是异步接口。 + */ + function getStorage(options: GetStorageOptions): void; + + /** + * 同步获取缓存数据。 + * 这是同步接口 + */ + function getStorageSync(options: { key: string; }): any; + + interface RemoveStorageOptions extends BaseOptions { + key: string; + } + /** + * 删除缓存数据。 + * 这是异步接口。 + */ + function removeStorage(options: RemoveStorageOptions): void; + + /** + * 同步删除缓存数据。 + * 这是同步接口。 + * @param key 缓存数据的key + */ + function removeStorageSync(options: { key: string; }): void; + + /** + * 清除本地数据缓存。 + * 这是异步接口。 + */ + function clearStorage(): void; + + /** + * 同步清除本地数据缓存。 + * 这是同步接口。 + */ + function clearStorageSync(): void; + + interface StorageInfo { + /** + * 当前storage中所有的key + */ + keys: string[]; + /** + * 当前占用的空间大小, 单位kb + */ + currentSize: number; + /** + * 限制的空间大小,单位kb + */ + limitSize: number; + } + interface GetStorageInfoOptions extends BaseOptions { + success(res: StorageInfo): void; + } + /** + * 异步获取当前storage的相关信息 + */ + function getStorageInfo(options: GetStorageInfoOptions): void; + + function getStorageInfoSync(): StorageInfo; + //#endregion +} + +// 文件 +declare namespace my { + //#region 文件 https://docs.alipay.com/mini/api/file + interface SavedFileData { + /** 文件保存路径 */ + apFilePath: string; + } + interface SaveFileOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + success?(res: SavedFileData): void; + } + /** + * 保存文件到本地(本地文件大小总容量限制:10M) + */ + function saveFile(options: SaveFileOptions): void; + + interface GetFileInfoSuccess { + /** 文件大小,单位:B */ + size: number; + /** 摘要结果 */ + digest: string; + } + interface GetFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 摘要算法,支持md5和sha1,默认为md5 */ + digestAlgorithm?: 'md5' | 'sha1'; + success?(options: GetFileInfoSuccess): void; + } + /** + * 获取文件信息 + * 基础库版本 1.4.0 开始支持,低版本需做兼容处理 + */ + function getFileInfo(options: GetFileInfoOptions): void; + + interface SavedFileInfoData { + /** + * 文件大小,单位B + */ + size: number; + /** + * 创建时间 + */ + createTime: number; + } + interface GetSavedFileInfoOptions extends BaseOptions { + /** 文件路径 */ + apFilePath: string; + /** 接口调用成功的回调函数 */ + success?(res: SavedFileInfoData): void; + } + /** + * 获取保存的文件信息 + */ + function getSavedFileInfo(options: GetSavedFileInfoOptions): void; + + interface GetSavedFileListOptions extends BaseOptions { + success?(res: { + fileList: Array<{ + /** 文件大小 */ + size: number; + /** 创建时间 */ + createTime: number; + /** 文件路径 */ + apFilePath: string; + }> + }): void; + } + function getSavedFileList(options: GetSavedFileListOptions): void; + + type RemoveSavedFileOptions = GetSavedFileInfoOptions; + /** + * 删除某个保存的文件 + */ + function removeSavedFile(options: RemoveSavedFileOptions): void; + //#endregion +} + +// 位置 +declare namespace my { + //#region 位置 https://docs.alipay.com/mini/api/location + interface LocationData { + /** 经度 */ + longitude: string; + /** 纬度 */ + latitude: string; + /** 精确度,单位m */ + accuracy: string; + /** + * 水平精确度,单位m + */ + horizontalAccuracy: string; + /** + * 国家(type>0生效) + */ + country?: string; + /** + * 国家编号 (type>0生效) + */ + countryCode?: string; + /** + * 省份(type>0生效) + */ + province?: string; + /** + * 城市(type>0生效) + */ + city?: string; + /** + * 城市级别的地区代码(type>0生效) + */ + cityAdcode?: string; + /** + * 区县(type>0生效) + */ + district?: string; + /** + * 区县级别的地区代码(type>0生效) + */ + districtAdcode?: string; + /** + * 需要街道级别逆地理的才会有的字段,街道门牌信息,结构是:{ street, number } (type > 1生效) + */ + streetNumber?: { + street: string; + number: string; + }; + /** + * 需要POI级别逆地理的才会有的字段, 定位点附近的 POI 信息,结构是:{ name, address } (type > 2生效) + */ + pois?: Array<{ + name: string; + address: string; + }>; + } + interface GetLocationOptions extends BaseOptions { + /** + * 支付宝客户端经纬度定位缓存过期时间,单位秒。默认 30s。使用缓存会加快定位速度,缓存过期会重新定位 + */ + cacheTimeout: number; + /** + * 0:默认,获取经纬度 + * 1:获取经纬度和详细到区县级别的逆地理编码数据 + * 2:获取经纬度和详细到街道级别的逆地理编码数据,不推荐使用 + * 3:获取经纬度和详细到POI级别的逆地理编码数据,不推荐使用 + */ + type: 0 | 1 | 2 | 3; + /** 接口调用成功的回调函数,返回内容详见返回参数说明。 */ + success(res: LocationData): void; + } + /** + * 获取用户当前的地理位置信息 + */ + function getLocation(options: Partial): void; + + interface OpenLocationOptions extends BaseOptions { + /** 经度 */ + longitude: number | string; + /** 纬度 */ + latitude: number | string; + /** 位置名称 */ + name: string; + /** 地址的详细说明 */ + address: string; + /** 缩放比例,范围 3~19,默认为 15 */ + scale?: number; + } + /** + * 使用微信内置地图查看位置 + */ + function openLocation(options: OpenLocationOptions): void; + + interface ChooseLocationData { + /** + * 位置名称 + */ + name: string; + /** + * 详细地址 + */ + address: string; + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude: number; + /** + * 经度,浮点数,范围为-180~180,负数表示西经 + */ + longitude: number; + } + interface ChooseLocationOptions extends BaseOptions { + success(res: ChooseLocationData): void; + } + /** + * 使用支付宝内置地图选择地理位置。 + */ + function chooseLocation(options: ChooseLocationOptions): void; + //#endregion +} + +// 网络 +declare namespace my { + //#region 网络 https://docs.alipay.com/mini/api/network + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 设置请求的 HTTP 头,默认 {'Content-Type': 'application/x-www-form-urlencoded'} */ + header?: RequestHeader; + /** 默认GET,目前支持GET,POST */ + method?: "GET" | "POST"; + /** 请求的参数 */ + data?: any; + /** + * 超时时间,单位ms,默认30000 + */ + timeout?: number; + /** 期望返回的数据格式,默认json,支持json,text,base64 */ + dataType?: 'json' | 'text' | 'base64'; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + } + function httpRequest(options: RequestOptions): void; + + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器地址 */ + url: string; + /** 要上传文件资源的本地定位符 */ + filePath: string; + /** 文件名,即对应的 key, 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + fileName: string; + /** + * 文件类型 + */ + fileType: 'image' | 'video' | 'audio'; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form 数据 */ + formData?: any; + success?(res: { + /** 服务器返回的数据 */ + data: string; + /** HTTP 状态码 */ + statusCode: string; + header: any; + }): void; + } + /** + * 上传本地资源到开发者服务器。 + */ + function uploadFile(options: UploadFileOptions): void; + + interface DownloadFileOptions extends BaseOptions { + /** 下载文件地址 */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。 + */ + function downloadFile(options: DownloadFileOptions): void; + + interface ConnectSocketOptions extends BaseOptions { + /** 目标服务器url */ + url: string; + /** 请求的参数 */ + data?: any; + /** 设置请求的头部 */ + header?: RequestHeader; + method?: 'GET' | 'POST'; // todo missing in api + } + /** + * 创建一个 WebSocket 的连接; + * 一个支付宝小程序同时只能保留一个 WebSocket 连接,如果当前已存在 WebSocket 连接,会自动关闭该连接,并重新创建一个新的 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + + /** + * 监听WebSocket连接打开事件。 + */ + function onSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket关闭。 + */ + function onSocketClose(callback: () => void): void; + + /** + * 取消监听WebSocket连接打开事件。 + */ + function offSocketOpen(callback: () => void): void; + + /** + * 监听WebSocket错误。 + */ + function onSocketError(callback: (error: any) => void): void; + + /** + * 取消监听WebSocket错误。 + */ + function offSocketError(callback: (error: any) => void): void; + + interface SendSocketMessageOptions extends BaseOptions { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + } + /** + * 通过 WebSocket 连接发送数据,需要先使用 my.connectSocket 发起建连,并在 my.onSocketOpen 回调之后再发送数据。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: { + /** + * 需要发送的内容:普通的文本内容 String 或者经 base64 编码后的 String + */ + data: string | ArrayBuffer; + /** + * 如果需要发送二进制数据,需要将入参数据经 base64 编码成 String 后赋值 data,同时将此字段设置为true,否则如果是普通的文本内容 String,不需要设置此字段 + */ + isBuffer?: boolean; + }) => void): void; + function offSocketMessage(callback: (error: any) => void): void; + + interface CloseSocketOptions extends BaseOptions { + success?(res: any): void; + } + /** + * 监听WebSocket关闭。 + */ + function closeSocket(options?: CloseSocketOptions): void; + + /** + * 取消监听WebSocket关闭。 + */ + function offSocketClose(callback: (error: any) => void): void; + //#endregion +} + +// 设备 +declare namespace my { + //#region canIUse https://docs.alipay.com/mini/api/can-i-use + /** + * 判断当前小程序的 API、入参或返回值、组件、属性等在当前版本是否支持。 + * 参数使用 ${API}.${type}.${param}.${option} 或者 ${component}.${attribute}.${option} 方式来调用 + * - API 表示 api 名字 + * - type 取值 object/return/callback 表示 api 的判断类型 + * - param 表示参数的某一个属性名 + * - option 表示参数属性的具体属性值 + * - component 表示组件名称 + * - attribute 表示组件属性名 + * - option 表示组件属性值 + */ + function canIUse(api: string): boolean; + //#endregion + + //#region 获取基础库版本号 https://docs.alipay.com/mini/api/sdk-version + const SDKVersion: string; + //#endregion + //#region 系统信息 https://docs.alipay.com/mini/api/system-info + interface SystemInfo { + /** + * 手机型号 + */ + model: string; + /** + * 设备像素比 + */ + pixelRatio: number; + /** + * 窗口宽度 + */ + windowWidth: number; + /** + * 窗口高度 + */ + windowHeight: number; + /** + * 支付宝设置的语言 + */ + language: string; + /** + * 支付宝版本号 + */ + version: string; + /** + * 设备磁盘容量 + */ + storage: string; + /** + * 当前电量百分比 + */ + currentBattery: string; + /** + * 系统版本 + */ + system: string; + /** + * 系统名:Android,iOS + */ + platform: 'Android' | 'iOS' | string; + /** + * 屏幕宽度 + */ + screenWidth: number; + /** + * 屏幕高度 + */ + screenHeight: number; + /** + * 手机品牌 + */ + brand: string; + /** + * 用户设置字体大小 + */ + fontSizeSetting: number; + /** + * 当前运行的客户端,当前是支付宝则有效值是"alipay" + */ + app: 'alipay' | string; + } + interface GetSystemInfoOptions extends BaseOptions { + success?(res: SystemInfo): void; + } + function getSystemInfo(options: GetSystemInfoOptions): void; + function getSystemInfoSync(): SystemInfo; + //#endregion + + //#region 网络状态 https://docs.alipay.com/mini/api/network-status + interface GetNetworkTypeOptions extends BaseOptions { + success?(res: { + /** 网络是否可用 */ + networkAvailable: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }): void; + } + type NetworkType = 'UNKNOWN' | 'NOTREACHABLE' | 'WIFI' | '3G' | '2G' | '4G' | 'WWAN'; + function getNetworkType(options: GetNetworkTypeOptions): void; + + /** + * 开始网络状态变化的监听 + */ + function onNetworkStatusChange(callback: (res: { + /** 网络是否可用 */ + isConnected: boolean; + /** 网络类型值 UNKNOWN / NOTREACHABLE / WIFI / 3G / 2G / 4G / WWAN */ + networkType: NetworkType; + }) => void): void; + + /** + * 取消网络状态变化的监听 + */ + function offNetworkStatusChange(): void; + //#endregion + + //#region 剪贴板 https://docs.alipay.com/mini/api/clipboard + interface GetClipboardOptions extends BaseOptions { + success?(res: { + text: string; + }): void; + } + function getClipboard(options: GetClipboardOptions): void; + + interface SetClipboardOptions extends BaseOptions { + /** 剪贴板数据 */ + text: string; + } + function setClipboard(options: SetClipboardOptions): void; + //#endregion + + //#region 摇一摇 https://docs.alipay.com/mini/api/shake + function watchShake(options: BaseOptions): void; + //#endregion + + //#region 震动 https://docs.alipay.com/mini/api/vibrate + /** + * 调用震动功能。 + */ + function vibrate(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateLong(options?: BaseOptions): void; + + /** + * 调用震动功能。 + */ + function vibrateShort(options?: BaseOptions): void; + //#endregion + + //#region 拨打电话 https://docs.alipay.com/mini/api/macke-call + interface MakePhoneCallOptions extends BaseOptions { + /** + * 需要拨打的电话号码 + */ + number: string; + } + /** + * 拨打电话 + */ + function makePhoneCall(options: MakePhoneCallOptions): void; + //#endregion + + //#region 获取服务器时间 https://docs.alipay.com/mini/api/get-server-time + interface GetServerTimeOptions extends BaseOptions { + success?(res: { + /** 服务器时间的毫秒数 */ + time: number; + }): void; + } + function getServerTime(options: GetServerTimeOptions): void; + //#endregion + + //#region 用户截屏事件 https://docs.alipay.com/mini/api/user-capture-screen + /** + * 监听用户主动截屏事件,用户使用系统截屏按键截屏时触发此事件 + */ + function onUserCaptureScreen(callback?: (res: any) => void): void; + + /** + * 取消监听截屏事件。一般需要与 my.onUserCaptureScreen 成对出现。 + */ + function offUserCaptureScreen(): void; + //#endregion + + //#region 屏幕亮度 https://docs.alipay.com/mini/api/screen-brightness + interface SetKeepScreenOnOptions extends BaseOptions { + /** 是否保持屏幕常亮 */ + keepScreenOn: boolean; + success?(res: { errMsg: string }): void; + } + /** + * 设置是否保持常亮状态。 + * 仅在当前小程序生效,离开小程序后设置失效。 + */ + function setKeepScreenOn(options?: SetKeepScreenOnOptions): void; + + interface GetScreenBrightnessOptions extends BaseOptions { + /** 屏幕亮度值,范围 0~1,0 最暗,1 最亮 */ + success(value: number): void; + } + /** + * 获取屏幕亮度 + */ + function getScreenBrightness(options?: GetScreenBrightnessOptions): void; + + interface SetScreenBrightnessOptions extends BaseOptions { + /** 需要设置的屏幕亮度,取值范围0-1 */ + brightness: number; + } + /** + * 设置屏幕亮度 + */ + function setScreenBrightness(options: SetScreenBrightnessOptions): void; + //#endregion + + //#region 权限引导 https://docs.alipay.com/mini/api/show-auth-guide + interface showAuthGuideOptions extends BaseOptions { + /** + * 引导的权限标识,用于标识该权限类型(如 LBS) + * 支持的 authType 如下: + * + * 权限名称 权限码 支持平台 + * 后台保活权限 BACKGROUNDER Android + * 桌面快捷权限 SHORTCUT Android + * 麦克风权限 MICROPHONE iOS + * 通讯录权限 ADDRESSBOOK iOS + * 相机权限 CAMERA iOS + * 照片权限 PHOTO iOS + * push通知栏权限 NOTIFICATION iOS + * 自启动权限 SELFSTARTING Android + * lbs总开关 LBSSERVICE iOS + * lbs开关(app) LBS iOS + */ + authType: 'BACKGROUNDER' | 'SHORTCUT' | 'MICROPHONE' | 'ADDRESSBOOK' | 'CAMERA' | 'PHOTO' | 'NOTIFICATION' | 'SELFSTARTING' | 'LBSSERVICE' | 'LBS'; + } + function showAuthGuide(options: showAuthGuideOptions): void; + //#endregion +} + +// 扫码 +declare namespace my { + //#region 扫码 https://docs.alipay.com/mini/api/scan + type scanType = "qr" | "bar"; + interface ScanCodeData { + /** + * 扫描二维码时返回二维码数据 + */ + code: string; + /** + * 所扫码的类型 + */ + qrCode: string; + /** + * 扫描条形码时返回条形码数据 + */ + barCode: string; + } + interface ScanOptions extends BaseOptions { + /** + * 扫码样式(默认 qr): + * 1. qr,扫码框样式为二维码扫码框 + * 1. bar,扫码样式为条形码扫码框 + */ + type?: scanType; + /** + * 是否隐藏相册(不允许从相册选择图片),只能从相机扫码 + */ + hideAlbum?: boolean; + success?(res: ScanCodeData): void; + } + /** + * 调起客户端扫码界面,扫码成功后返回对应的结果 + */ + function scan(options: ScanOptions): void; + //#endregion +} + +// 蓝牙 +declare namespace my { + //#region 快速接入 https://docs.alipay.com/mini/api/bluetooth-intro + //#endregion + + //#region API https://docs.alipay.com/mini/api/bluetooth-api + interface OpenBluetoothAdapterOptions extends BaseOptions { + /** 不传的话默认是true,表示是否在离开当前页面时自动断开蓝牙(仅对android有效) */ + autoClose: boolean; + success(res: { + /** + * 是否支持 BLE + */ + isSupportBLE: boolean; + }): void; + } + /** + * 初始化小程序蓝牙模块,生效周期为调用 my.openBluetoothAdapter 至调用 my.closeBluetoothAdapter 或小程序被销毁为止。 在小程序蓝牙适配器模块生效期间,开发者可以正常调用下面的小程序API,并会收到蓝牙模块相关的 on 事件回调。 + */ + function openBluetoothAdapter(options: Partial): void; + + interface CloseBluetoothAdapterOptions extends BaseOptions { + success(res: any): void; + } + /** + * 关闭本机蓝牙模块 + */ + function closeBluetoothAdapter(options: CloseBluetoothAdapterOptions): void; + + interface BluetoothAdapterStateData extends ErrMsgResponse { + /** + * 是否正在搜索设备 + */ + discovering: boolean; + /** + * 蓝牙模块是否可用(需支持 BLE 并且蓝牙是打开状态) + */ + available: boolean; + } + interface GetBluetoothAdapterStateOptions extends BaseOptions { + success(res: BluetoothAdapterStateData): void; + } + /** + * 获取本机蓝牙适配器状态 + */ + function getBluetoothAdapterState(options: GetBluetoothAdapterStateOptions): void; + + interface StartBluetoothDevicesDiscoveryOptions extends BaseOptions { + /** + * 蓝牙设备主 service 的 uuid 列表 + * 某些蓝牙设备会广播自己的主 service 的 uuid。如果这里传入该数组,那么根据该 uuid 列表,只搜索有这个主服务的设备。 + */ + services?: string[]; + /** + * 否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 + */ + allowDuplicatesKey?: boolean; + /** + * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 + */ + interval?: number; + } + /** + * 开始搜寻附近的蓝牙外围设备。搜索结果将在 my.onBluetoothDeviceFound 事件中返回。 + */ + function startBluetoothDevicesDiscovery(options: StartBluetoothDevicesDiscoveryOptions): void; + + interface StopBluetoothDevicesDiscoveryOptions extends BaseOptions { + success(res: ErrMsgResponse): void; + } + /** + * 停止搜寻附近的蓝牙外围设备。请在确保找到需要连接的设备后调用该方法停止搜索。 + */ + function stopBluetoothDevicesDiscovery(options: StopBluetoothDevicesDiscoveryOptions): void; + + /** + * 蓝牙设备信息 + */ + interface BluetoothDevice { + /** + * 蓝牙设备名称,某些设备可能没有 + */ + name: string; + /** + * (兼容旧版本) 值与 name 一致 + */ + deviceName: string; + /** + * 广播设备名称 + */ + localName: string; + /** + * 设备的 id + */ + deviceId: string; + /** + * 设备信号强度 + */ + RSSI: number; + /** + * 设备的广播内容 + */ + advertisData: ArrayBuffer; + /** + * 设备的manufacturerData + */ + manufacturerData: ArrayBuffer; + } + interface GetBluetoothDevicesOptions extends BaseOptions { + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取所有已发现的蓝牙设备,包括已经和本机处于连接状态的设备。 + */ + function getBluetoothDevices(options: GetBluetoothDevicesOptions): void; + + interface GetConnectedBluetoothDevicesOptions extends BaseOptions { + services?: string[]; + success( + res: { + devices: BluetoothDevice[]; + } & ErrMsgResponse + ): void; + } + /** + * 获取处于已连接状态的设备。 + */ + function getConnectedBluetoothDevices(options: GetConnectedBluetoothDevicesOptions): void; + + interface BLEDeviceOptions extends BaseOptions { + /** + * 蓝牙设备id + */ + deviceId: string; + } + /** + * 连接低功耗蓝牙设备。 + */ + function connectBLEDevice(options: BLEDeviceOptions): void; + + /** + * 断开与低功耗蓝牙设备的连接。 + */ + function disconnectBLEDevice(options: BLEDeviceOptions): void; + + interface WriteBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应的值,16进制字符串,限制在20字节内 + */ + value: string; + } + /** + * 向低功耗蓝牙设备特征值中写入数据。 + */ + function writeBLECharacteristicValue( + options: WriteBLECharacteristicValueOptions + ): void; + + interface ReadBLECharacteristicValueOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + success( + res: { + characteristic: { + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的二进制值 + */ + value: ArrayBuffer; + }; + } & ErrMsgResponse + ): void; + } + + /** + * 读取低功耗蓝牙设备特征值中的数据。调用后在 my.onBLECharacteristicValueChange() 事件中接收数据返回。 + */ + function readBLECharacteristicValue(options: ReadBLECharacteristicValueOptions): void; + + interface NotifyBLECharacteristicValueChangeOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * 是否启用notify或indicate + */ + state?: boolean; + } + function notifyBLECharacteristicValueChange(optons: NotifyBLECharacteristicValueChangeOptions): void; + + interface NotifyBLECharacteristicValueChangedOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * notify 的 descriptor 的 uuid (只有android 会用到,非必填,默认值00002902-0000-10008000-00805f9b34fb) + */ + descriptorId?: string; + /** + * true: 启用 notify; false: 停用 notify + */ + state: boolean; + success(res: ErrMsgResponse): void; + } + /** + * 启用低功耗蓝牙设备特征值变化时的 notify 功能。注意:设备的特征值必须支持 notify/indicate 才可以成功调用,具体参照 characteristic 的 properties 属性 另外,必须先启用 notify 才能监听到设备 characteristicValueChange 事件。 + */ + function notifyBLECharacteristicValueChanged(options: NotifyBLECharacteristicValueChangedOptions): void; + + interface GetBLEDeviceServicesOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + services: Array<{ + /** + * 蓝牙设备服务的 uuid + */ + serviceId: string; + /** + * 该服务是否为主服务 + */ + isPrimary: boolean; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 service(服务) + */ + function getBLEDeviceServices(options: GetBLEDeviceServicesOptions): void; + + interface GetBLEDeviceCharacteristicsOptions extends BaseOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙服务 uuid + */ + serviceId: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success(res: { + characteristics: Array<{ + /** + * 蓝牙设备特征值的 uuid + */ + characteristicId: string; + /** + * 蓝牙设备特征值对应服务的 uuid + */ + serviceId: string; + /** + * 蓝牙设备特征值对应的16进制值 + */ + value: ArrayBuffer; + /** + * 该特征值支持的操作类型 + */ + properties: Array<{ + /** + * 该特征值是否支持 read 操作 + */ + read: boolean; + /** + * 该特征值是否支持 write 操作 + */ + write: boolean; + /** + * 该特征值是否支持 notify 操作 + */ + notify: boolean; + /** + * 该特征值是否支持 indicate 操作 + */ + indicate: boolean; + }>; + }>; + } & ErrMsgResponse): void; + } + /** + * 获取蓝牙设备所有 characteristic(特征值) + */ + function getBLEDeviceCharacteristics(options: GetBLEDeviceCharacteristicsOptions): void; + + interface OnBluetoothDeviceFoundOptions extends BaseOptions { + success?(res: { + devices: BluetoothDevice[]; + }): void; + } + /** + * 搜索到新的蓝牙设备时触发此事件。 + */ + function onBluetoothDeviceFound(options: OnBluetoothDeviceFoundOptions): void; + + /** + * 移除寻找到新的蓝牙设备事件的监听。 + */ + function offBluetoothDeviceFound(callback?: any): void; + + interface OnBLECharacteristicValueChangeOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 蓝牙特征值对应 service 的 uuid + */ + serviceId: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId: string; + /** + * 特征值最新的16进制值 + */ + value: ArrayBuffer; + }): void; + } + /** + * 监听低功耗蓝牙设备的特征值变化的事件。 + */ + function onBLECharacteristicValueChange(options: OnBLECharacteristicValueChangeOptions): void; + + interface OnBLEConnectionStateChangedOptions extends BaseOptions { + success?(res: { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId: string; + /** + * 连接目前的状态 + */ + connected: boolean; + }): void; + } + /** + * 移除低功耗蓝牙设备的特征值变化事件的监听。 + */ + function offBLECharacteristicValueChange(callback?: any): void; + + /** + * 监听低功耗蓝牙连接的错误事件,包括设备丢失,连接异常断开等。 + */ + function onBLEConnectionStateChanged(options: OnBLEConnectionStateChangedOptions): void; + + /** + * 移除低功耗蓝牙连接状态变化事件的监听。 + */ + function offBLEConnectionStateChanged(): void; + + interface BluetoothAdapterState { + /** + * 蓝牙适配器是否可用 + */ + available: boolean; + /** + * 蓝牙适配器是否处于搜索状态 + */ + discovering: boolean; + } + /** + * 监听本机蓝牙状态变化的事件。 + */ + function onBluetoothAdapterStateChange(callback: (res: BluetoothAdapterState) => void): void; + + /** + * 移除本机蓝牙状态变化的事件的监听。 + */ + function offBluetoothAdapterStateChange(): void; + //#endregion +} + +// iBeacon +declare namespace my { + //#region iBeacon https://docs.alipay.com/mini/api/yqleyc + interface StartBeaconDiscoveryOptions extends BaseOptions { + /** + * iBeacon设备广播的 uuids + */ + uuids: string[]; + success?(res: ErrMsgResponse): void; + } + /** + * 开始搜索附近的iBeacon设备 + */ + function startBeaconDiscovery(options: StartBeaconDiscoveryOptions): void; + + interface StopBeaconDiscoveryOptions extends BaseOptions { + success?(res: ErrMsgResponse): void; + } + /** + * 停止搜索附近的iBeacon设备 + */ + function stopBeaconDiscovery(options: StopBeaconDiscoveryOptions): void; + + interface Beacon { + /** iBeacon 设备广播的 uuid */ + uuid: string; + /** iBeacon 设备的主 id */ + major: string; + /** iBeacon 设备的次 id */ + minor: string; + /** 表示设备距离的枚举值(0-3分别代表:未知、极近、近、远) */ + proximity: 0 | 1 | 2 | 3; + /** iBeacon 设备的距离 */ + accuracy: number; + /** iBeacon 信号强度 */ + rssi: number; + } + interface GetBeaconsSuccess { + beacons: Beacon[]; + /** + * errorCode=0 ,接口调用成功 + */ + errCode: string; + /** + * ok + */ + errMsg: string; + } + interface GetBeaconsOptions extends BaseOptions { + success?(options: GetBeaconsSuccess): void; + } + /** + * 获取所有已搜索到的iBeacon设备 + */ + function getBeacons(options: GetBeaconsOptions): void; + + interface BeaconUpdateOptions extends BaseOptions { + success?(res: { + beacons: Beacon[]; + }): void; + } + /** + * 监听 iBeacon 设备的更新事件 + */ + function onBeaconUpdate(options: BeaconUpdateOptions): void; + + interface BeaconServiceChangeOptions extends BaseOptions { + success?(res: { + /** + * 服务目前是否可用 + */ + available: boolean; + /** + * 目前是否处于搜索状态 + */ + discovering: boolean; + }): void; + } + /** + * 监听 iBeacon 服务的状态变化 + */ + function onBeaconServiceChange(options: BeaconServiceChangeOptions): void; + //#endregion +} + +// 数据安全 +declare namespace my { + //#region 数据安全 https://docs.alipay.com/mini/api/data-safe + interface RsaOptions extends BaseOptions { + /** + * 使用rsa加密还是rsa解密,encrypt加密,decrypt解密 + */ + action: string; + /** + * 要处理的文本,加密为原始文本,解密为Base64编码格式文本 + */ + text: string; + /** + * rsa秘钥,加密使用公钥,解密使用私钥 + */ + key: string; + success?(res: { + /** + * 经过处理过后得到的文本,加密为Base64编码文本,解密为原始文本 + */ + text: string; + }): void; + } + /** + * 非对称加密。 + */ + function rsa(options: RsaOptions): void; + //#endregion +} + +// 分享 +declare namespace my { + //#region 分享 https://docs.alipay.com/mini/api/share_app + //#endregion +} + +// 自定义分析 +declare namespace my { + //#region 自定义分析 https://docs.alipay.com/mini/api/report + /** + * 自定义分析数据的上报接口。使用前需要在小程序管理后台的事件管理中新建事件,并配置好事件名和字段。 + * + * @param eventName 自定义事件名,需申请 + * @param data 上报的数据 + */ + function reportAnalytics(eventName: string, data: any): void; + + /** + * 隐藏分享按钮。 + */ + function hideShareMenu(options?: BaseOptions): void; + //#endregion +} + +declare namespace my { + interface LaunchOptions { + /** + * 打开小程序的路径 + */ + path: string; + /** + * 打开小程序的query + */ + query: object; + /** + * 打开小程序的[场景值] + */ + scene: number; + /** + * shareTicket,详见 获取更多[转发信息] + */ + shareTicket: string; + /** + * 当场景为由从另一个小程序或公众号或App打开时,返回此字段 + */ + referrerInfo: object; + /** + * 来源小程序或公众号或App的 appId,详见下方说明 + */ + "referrerInfo.appId": string; + /** + * 来源小程序传过来的数据,scene=1037或1038时支持 + */ + "referrerInfo.extraData": object; + // #endregion + } + interface AppOptions { + /** + * 监听小程序初始化。 + * 当小程序初始化完成时,会触发 onLaunch(全局只触发一次) + * 生命周期函数 + */ + onLaunch?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序显示。 + * 当小程序启动,或从后台进入前台显示,会触发 onShow + * 生命周期函数 + */ + onShow?: (this: App, option: LaunchOptions) => void; + /** + * 监听小程序隐藏。 + * 当小程序从前台进入后台,会触发 onHide + * 生命周期函数 + */ + onHide?: (this: App) => void; + /** + * 错误监听函数 + * 当小程序发生脚本错误或者 api 调用失败时 + * 会触发 onError 并带上错误信息 + */ + onError?: (this: App, msg: string) => void; + /** + * 小程序退出时触发 + */ + onUnlaunch?: (this: App) => void; + /** + * 全局Data + */ + globalData?: object; + [key: string]: any; + } + interface CreateIntersectionObserverOption { + thresholds?: [number, number]; + initialRatio?: number; + selectAll?: boolean; + } + + interface Margins { + left?: number; + right?: number; + top?: number; + bottom?: number; + } + interface ObserveResponse { + id: string; + dataset: any; + time: number; + intersectionRatio: number; // 相交区域占目标节点的布局区域的比例 + boundingClientRect: RectArea; + intersectionRect: RectArea; + relativeRect: RectArea; + } + interface IntersectionObserver { + relativeTo(selector?: string, margins?: Margins): IntersectionObserver; + relativeToViewport(margins?: Margins): IntersectionObserver; + observe( + selector?: string, + callback?: (response: ObserveResponse) => void + ): IntersectionObserver; + disconnect(): void; + } + interface ComponentRelation { + /** 目标组件的相对关系,可选的值为 parent 、 child 、 ancestor 、 descendant */ + type: "parent" | "child" | "ancestor" | "descendant"; + /** 如果这一项被设置,则它表示关联的目标节点所应具有的behavior,所有拥有这一behavior的组件节点都会被关联 */ + target?: string; + /** 关系生命周期函数,当关系被建立在页面节点树中时触发,触发时机在组件attached生命周期之后 */ + linked?: (target: Component) => void; + /** 关系生命周期函数,当关系在页面节点树中发生改变时触发,触发时机在组件moved生命周期之后 */ + linkChanged?: (target: Component) => void; + /** 关系生命周期函数,当关系脱离页面节点树时触发,触发时机在组件detached生命周期之后 */ + unlinked?: (target: Component) => void; + } + interface Component { + /** + * 组件的文件路径 + */ + is: string; + /** + * 节点id + */ + id: string; + /** + * 节点dataset + */ + dataset: string; + /** + * 组件数据,包括内部数据和属性值 + */ + data: any; + + /** + * 组件数据,包括内部数据和属性值(与 data 一致) + */ + properties: any; + /** + * 将数据从逻辑层发送到视图层,同时改变对应的 this.data 的值 + * 1. 直接修改 this.data 而不调用 this.setData 是无法改变页面的状态的,还会造成数据不一致。 + * 2. 单次设置的数据不能超过1024kB,请尽量避免一次设置过多的数据。 + * 3. 请不要把 data 中任何一项的 value 设为 undefined ,否则这一项将不被设置并可能遗留一些潜在问题 + * @param data object 以 key,value 的形式表示将 this.data 中的 key 对应的值改变成 value + * @param [callback] callback 是一个回调函数,在这次setData对界面渲染完毕后调用 + */ + setData( + data: any, + callback?: () => void + ): void; + hasBehavior(behavior: any): boolean; + triggerEvent( + name: string, + details?: any, + options?: Partial<{ + bubbles: boolean; + composed: boolean; + capturePhase: boolean; + }> + ): void; + createSelectorQuery(): SelectorQuery; + createIntersectionObserver( + options?: CreateIntersectionObserverOption + ): IntersectionObserver; + /** + * 使用选择器选择组件实例节点 + * 返回匹配到的第一个组件实例对象 + */ + selectComponent(selector: string): Component; + /** + * selector 使用选择器选择组件实例节点,返回匹配到的全部组件实例对象组成的数组 + */ + selectAllComponents(selector: string): Component[]; + getRelationNodes(relationKey: string): ComponentRelation[]; + } + interface Page extends Component { + /** + * data + */ + data: any; + /** + * 强制更新 + */ + forceUpdate(): void; + /** + * 字段可以获取到当前页面的路径。 + */ + route(): void; + /** + * 更新 + */ + update(): void; + /** + * 将页面滚动到目标位置。 + * + * scrollTop 滚动到页面的目标位置(单位px) + * [duration] 滚动动画的时长,默认300ms,单位 ms + */ + pageScrollTo(option?: PageScrollToOptions): void; + [key: string]: any; + } + interface App { + data: any; + /** + * 获取当前页面 + */ + getCurrentPage(): Page; + [key: string]: any; + } + interface EventTarget { + id: string; + tagName: string; + dataset: { [name: string]: string }; + } + type TouchEventType = + | "tap" + | "touchstart" + | "touchmove" + | "touchcancel" + | "touchend" + | "touchforcechange"; + + type TransitionEventType = + | "transitionend" + | "animationstart" + | "animationiteration" + | "animationend"; + + type EventType = + | "input" + | "form" + | "submit" + | "scroll" + | TouchEventType + | TransitionEventType + | "tap" + | "longpress"; + interface BaseEvent { + type: T; + timeStamp: number; + currentTarget: EventTarget; + target: EventTarget; + detail: Detail; + } + interface Options { + query: any; // 当前小程序的 query + path: string; // 当前小程序的页面地址 + } + interface PageOptions { + data: any; + onLaunch(this: Page, options: Options): void; + onShow(this: Page, options: Options): void; + onHide(this: Page): void; + onError(this: Page): void; + [key: string]: any; + } + function postMessage(param: any): void; + type onMessageFun = (p: any) => void; + let onMessage: onMessageFun; +} + +declare function App(app: Partial): void; + +declare function getApp(): my.App; + +declare function Behavior(options?: any): my.Component; + +declare function Component(options?: any): my.Component; + +declare function Page(options: Partial): void; + +declare function getCurrentPages(): my.Page[]; diff --git a/types/ali-app/tsconfig.json b/types/ali-app/tsconfig.json new file mode 100644 index 0000000000..a2402fac2c --- /dev/null +++ b/types/ali-app/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "esnext", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "ali-app-tests.ts" + ], + "exclude": [ + ".prettierrc" + ] +} \ No newline at end of file diff --git a/types/ali-app/tslint.json b/types/ali-app/tslint.json new file mode 100644 index 0000000000..f491d1bed9 --- /dev/null +++ b/types/ali-app/tslint.json @@ -0,0 +1,7 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false, + "no-unnecessary-generics": false + } +} \ No newline at end of file diff --git a/types/ali-oss/Cluster.d.ts b/types/ali-oss/Cluster.d.ts deleted file mode 100644 index 60886fca36..0000000000 --- a/types/ali-oss/Cluster.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { - ACLType, - CopyAndPutMetaResult, - CopyObjectOptions, - DeleteMultiOptions, - DeleteMultiResult, - GetObjectOptions, - GetObjectResult, - GetStreamOptions, - GetStreamResult, - HeadObjectOptions, - HeadObjectResult, - ListObjectResult, - ListObjectsQuery, - NormalSuccessResponse, - PutObjectOptions, - PutObjectResult, - PutStreamOptions, - RequestOptions, - SignatureUrlOptions, - UserMeta -} from "./index"; - -export interface ClusterType { - host: string; - accessKeyId: string; - accessKeySecret: string; -} - -export interface ClusterOptions { - clusters: ClusterType[]; - schedule?: string; -} - -export class Cluster { - constructor(options: ClusterOptions) - - list(query: ListObjectsQuery | null, options: RequestOptions): Promise; - - put(name: string, file: any, options?: PutObjectOptions): Promise; - - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; - - head(name: string, options?: HeadObjectOptions): Promise; - - get(name: string, file?: any, options?: GetObjectOptions): Promise; - - getStream(name?: string, options?: GetStreamOptions): Promise; - - delete(name: string, options?: RequestOptions): Promise; - - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; - - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; - - deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; - - signatureUrl(name: string, options?: SignatureUrlOptions): string; - - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; - - restore(name: string, options?: RequestOptions): Promise; -} diff --git a/types/ali-oss/ImageClient.d.ts b/types/ali-oss/ImageClient.d.ts deleted file mode 100644 index 850213083c..0000000000 --- a/types/ali-oss/ImageClient.d.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { NormalSuccessResponse, RequestOptions } from "./index"; - -export interface ImageClientOptions { - imageHost: string; // your image service domain that binding to a OSS bucket - accessKeyId: string; // access key you create on aliyun console website - accessKeySecret: string; // access secret you create - bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou - internal?: boolean; // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. - timeout?: string | number; // instance level timeout for all operations, default is 60s -} - -export interface ImageGetOptions { - timeout?: number; - headers?: object; -} - -export interface StyleData { - Name: string; // style name - Content: string; // style content - CreateTime: string; // style create time - LastModifyTime: string; // style last modify time -} -export class ImageClient { - constructor(options: ImageClientOptions) - - /** - * Get an image from the image channel. - */ - get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>; - - /** - * Get an image read stream. - */ - getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>; - - /** - * Get a image exif info by image object name from the image channel. - */ - getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * Get a image info and exif info by image object name from the image channel. - */ - getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * todo - */ - putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; - - /** - * Get a style by name from the image channel. - */ - getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>; - - /** - * Get all styles from the image channel. - */ - listStyle(options?: RequestOptions): Promise; - - /** - * todo - */ - deleteStyle(styleName: string, options?: RequestOptions): Promise; - - /** - * Create a signature url for directly download. - */ - signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string; -} diff --git a/types/ali-oss/ali-oss-tests.ts b/types/ali-oss/ali-oss-tests.ts index 96f817cca8..dc751b8d44 100644 --- a/types/ali-oss/ali-oss-tests.ts +++ b/types/ali-oss/ali-oss-tests.ts @@ -1,34 +1,25 @@ -import OSS from "ali-oss"; +import * as OSS from 'ali-oss'; -const client = new OSS({ +const ossOptions: OSS.Options = { accessKeyId: 'your access key', accessKeySecret: 'your access secret', bucket: 'your bucket name', region: 'oss-cn-hangzhou' -}); +}; -const ImageClient = OSS.ImageClient({ - imageHost: 'host', - accessKeySecret: "secret", - accessKeyId: 'id', - bucket: "", - internal: false, - region: "", - timeout: 2000 -}); +const client = new OSS(ossOptions); -const cluster = OSS.Cluster({ - clusters: [ - { - accessKeyId: 'id', - accessKeySecret: 'secret', - host: "" - }, - { - accessKeyId: 'id', - accessKeySecret: 'secret', - host: "" - }, - ], - schedule: 'masterSlave', -}); +const clusterOptions: OSS.ClusterOptions = { + clusters: [], +}; + +const clusterClient = new OSS.Cluster(clusterOptions); + +const imageOptions: OSS.ImageClientOptions = { + imageHost: 'xxxx', + accessKeyId: 'xxxx', + accessKeySecret: 'xxxx', + bucket: 'xxxx' +}; + +const imageClient = new OSS.ImageClient(imageOptions); diff --git a/types/ali-oss/index.d.ts b/types/ali-oss/index.d.ts index c3fa0dd10b..13f7f56ff9 100644 --- a/types/ali-oss/index.d.ts +++ b/types/ali-oss/index.d.ts @@ -4,442 +4,555 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import * as ImageClientDefinition from './ImageClient'; -import * as ClusterDefinition from "./Cluster"; +export = OSS; -export * from './ImageClient'; -export * from './Cluster'; +// basic OSS +declare namespace OSS { + interface Options { + accessKeyId: string; // access secret you create + accessKeySecret: string; // access secret you create + stsToken?: string; // used by temporary authorization + bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + endpoint?: string; // oss region domain. It takes priority over region. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. + internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. + secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. + timeout?: string | number; // instance level timeout for all operations, default is 60s + } -export interface Options { - accessKeyId: string; // access secret you create - accessKeySecret: string; // access secret you create - stsToken?: string; // used by temporary authorization - bucket?: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. - endpoint?: string; // oss region domain. It takes priority over region. - region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou. - internal?: boolean; // access OSS with aliyun internal network or not, default is false. If your servers are running on aliyun too, you can set true to save lot of money. - secure?: boolean; // instruct OSS client to use HTTPS (secure: true) or HTTP (secure: false) protocol. - timeout?: string | number; // instance level timeout for all operations, default is 60s -} + interface Bucket { + name: string; + region: string; + creationDate: string; + StorageClass: StorageType; + } -export interface Bucket { - name: string; - region: string; - creationDate: string; - StorageClass: StorageType; -} + type StorageType = "Standard" | "IA" | "Archive"; -export type StorageType = "Standard" | "IA" | "Archive"; + type ACLType = "public-read-write" | "public-read" | "and private"; -export type ACLType = "public-read-write" | "public-read" | "and private"; + type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; -export type HTTPMethods = "GET" | "POST" | "DELETE" | "PUT"; + interface RequestOptions { + // the operation timeout + timeout?: number; + } -export interface RequestOptions { - // the operation timeout - timeout?: number; -} + type RuleStatusType = "Enabled" | "Disabled"; -export type RuleStatusType = "Enabled" | "Disabled"; + interface LifecycleRule { + id?: string; // rule id, if not set, OSS will auto create it with random string. + prefix: string; // store prefix + status: RuleStatusType; // rule status, allow values: Enabled or Disabled + days?: number | string; // expire after the days + date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. + } -export interface LifecycleRule { - id?: string; // rule id, if not set, OSS will auto create it with random string. - prefix: string; // store prefix - status: RuleStatusType; // rule status, allow values: Enabled or Disabled - days?: number | string; // expire after the days - date: string; // expire date, e.g.: 2022-10-11T00:00:00.000Z date and days only set one. -} + interface CORSRule { + allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header + allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header + allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header + exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header + maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header + } -export interface CORSRule { - allowedOrigin: string | string[]; // configure for Access-Control-Allow-Origin header - allowedMethod: string | string[]; // configure for Access-Control-Allow-Methods header - allowedHeader?: string | string[]; // configure for Access-Control-Allow-Headers header - exposeHeader?: string | string[]; // configure for Access-Control-Expose-Headers header - maxAgeSeconds?: string | string[]; // configure for Access-Control-Max-Age header -} + interface OwnerType { + id: string; + displayName: string; + } -export interface OwnerType { - id: string; - displayName: string; -} + interface ObjectMeta { + name: string; // object name on oss + lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + type: string; // object type, e.g.: Normal + size: number; // object size, e.g.: 344606 + storageClass: StorageType; + owner: OwnerType; + } -export interface ObjectMeta { - name: string; // object name on oss - lastModified: string; // object last modified GMT date, e.g.: 2015-02-19T08:39:44.000Z - etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" - type: string; // object type, e.g.: Normal - size: number; // object size, e.g.: 344606 - storageClass: StorageType; - owner: OwnerType; -} + interface NormalSuccessResponse { + // response status + status: number; + // response headers + headers: object; // todo the object in detail + // response size + size: number; + // request total use time (ms) + rt: number; + } -export interface NormalSuccessResponse { - // response status - status: number; - // response headers - headers: object; // todo the object in detail - // response size - size: number; - // request total use time (ms) - rt: number; -} + interface UserMeta { + uid: number; + pid: number; + } -export interface UserMeta { - uid: number; - pid: number; -} + interface ObjectCallback { + url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL. + host?: string; // The host header value for initiating callback requests. + body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). + contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. + customValue?: object; + headers?: object; // extra headers, detail see RFC 2616 + } -export interface ObjectCallback { - url: string; // After a file is uploaded successfully, the OSS sends a callback request to this URL. - host?: string; // The host header value for initiating callback requests. - body: string; // The value of the request body when a callback is initiated, for example, key=$(key)&etag=$(etag)&my_var=$(x:my_var). - contentType?: string; // The Content-Type of the callback requests initiatiated, It supports application/x-www-form-urlencoded and application/json, and the former is the default value. - customValue?: object; - headers?: object; // extra headers, detail see RFC 2616 -} + interface ModifyData { + lastModified: string; // object last modified GMT string + etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" + } -export interface ModifyData { - lastModified: string; // object last modified GMT string - etag: string; // object etag contains ", e.g.: "5B3C1A2E053D763E1B002CC607C5A0FE" -} + interface Checkpoint { + file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings + name: string; // object key + fileSize: number; + partSize: number; + uploadId: string; + doneParts: Array<{ number: number, etag: string }>; + } -export interface Checkpoint { - file: any; // The file object selected by the user, if the browser is restarted, it needs the user to manually trigger the settings - name: string; // object key - fileSize: number; - partSize: number; - uploadId: string; - doneParts: Array<{ number: number, etag: string }>; -} + interface ObjectPart { + PartNumber: number; + LastModified: any; // {Date} Time when a part is uploaded. + ETag: string; + size: number; + } -export interface ObjectPart { - PartNumber: number; - LastModified: any; // {Date} Time when a part is uploaded. - ETag: string; - size: number; -} + interface Upload { + name: string; + uploadId: string; + initiated: any; + } -export interface Upload { - name: string; - uploadId: string; - initiated: any; -} + interface Channel { + Name: string; + Description: string; + Status: string; + LastModified: string; + PublishUrls: string[]; + PlayUrls: string[]; + } -export interface Channel { - Name: string; - Description: string; - Status: string; - LastModified: string; - PublishUrls: string[]; - PlayUrls: string[]; -} - -export interface ChannelHistory { - StartTime: string; // - EndTime: string; - RemoteAddr: string; // the remote addr -} + interface ChannelHistory { + StartTime: string; // + EndTime: string; + RemoteAddr: string; // the remote addr + } // parameters type -export interface ListBucketsQueryType { - prefix?: string; // search buckets using prefix key - marker?: string; // search start from marker, including marker key - 'max-keys'?: string | number; // max buckets, default is 100, limit to 1000 + interface ListBucketsQueryType { + prefix?: string; // search buckets using prefix key + marker?: string; // search start from marker, including marker key + 'max-keys'?: string | number; // max buckets, default is 100, limit to 1000 + } + + interface PutBucketOptions { + timeout: number; + storageClass: StorageType; + } + + interface PutBucketWebsiteConfig { + index: string; // default page, e.g.: index.html + error?: string; // error page, e.g.: 'error.html' + } + + interface ListObjectsQuery { + prefix?: string; // search object using prefix key + marker?: string; // search start from marker, including marker key + delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir + 'max-keys': string | number; // max objects, default is 100, limit to 1000 + } + + interface ListObjectResult { + objects: ObjectMeta[]; + prefixes: string[]; + isTruncated: boolean; + nextMarker: string; + res: NormalSuccessResponse; + } + + interface PutObjectOptions { + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } + callback: ObjectCallback; + } + + interface PutObjectResult { + name: string; + data: object; + res: NormalSuccessResponse; + } + + interface PutStreamOptions { + contentLength?: number; // the stream length, chunked encoding will be used if absent + timeout: number; // the operation timeout + mime: string; // custom mime, will send with Content-Type entity header + meta: UserMeta; + callback: ObjectCallback; + } + + interface AppendObjectOptions { + position?: string; // specify the position which is the content length of the latest object + timeout?: number; // the operation timeout + mime?: string; // custom mime, will send with Content-Type entity header + meta?: UserMeta; + headers?: object; + } + + interface AppendObjectResult { + name: string; + url: string; // the url of oss + res: NormalSuccessResponse; + nextAppendPosition: string; // the next position + } + + interface HeadObjectOptions { + timeout?: number; + headers?: object; + } + + interface HeadObjectResult { + status: number; // response status, maybe 200 or 304 + meta: UserMeta; + res: NormalSuccessResponse; + } + + interface GetObjectOptions { + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; + } + + interface GetObjectResult { + content?: any; // file content buffer if file parameter is null or ignore + res: NormalSuccessResponse; + } + + interface GetStreamOptions { + timeout?: number; + process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} + headers?: object; + } + + interface GetStreamResult { + stream?: any; // readable stream instance if response status is not 200, stream will be null. + res: NormalSuccessResponse; + } + + interface CopyObjectOptions { + timeout?: number; + meta?: UserMeta; + headers?: object; + } + + interface CopyAndPutMetaResult { + data: ModifyData; + res: NormalSuccessResponse; + } + + interface DeleteMultiOptions { + quite?: boolean; // quite mode or verbose mode, default is false + timeout?: number; + } + + interface DeleteMultiResult { + deleted?: string[]; // deleted object names list + res: NormalSuccessResponse; + } + + interface ResponseHeaderType { + 'content-type'?: string; + 'content-disposition'?: string; + 'cache-control'?: string; + } + + interface SignatureUrlOptions { + expires?: number; // after expires seconds, the url will become invalid, default is 1800 + method?: HTTPMethods; // the HTTP method, default is 'GET' + 'Content-Type'?: string; // set the request content type + process?: string; + response?: ResponseHeaderType; // set the response headers for download + callback?: ObjectCallback; + } + + interface GetACLResult { + acl: ACLType; + res: NormalSuccessResponse; + } + + interface InitMultipartUploadOptions { + timeout?: number; + mime?: string; // Mime file type + meta?: UserMeta; + headers?: object; + } + + interface InitMultipartUploadResult { + res: { status: number, headers: object, size: number, rt: number }; + bucket: string; // bucket name + name: string; // object name store on OSS + uploadId: string; // upload id, use for uploadPart, completeMultipart + } + + interface UploadPartResult { + name: string; + etag: string; + res: NormalSuccessResponse; + } + + interface CompleteMultipartUploadOptions { + timeout?: number; + callback?: ObjectCallback; + headers?: object; + } + + interface CompleteMultipartUploadResult { + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; + } + + interface MultipartUploadOptions { + parallel?: number; // the number of parts to be uploaded in parallel + partSize?: number; // the suggested size for each part + progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part + checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. + meta?: UserMeta; + mime?: string; + callback?: ObjectCallback; + headers?: object; + timeout?: number; + copyheaders?: object; // {Object} only uploadPartCopy api used, detail + } + + interface MultipartUploadResult { + bucket: string; + name: string; + etag: string; + data: object; + res: NormalSuccessResponse; + } + + interface MultipartUploadCopyResult { + bucket: string; + name: string; + etag: string; + res: NormalSuccessResponse; + } + + interface MultipartUploadCopySourceData { + sourceKey: string; // the source object name + sourceBucketName: string; // sourceData. the source bucket name + startOffset: number; // data copy start byte offset, e.g: 0 + endOffset: number; // data copy end byte offset, e.g: 102400 + } + + interface ListPartsQuery { + 'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000. + 'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. + 'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url + } + + interface ListPartsResult { + uploadId: string; + bucket: string; + name: string; + PartNumberMarker: number; + nextPartNumberMarker: number; + maxParts: number; + isTruncated: boolean; + parts: ObjectPart[]; + res: NormalSuccessResponse; + } + + interface ListUploadsQuery { + prefix?: string; + 'max-uploads'?: number; + 'key-marker'?: string; + 'upload-id-marker'?: string; + } + + interface ListUploadsResult { + res: NormalSuccessResponse; + bucket: string; + nextKeyMarker: any; + nextUploadIdMarker: any; + isTruncated: boolean; + uploads: Upload[]; + } + + interface PutChannelConf { + Description?: string; + Status?: string; + Target?: { + Type: string, + FragDuration: number, + FragCount: number, + PlaylistName: string + }; + } + + interface PutChannelResult { + publishUrls: string[]; + playUrls: string[]; + res: NormalSuccessResponse; + } + + interface GetChannelResult { + Status: string; + ConnectedTime?: string; + RemoteAddr?: string; + Video?: object; + Audio?: object; + res: NormalSuccessResponse; + } + + interface ListChannelsQuery { + prefix: string; // the channel id prefix (returns channels with this prefix) + marker: string; // the channel id marker (returns channels after this id) + 'max-keys ': number; // max number of channels to return + } + + interface ListChannelsResult { + channels: Channel[]; + nextMarker: string | null; + isTruncated: boolean; + res: NormalSuccessResponse; + } + + interface ChannelHistoryResult { + records: ChannelHistory; + res: NormalSuccessResponse; + } + + interface GetRtmpUrlOptions { + expires?: number; // the expire time in seconds of the url + params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'} + timeout?: number; // the operation timeout + } } -export interface PutBucketOptions { - timeout: number; - storageClass: StorageType; +/// cluster +declare namespace OSS { + interface ClusterType { + host: string; + accessKeyId: string; + accessKeySecret: string; + } + + interface ClusterOptions { + clusters: ClusterType[]; + schedule?: string; + } + + class Cluster { + constructor(options: ClusterOptions) + + list(query: ListObjectsQuery | null, options: RequestOptions): Promise; + + put(name: string, file: any, options?: PutObjectOptions): Promise; + + putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; + + head(name: string, options?: HeadObjectOptions): Promise; + + get(name: string, file?: any, options?: GetObjectOptions): Promise; + + getStream(name?: string, options?: GetStreamOptions): Promise; + + delete(name: string, options?: RequestOptions): Promise; + + copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; + + putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; + + deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; + + signatureUrl(name: string, options?: SignatureUrlOptions): string; + + putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + + restore(name: string, options?: RequestOptions): Promise; + } } -export interface PutBucketWebsiteConfig { - index: string; // default page, e.g.: index.html - error?: string; // error page, e.g.: 'error.html' +// image +declare namespace OSS { + interface ImageClientOptions { + imageHost: string; // your image service domain that binding to a OSS bucket + accessKeyId: string; // access key you create on aliyun console website + accessKeySecret: string; // access secret you create + bucket: string; // the default bucket you want to access If you don't have any bucket, please use putBucket() create one first. + region?: string; // the bucket data region location, please see Data Regions, default is oss-cn-hangzhou + internal?: boolean; // access OSS with aliyun internal network or not, default is false If your servers are running on aliyun too, you can set true to save lot of money. + timeout?: string | number; // instance level timeout for all operations, default is 60s + } + + interface ImageGetOptions { + timeout?: number; + headers?: object; + } + + interface StyleData { + Name: string; // style name + Content: string; // style content + CreateTime: string; // style create time + LastModifyTime: string; // style last modify time + } + + class ImageClient { + constructor(options: ImageClientOptions) + + /** + * Get an image from the image channel. + */ + get(name: string, file?: any, options?: ImageGetOptions): Promise<{ content: any, res: NormalSuccessResponse }>; + + /** + * Get an image read stream. + */ + getStream(name: string, options?: ImageGetOptions): Promise<{ stream: any, res: NormalSuccessResponse }>; + + /** + * Get a image exif info by image object name from the image channel. + */ + getExif(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * Get a image info and exif info by image object name from the image channel. + */ + getInfo(name: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * todo + */ + putStyle(name: string, style: string, options?: RequestOptions): Promise<{ data: object, res: NormalSuccessResponse }>; + + /** + * Get a style by name from the image channel. + */ + getStyle(name: string, options?: RequestOptions): Promise<{ data: StyleData, res: NormalSuccessResponse}>; + + /** + * Get all styles from the image channel. + */ + listStyle(options?: RequestOptions): Promise; + + /** + * todo + */ + deleteStyle(styleName: string, options?: RequestOptions): Promise; + + /** + * Create a signature url for directly download. + */ + signatureUrl(name: string, options?: { expires?: string, timeout?: string }): string; + } } -export interface ListObjectsQuery { - prefix?: string; // search object using prefix key - marker?: string; // search start from marker, including marker key - delimiter?: string; // delimiter search scope e.g. / only search current dir, not including subdir - 'max-keys': string | number; // max objects, default is 100, limit to 1000 -} - -export interface ListObjectResult { - objects: ObjectMeta[]; - prefixes: string[]; - isTruncated: boolean; - nextMarker: string; - res: NormalSuccessResponse; -} - -export interface PutObjectOptions { - timeout?: number; // the operation timeout - mime?: string; // custom mime, will send with Content-Type entity header - meta?: UserMeta; // user meta, will send with x-oss-meta- prefix string e.g.: { uid: 123, pid: 110 } - callback: ObjectCallback; -} - -export interface PutObjectResult { - name: string; - data: object; - res: NormalSuccessResponse; -} - -export interface PutStreamOptions { - contentLength?: number; // the stream length, chunked encoding will be used if absent - timeout: number; // the operation timeout - mime: string; // custom mime, will send with Content-Type entity header - meta: UserMeta; - callback: ObjectCallback; -} - -export interface AppendObjectOptions { - position?: string; // specify the position which is the content length of the latest object - timeout?: number; // the operation timeout - mime?: string; // custom mime, will send with Content-Type entity header - meta?: UserMeta; - headers?: object; -} - -export interface AppendObjectResult { - name: string; - url: string; // the url of oss - res: NormalSuccessResponse; - nextAppendPosition: string; // the next position -} - -export interface HeadObjectOptions { - timeout?: number; - headers?: object; -} - -export interface HeadObjectResult { - status: number; // response status, maybe 200 or 304 - meta: UserMeta; - res: NormalSuccessResponse; -} - -export interface GetObjectOptions { - timeout?: number; - process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object; -} - -export interface GetObjectResult { - content?: any; // file content buffer if file parameter is null or ignore - res: NormalSuccessResponse; -} - -export interface GetStreamOptions { - timeout?: number; - process?: string; // image process params, will send with x-oss-process e.g.: {process: 'image/resize,w_200'} - headers?: object; -} - -export interface GetStreamResult { - stream?: any; // readable stream instance if response status is not 200, stream will be null. - res: NormalSuccessResponse; -} - -export interface CopyObjectOptions { - timeout?: number; - meta?: UserMeta; - headers?: object; -} - -export interface CopyAndPutMetaResult { - data: ModifyData; - res: NormalSuccessResponse; -} - -export interface DeleteMultiOptions { - quite?: boolean; // quiet mode or verbose mode, default is false - timeout?: number; -} - -export interface DeleteMultiResult { - deleted?: string[]; // deleted object names list - res: NormalSuccessResponse; -} - -export interface ResponseHeaderType { - 'content-type'?: string; - 'content-disposition'?: string; - 'cache-control'?: string; -} - -export interface SignatureUrlOptions { - expires?: number; // after expires seconds, the url will become invalid, default is 1800 - method?: HTTPMethods; // the HTTP method, default is 'GET' - 'Content-Type'?: string; // set the request content type - process?: string; - response?: ResponseHeaderType; // set the response headers for download - callback?: ObjectCallback; -} - -export interface GetACLResult { - acl: ACLType; - res: NormalSuccessResponse; -} - -export interface InitMultipartUploadOptions { - timeout?: number; - mime?: string; // Mime file type - meta?: UserMeta; - headers?: object; -} - -export interface InitMultipartUploadResult { - res: { status: number, headers: object, size: number, rt: number }; - bucket: string; // bucket name - name: string; // object name store on OSS - uploadId: string; // upload id, use for uploadPart, completeMultipart -} - -export interface UploadPartResult { - name: string; - etag: string; - res: NormalSuccessResponse; -} - -export interface CompleteMultipartUploadOptions { - timeout?: number; - callback?: ObjectCallback; - headers?: object; -} - -export interface CompleteMultipartUploadResult { - bucket: string; - name: string; - etag: string; - data: object; - res: NormalSuccessResponse; -} - -export interface MultipartUploadOptions { - parallel?: number; // the number of parts to be uploaded in parallel - partSize?: number; // the suggested size for each part - progress?: (...args: any[]) => any; // the progress callback called after each successful upload of one part - checkpoint?: Checkpoint; // the checkpoint to resume upload, if this is provided, it will continue the upload from where interrupted, otherwise a new multipart upload will be created. - meta?: UserMeta; - mime?: string; - callback?: ObjectCallback; - headers?: object; - timeout?: number; - copyheaders?: object; // {Object} only uploadPartCopy api used, detail -} - -export interface MultipartUploadResult { - bucket: string; - name: string; - etag: string; - data: object; - res: NormalSuccessResponse; -} - -export interface MultipartUploadCopyResult { - bucket: string; - name: string; - etag: string; - res: NormalSuccessResponse; -} - -export interface MultipartUploadCopySourceData { - sourceKey: string; // the source object name - sourceBucketName: string; // sourceData. the source bucket name - startOffset: number; // data copy start byte offset, e.g: 0 - endOffset: number; // data copy end byte offset, e.g: 102400 -} - -export interface ListPartsQuery { - 'max-parts': number; // The maximum part number in the response of the OSS. default value: 1000. - 'part-number-marker': number; // Starting position of a specific list. A part is listed only when the part number is greater than the value of this parameter. - 'encoding-type': string; // Specify the encoding of the returned content and the encoding type. Optional value: url -} - -export interface ListPartsResult { - uploadId: string; - bucket: string; - name: string; - PartNumberMarker: number; - nextPartNumberMarker: number; - maxParts: number; - isTruncated: boolean; - parts: ObjectPart[]; - res: NormalSuccessResponse; -} - -export interface ListUploadsQuery { - prefix?: string; - 'max-uploads'?: number; - 'key-marker'?: string; - 'upload-id-marker'?: string; -} - -export interface ListUploadsResult { - res: NormalSuccessResponse; - bucket: string; - nextKeyMarker: any; - nextUploadIdMarker: any; - isTruncated: boolean; - uploads: Upload[]; -} - -export interface PutChannelConf { - Description?: string; - Status?: string; - Target?: { - Type: string, - FragDuration: number, - FragCount: number, - PlaylistName: string - }; -} - -export interface PutChannelResult { - publishUrls: string[]; - playUrls: string[]; - res: NormalSuccessResponse; -} - -export interface GetChannelResult { - Status: string; - ConnectedTime?: string; - RemoteAddr?: string; - Video?: object; - Audio?: object; - res: NormalSuccessResponse; -} - -export interface ListChannelsQuery { - prefix: string; // the channel id prefix (returns channels with this prefix) - marker: string; // the channel id marker (returns channels after this id) - 'max-keys ': number; // max number of channels to return -} - -export interface ListChannelsResult { - channels: Channel[]; - nextMarker: string | null; - isTruncated: boolean; - res: NormalSuccessResponse; -} - -export interface ChannelHistoryResult { - records: ChannelHistory; - res: NormalSuccessResponse; -} - -export interface GetRtmpUrlOptions { - expires?: number; // the expire time in seconds of the url - params?: object; // the additional parameters for url, e.g.: {playlistName: 'play.m3u8'} - timeout?: number; // the operation timeout -} - -export default class OSS { - // the image client - static ImageClient: (options: ImageClientDefinition.ImageClientOptions) => ImageClientDefinition.ImageClient; - static Cluster: (options: ClusterDefinition.ClusterOptions) => ClusterDefinition.Cluster; - - constructor(options: Options) +declare class OSS { + constructor(options: OSS.Options) /******************************************* the bucket operations *************************************************/ @@ -447,12 +560,12 @@ export default class OSS { /** * List buckets in this account. */ - listBuckets(query: ListBucketsQueryType | null, options?: RequestOptions): Promise; + listBuckets(query: OSS.ListBucketsQueryType | null, options?: OSS.RequestOptions): Promise; /** * Create a new bucket. */ - putBucket(name: string, options?: PutBucketOptions): Promise<{ bucket: string, res: NormalSuccessResponse }>; + putBucket(name: string, options?: OSS.PutBucketOptions): Promise<{ bucket: string, res: OSS.NormalSuccessResponse }>; /** * Use the bucket. @@ -462,7 +575,7 @@ export default class OSS { /** * Delete an empty bucket. */ - deleteBucket(name: string, options?: RequestOptions): Promise; + deleteBucket(name: string, options?: OSS.RequestOptions): Promise; /** * Get bucket information,include CreationDate、ExtranetEndpoint、IntranetEndpoint、Location、Name、StorageClass、 Owner、AccessControlList @@ -478,114 +591,114 @@ export default class OSS { /** * Update the bucket ACL. */ - putBucketACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + putBucketACL(name: string, acl: OSS.ACLType, options?: OSS.RequestOptions): Promise; /** * Get the bucket ACL. * acl - acl settings string */ - getBucketACL(name: string, options?: RequestOptions): Promise<{ acl: string, res: NormalSuccessResponse }>; + getBucketACL(name: string, options?: OSS.RequestOptions): Promise<{ acl: string, res: OSS.NormalSuccessResponse }>; // logging operations /** * Update the bucket logging settings. Log file will create every one hour and name format: -YYYY-mm-DD-HH-MM-SS-UniqueString. */ - putBucketLogging(name: string, prefix?: string, options?: RequestOptions): Promise; + putBucketLogging(name: string, prefix?: string, options?: OSS.RequestOptions): Promise; /** * Get the bucket logging settings. */ - getBucketLogging(name: string, options?: RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: NormalSuccessResponse }>; + getBucketLogging(name: string, options?: OSS.RequestOptions): Promise<{ enable: boolean, prefix: string | null, res: OSS.NormalSuccessResponse }>; /** * Delete the bucket logging settings. */ - deleteBucketLogging(name: string, options?: RequestOptions): Promise; + deleteBucketLogging(name: string, options?: OSS.RequestOptions): Promise; // Website operations /** * Set the bucket as a static website. */ - putBucketWebsite(name: string, config: PutBucketWebsiteConfig): Promise; + putBucketWebsite(name: string, config: OSS.PutBucketWebsiteConfig): Promise; /** * Get the bucket website config. */ - getBucketWebsite(name: string, options?: RequestOptions): Promise<{ index: string, error: string, res: NormalSuccessResponse }>; + getBucketWebsite(name: string, options?: OSS.RequestOptions): Promise<{ index: string, error: string, res: OSS.NormalSuccessResponse }>; /** * Delete the bucket website config. */ - deleteBucketWebsite(name: string, options?: RequestOptions): Promise; + deleteBucketWebsite(name: string, options?: OSS.RequestOptions): Promise; // referer operations /** * Set the bucket request Referer white list. */ - putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: RequestOptions): Promise; + putBucketReferer(name: string, allowEmpty: boolean, referers: string[], options?: OSS.RequestOptions): Promise; /** * Get the bucket request Referer white list. */ - getBucketReferer(name: string, options?: RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: NormalSuccessResponse }>; + getBucketReferer(name: string, options?: OSS.RequestOptions): Promise<{ allowEmpty: boolean, referers: string[], res: OSS.NormalSuccessResponse }>; /** * Delete the bucket request Referer white list. */ - deleteBucketReferer(name: string, options?: RequestOptions): Promise; + deleteBucketReferer(name: string, options?: OSS.RequestOptions): Promise; // lifecycle operations /** * Set the bucket object lifecycle. */ - putBucketLifecycle(name: string, rules: LifecycleRule[], options?: RequestOptions): Promise; + putBucketLifecycle(name: string, rules: OSS.LifecycleRule[], options?: OSS.RequestOptions): Promise; /** * Get the bucket object lifecycle. */ - getBucketLifecycle(name: string, options?: RequestOptions): Promise<{ rules: LifecycleRule[], res: NormalSuccessResponse }>; + getBucketLifecycle(name: string, options?: OSS.RequestOptions): Promise<{ rules: OSS.LifecycleRule[], res: OSS.NormalSuccessResponse }>; /** * Delete the bucket object lifecycle. */ - deleteBucketLifecycle(name: string, options?: RequestOptions): Promise; + deleteBucketLifecycle(name: string, options?: OSS.RequestOptions): Promise; // CORS operations /** * Set CORS rules of the bucket object */ - putBucketCORS(name: string, rules: CORSRule[], options?: RequestOptions): Promise; + putBucketCORS(name: string, rules: OSS.CORSRule[], options?: OSS.RequestOptions): Promise; /** * Get CORS rules of the bucket object. */ - getBucketCORS(name: string): Promise<{ rules: CORSRule[], res: NormalSuccessResponse }>; + getBucketCORS(name: string): Promise<{ rules: OSS.CORSRule[], res: OSS.NormalSuccessResponse }>; /** * Delete CORS rules of the bucket object. */ - deleteBucketCORS(name: string): Promise; + deleteBucketCORS(name: string): Promise; /********************************************************** Object operations ********************************************/ /** * List objects in the bucket. */ - list(query: ListObjectsQuery | null, options: RequestOptions): Promise; + list(query: OSS.ListObjectsQuery | null, options: OSS.RequestOptions): Promise; /** * Add an object to the bucket. */ - put(name: string, file: any, options?: PutObjectOptions): Promise; + put(name: string, file: any, options?: OSS.PutObjectOptions): Promise; /** * Add a stream object to the bucket. */ - putStream(name: string, stream: any, options?: PutStreamOptions): Promise<{ name: string, res: NormalSuccessResponse }>; + putStream(name: string, stream: any, options?: OSS.PutStreamOptions): Promise<{ name: string, res: OSS.NormalSuccessResponse }>; /** * Append an object to the bucket, it's almost same as put, but it can add content to existing object rather than override it. */ - append(name: string, file: any, options?: AppendObjectOptions): Promise; + append(name: string, file: any, options?: OSS.AppendObjectOptions): Promise; /** * Get the Object url. If provide baseUrl, will use baseUrl instead the default endpoint. @@ -600,67 +713,67 @@ export default class OSS { /** * Head an object and get the meta info. */ - head(name: string, options?: HeadObjectOptions): Promise; + head(name: string, options?: OSS.HeadObjectOptions): Promise; /** * Get an object from the bucket. */ - get(name: string, file?: any, options?: GetObjectOptions): Promise; + get(name: string, file?: any, options?: OSS.GetObjectOptions): Promise; /** * Get an object read stream. */ - getStream(name?: string, options?: GetStreamOptions): Promise; + getStream(name?: string, options?: OSS.GetStreamOptions): Promise; /** * Delete an object from the bucket. */ - delete(name: string, options?: RequestOptions): Promise; + delete(name: string, options?: OSS.RequestOptions): Promise; /** * Copy an object from sourceName to name. */ - copy(name: string, sourceName: string, options?: CopyObjectOptions): Promise; + copy(name: string, sourceName: string, options?: OSS.CopyObjectOptions): Promise; /** * Set an exists object meta. */ - putMeta(name: string, meta: UserMeta, options: RequestOptions): Promise; + putMeta(name: string, meta: OSS.UserMeta, options: OSS.RequestOptions): Promise; /** * Delete multi objects in one request. */ - deleteMulti(names: string[], options?: DeleteMultiOptions): Promise; + deleteMulti(names: string[], options?: OSS.DeleteMultiOptions): Promise; /** * Create a signature url for download or upload object. When you put object with signatureUrl ,you need to pass Content-Type.Please look at the example. */ - signatureUrl(name: string, options?: SignatureUrlOptions): string; + signatureUrl(name: string, options?: OSS.SignatureUrlOptions): string; /** * Set object's ACL. */ - putACL(name: string, acl: ACLType, options?: RequestOptions): Promise; + putACL(name: string, acl: OSS.ACLType, options?: OSS.RequestOptions): Promise; /** * Get object's ACL. */ - getACL(name: string, options?: RequestOptions): Promise; + getACL(name: string, options?: OSS.RequestOptions): Promise; /** * Restore Object. */ - restore(name: string, options?: RequestOptions): Promise; + restore(name: string, options?: OSS.RequestOptions): Promise; /** * multi upload */ - initMultipartUpload(name: string, options?: InitMultipartUploadOptions): Promise; + initMultipartUpload(name: string, options?: OSS.InitMultipartUploadOptions): Promise; /** * After initiating a Multipart Upload event, you can upload data in parts based on the specified object name and Upload ID. */ - uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: RequestOptions): Promise; + uploadPart(name: string, uploadId: string, partNo: number, file: any, start: number, end: number, options?: OSS.RequestOptions): Promise; /** * Using Upload Part Copy, you can copy data from an existing object and upload a part of the data. @@ -673,7 +786,7 @@ export default class OSS { range: string, sourceData: { sourceKey: string, sourceBucketName: string }, options: { timeout?: number, headers?: object } - ): Promise; + ): Promise; /** * After uploading all data parts, you must call the Complete Multipart Upload API to complete Multipart Upload for the entire file. @@ -682,79 +795,79 @@ export default class OSS { name: string, uploadId: string, parts: Array<{ number: number, etag: string }>, - options?: CompleteMultipartUploadOptions - ): Promise; + options?: OSS.CompleteMultipartUploadOptions + ): Promise; /** * Upload file with OSS multipart. */ - multipartUpload(name: string, file: any, options: MultipartUploadOptions): Promise; + multipartUpload(name: string, file: any, options: OSS.MultipartUploadOptions): Promise; /** * Copy file with OSS multipart. * this function contains head, initMultipartUpload, uploadPartCopy, completeMultipartUpload. * When copying a file larger than 1 GB, you should use the Upload Part Copy method. If you want to copy a file smaller than 1 GB, see Copy Object. */ - multipartUploadCopy(name: string, sourceData: MultipartUploadCopySourceData, options?: MultipartUploadOptions): Promise; + multipartUploadCopy(name: string, sourceData: OSS.MultipartUploadCopySourceData, options?: OSS.MultipartUploadOptions): Promise; /** * The ListParts command can be used to list all successfully uploaded parts mapped to a specific upload ID, i.e.: those not completed and not aborted. */ - listParts(name: string, uploadId: string, query?: ListPartsQuery, options?: RequestOptions): Promise; + listParts(name: string, uploadId: string, query?: OSS.ListPartsQuery, options?: OSS.RequestOptions): Promise; /** * List on-going multipart uploads, i.e.: those not completed and not aborted. */ - listUploads(query: ListUploadsQuery, options?: RequestOptions): Promise; + listUploads(query: OSS.ListUploadsQuery, options?: OSS.RequestOptions): Promise; /** * Abort a multipart upload for object. */ - abortMultipartUpload(name: string, uploadId: string, options?: RequestOptions): Promise; + abortMultipartUpload(name: string, uploadId: string, options?: OSS.RequestOptions): Promise; /************************************************ RTMP Operations *************************************************************/ /** * Create a live channel. */ - putChannel(id: string, conf: PutChannelConf, options?: RequestOptions): Promise; + putChannel(id: string, conf: OSS.PutChannelConf, options?: OSS.RequestOptions): Promise; /** * Get live channel info. */ - getChannel(id: string, options?: RequestOptions): Promise<{ data: PutChannelConf, res: NormalSuccessResponse }>; + getChannel(id: string, options?: OSS.RequestOptions): Promise<{ data: OSS.PutChannelConf, res: OSS.NormalSuccessResponse }>; /** * Delete a live channel. */ - deleteChannel(id: string, options?: RequestOptions): Promise; + deleteChannel(id: string, options?: OSS.RequestOptions): Promise; /** * Change the live channel status. */ - putChannelStatus(id: string, status?: string, options?: RequestOptions): Promise; + putChannelStatus(id: string, status?: string, options?: OSS.RequestOptions): Promise; /** * Get the live channel status. */ - getChannelStatus(id: string, options?: RequestOptions): Promise; + getChannelStatus(id: string, options?: OSS.RequestOptions): Promise; /** * List channels. */ - listChannels(query: ListChannelsQuery, options?: RequestOptions): Promise; + listChannels(query: OSS.ListChannelsQuery, options?: OSS.RequestOptions): Promise; /** * Get the live channel history. */ - getChannelHistory(id: string, options?: RequestOptions): Promise; + getChannelHistory(id: string, options?: OSS.RequestOptions): Promise; /** * Create a VOD playlist for the channel. */ - createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: RequestOptions): Promise; + createVod(id: string, name: string, time: { startTime: number, endTime: number }, options?: OSS.RequestOptions): Promise; /** * Get signatured rtmp url for publishing. */ - getRtmpUrl(channelId?: string, options?: GetRtmpUrlOptions): string; + getRtmpUrl(channelId?: string, options?: OSS.GetRtmpUrlOptions): string; } diff --git a/types/ali-oss/tsconfig.json b/types/ali-oss/tsconfig.json index 62f030a4fd..6a0fb7441b 100644 --- a/types/ali-oss/tsconfig.json +++ b/types/ali-oss/tsconfig.json @@ -18,8 +18,6 @@ }, "files": [ "index.d.ts", - "ImageClient.d.ts", - "Cluster.d.ts", "ali-oss-tests.ts" ] } diff --git a/types/ali-oss/tslint.json b/types/ali-oss/tslint.json index f93cf8562a..8192d88dd1 100644 --- a/types/ali-oss/tslint.json +++ b/types/ali-oss/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-mergeable-namespace": false + } } diff --git a/types/alt/tslint.json b/types/alt/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/alt/tslint.json +++ b/types/alt/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/amplitude-js/amplitude-js-tests.ts b/types/amplitude-js/amplitude-js-tests.ts index 4f3c2ea307..c5ffbe9898 100644 --- a/types/amplitude-js/amplitude-js-tests.ts +++ b/types/amplitude-js/amplitude-js-tests.ts @@ -1,85 +1,110 @@ // Tests for Amplitude SDK TypeScript definitions module Amplitude.Tests { + function all() { - amplitude.init('YOUR_API_KEY_HERE', null, { - // optional configuration options + var client: amplitude.AmplitudeClient = new amplitude.AmplitudeClient(); + var identify: amplitude.Identify = new amplitude.Identify(); + var revenue: amplitude.Revenue = new amplitude.Revenue(); + + client = amplitude.getInstance(); + client = amplitude.getInstance('some name'); + + amplitude.__VERSION__ === '1.2.3'; + amplitude.options.logLevel = 'WARN'; + + amplitude.init('API_KEY', 'USER_ID', { saveEvents: true, includeUtm: true, includeReferrer: true, batchEvents: true, eventUploadThreshold: 50 - }); - amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE', null, () => {}); + }, function () { }); + amplitude.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true }); + amplitude.init('API_KEY', 'USER_ID'); + amplitude.init('API_KEY'); - amplitude.logEvent('EVENT_IDENTIFIER_HERE'); - amplitude.setUserId('USER_ID_HERE'); - amplitude.init('YOUR_API_KEY_HERE', 'USER_ID_HERE'); - amplitude.setUserId(null); // not string 'null' - amplitude.setVersionName('VERSION_NAME_HERE'); - - amplitude.regenerateDeviceId(); - amplitude.setDeviceId('CUSTOM_DEVICE_ID'); - - amplitude.logEvent('EVENT_IDENTIFIER_HERE', { - 'color': 'blue', - 'age': 20, - 'key': 'value' - }); + amplitude.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 }); + amplitude.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' }); amplitude.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + + amplitude.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0'); + amplitude.setDomain('.amplitude.com'); + amplitude.setGroup('orgId', '15'); + amplitude.setGroup('orgId', ['15', '16']); + amplitude.setUserId('joe@gmail.com'); + amplitude.setUserProperties({ 'gender': 'female', 'sign_up_complete': true }) + amplitude.setVersionName('1.12.3'); + amplitude.isNewSession(); + amplitude.getSessionId() === 123; - let identify = new amplitude.Identify().set('gender', 'female').set('age', 20); amplitude.identify(identify); + amplitude.logRevenue(3.99, 1, 'product_1234'); + amplitude.logRevenueV2(revenue); - identify = new amplitude.Identify().setOnce('sign_up_date', '08/24/2015'); - amplitude.identify(identify); - identify = new amplitude.Identify().setOnce('sign_up_date', '09/14/2015'); - amplitude.identify(identify); + client.init('API_KEY', 'USER_ID', { + saveEvents: true, + includeUtm: true, + includeReferrer: true, + batchEvents: true, + eventUploadThreshold: 50 + }, function () { }); + client.init('API_KEY', 'USER_ID', { includeReferrer: true, includeUtm: true }); + client.init('API_KEY', 'USER_ID'); + client.init('API_KEY'); - identify = new amplitude.Identify().unset('gender').unset('age'); - amplitude.identify(identify); + client.logEvent('Clicked Homepage Button', { 'finished_flow': false, 'clicks': 15 }); + client.logEvent('EVENT_IDENTIFIER_HERE', { 'color': 'blue', 'age': 20, 'key': 'value' }); + client.logEvent("EVENT_IDENTIFIER_HERE", null, (httpCode, response) => { }); + client.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); + client.logEventWithTimestamp('EVENT_IDENTIFIER_HERE', { 'key': 'value' }, 1505430378000, (httpCode, response) => { }); + + client.setDeviceId('45f0954f-eb79-4463-ac8a-233a6f45a8f0'); + client.setDomain('.amplitude.com'); + client.setUserId('joe@gmail.com'); + client.setOptOut(true); + client.setGroup('type', 'name'); + client.setGroup('type', ['name', 'name2']); + client.setUserProperties({ 'gender': 'female', 'sign_up_complete': true }); + client.setGlobalUserProperties({ 'gender': 'female', 'sign_up_complete': true }); + client.setVersionName('1.12.3'); + client.setSessionId(1505430378000); + + client.options.logLevel = 'WARN'; + client.getSessionId() === 123; + client.isNewSession() === true; + client.regenerateDeviceId(); + client.clearUserProperties(); + + client.identify(identify); + client.logRevenue(3.99, 1, 'product_1234'); + client.logRevenueV2(revenue); + + + identify = new amplitude.Identify().set('colors', ['rose', 'gold']).add('karma', 1).setOnce('sign_up_date', '2016-03-31'); identify = new amplitude.Identify().add('karma', 1).add('friends', 1); - amplitude.identify(identify); - - identify = new amplitude.Identify().append('ab-tests', 'new-user-test').append('some_list', [1, 2, 3, 4, 'values']); - amplitude.identify(identify); - - identify = new amplitude.Identify().prepend('ab-tests', 'new-user-test').prepend('some_list', [1, 2, 3, 4, 'values']); - amplitude.identify(identify); - - identify = new amplitude.Identify() - .set('karma', 10) - .add('karma', 1) - .unset('karma'); - amplitude.identify(identify); - + identify = new amplitude.Identify().set('karma', 10).add('karma', 1).unset('karma'); + identify = new amplitude.Identify().append('ab-tests', 'new-user-tests'); + identify.append('some_list', [1, 2, 3, 4, 'values']); + identify = new amplitude.Identify().prepend('ab-tests', 'new-user-tests'); + identify.prepend('some_list', [1, 2, 3, 4, 'values']); + identify = new amplitude.Identify().set('user_type', 'beta'); + identify.set('name', { 'first': 'John', 'last': 'Doe' }); + identify = new amplitude.Identify().setOnce('sign_up_date', '2016-04-01'); + identify = new amplitude.Identify().unset('user_type').unset('age'); identify = new amplitude.Identify() .set('colors', ['rose', 'gold']) .append('ab-tests', 'campaign_a') .append('existing_list', [4, 5]); - amplitude.identify(identify); - amplitude.setUserProperties({ - gender: 'female', - age: 20 - }); - amplitude.clearUserProperties(); - - amplitude.setOptOut(true); - amplitude.setOptOut(false); - - amplitude.setGroup('orgId', '15'); - amplitude.setGroup('sport', ['soccer', 'tennis']); - - // TODO: Implement those. - /* - var revenue = new amplitude.Revenue().setProductId('com.company.productId').setPrice(3.99).setQuantity(3); - amplitude.logRevenueV2(revenue); - - amplitude.logEventWithGroups('initialize_game', { 'key': 'value' }, { 'sport': 'soccer' }); - */ + revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99); + revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setEventProperties({ 'city': 'San Francisco' }); + revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setQuantity(5); + revenue = new amplitude.Revenue().setProductId('productIdentifier').setPrice(10.99).setRevenueType('purchase'); } + } diff --git a/types/amplitude-js/index.d.ts b/types/amplitude-js/index.d.ts index 613f5ad5d8..1cdb843589 100644 --- a/types/amplitude-js/index.d.ts +++ b/types/amplitude-js/index.d.ts @@ -1,61 +1,146 @@ -// Type definitions for Amplitude SDK 2.12.1 +// Type definitions for Amplitude SDK 4.4.0 // Project: https://github.com/amplitude/Amplitude-Javascript // Definitions by: Arvydas Sidorenko -// Definitions: https://github.com/Asido/DefinitelyTyped +// Dan Manastireanu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module amplitude { + + type Callback = (responseCode: number, responseBody: string, details?: { reason: string; }) => void; + type LogReturn = number | void; + interface Config { + apiEndpoint?: string; batchEvents?: boolean; cookieExpiration?: number; cookieName?: string; + userId?: string; deviceId?: string; + deviceIdFromUrlParam?: boolean; domain?: string; eventUploadPeriodMillis?: number; eventUploadThreshold?: number; + forceHttps?: boolean; + includeGclid?: boolean; includeReferrer?: boolean; includeUtm?: boolean; language?: string; + logLevel?: 'DISABLE' | 'ERROR' | 'WARN' | 'INFO'; optOut?: boolean; platform?: string; saveEvents?: boolean; savedMaxCount?: number; + saveParamsReferrerOncePerSession?: boolean; sessionTimeout?: number; + trackingOptions?: { + city?: boolean; + country?: boolean; + device_model?: boolean; + dma?: boolean; + ip_address?: boolean; + language?: boolean; + os_name?: boolean; + os_version?: boolean; + platform?: boolean; + region?: boolean; + version_name?: boolean; + }, + unsentKey?: string; + unsentIdentifyKey?: string; uploadBatchSize?: number; } export class Identify { set(key: string, value: any): Identify; setOnce(key: string, value: any): Identify; - add(key: string, value: number): Identify; + add(key: string, value: number | string): Identify; append(key: string, value: any): Identify; prepend(key: string, value: any): Identify; unset(key: string): Identify; } - export function init(apiKey: string): void; - export function init(apiKey: string, userId: string): void; - export function init(apiKey: string, userId: string, options: Config): void; - export function init(apiKey: string, userId: string, options: Config, callback: () => void): void; + export class Revenue { + + setProductId(productId: string): Revenue; + setQuantity(quantity: number): Revenue; + setPrice(price: number): Revenue; + setRevenueType(revenueType: string): Revenue; + setEventProperties(eventProperties: any): Revenue; + } + + export class AmplitudeClient { + + constructor(instanceName?: string); + + options: Config; + + init(apiKey: string, userId?: string, config?: Config, callback?: (client: AmplitudeClient) => void): void; + + setVersionName(versionName: string): void; + + isNewSession(): boolean; + setSessionId(sessionId: number): void; + getSessionId(): number; + + setDomain(domain: string): void; + setUserId(userId: string): void; + + setDeviceId(id: string): void; + regenerateDeviceId(): void; + + identify(identify_obj: Identify, opt_callback?: Callback): void; + + setUserProperties(properties: any): void; + setGlobalUserProperties(properties: any): void; + clearUserProperties(): void; + + setOptOut(enable: boolean): void; + + setGroup(groupType: string, groupName: string | string[]): void; + + logEvent(event: string, data?: any, callback?: Callback): LogReturn; + logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; + logRevenueV2(revenue_obj: Revenue): LogReturn; + logRevenue(pric: number, quantity: number, product: string): LogReturn; + logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; + } + + // Proxy methods that get executed on the default AmplitudeClient instance (not all client methods are proxied) + + export function init(apiKey: string, userId?: string, options?: Config, callback?: (client: AmplitudeClient) => void): void; export function setVersionName(version: string): void; + + export function isNewSession(): boolean; + export function getSessionId(): number; + + export function setDomain(domain: string): void; + export function setUserId(userId: string): void; export function setDeviceId(id: string): void; export function regenerateDeviceId(): void; - export function identify(identify: Identify): void; + export function identify(identify: Identify, callback?: Callback): void; - export function setUserProperties(properties: Object): void; + export function setUserProperties(properties: any): void; + export function setGlobalUserProperties(properties: any): void; export function clearUserProperties(): void; export function setOptOut(optOut: boolean): void; export function setGroup(groupType: string, groupName: string | string[]): void; - export function logEvent(event: string): void; - export function logEvent(event: string, data: Object): void; - export function logEvent(event: string, data: Object, callback: (httpCode: number, response: any) => void): void; + export function logEvent(event: string, data?: any, callback?: Callback): LogReturn; + export function logEventWithGroups(event: string, data?: any, groups?: any, callback?: Callback): LogReturn; + export function logRevenueV2(revenue_obj: Revenue): LogReturn; + export function logRevenue(pric: number, quantity: number, product: string): LogReturn; + export function logEventWithTimestamp(event: string, data?: any, timestamp?: number, callback?: Callback): LogReturn; + + + export function getInstance(instanceName?: string): AmplitudeClient; + export const __VERSION__: string; export var options: Config; } 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/amqplib/index.d.ts b/types/amqplib/index.d.ts index 9ad6d9ceda..2ea088f841 100644 --- a/types/amqplib/index.d.ts +++ b/types/amqplib/index.d.ts @@ -8,7 +8,7 @@ import * as Promise from 'bluebird'; import * as events from 'events'; -import { Replies, Options, Message } from './properties'; +import { Replies, Options, Message, GetMessage, ConsumeMessage } from './properties'; export * from './properties'; export interface Connection extends events.EventEmitter { @@ -40,10 +40,10 @@ export interface Channel extends events.EventEmitter { publish(exchange: string, routingKey: string, content: Buffer, options?: Options.Publish): boolean; sendToQueue(queue: string, content: Buffer, options?: Options.Publish): boolean; - consume(queue: string, onMessage: (msg: Message | null) => any, options?: Options.Consume): Promise; + consume(queue: string, onMessage: (msg: ConsumeMessage | null) => any, options?: Options.Consume): Promise; cancel(consumerTag: string): Promise; - get(queue: string, options?: Options.Get): Promise; + get(queue: string, options?: Options.Get): Promise; ack(message: Message, allUpTo?: boolean): void; ackAll(): void; diff --git a/types/amqplib/properties.d.ts b/types/amqplib/properties.d.ts index 9f96b14f5c..97dc8ac393 100644 --- a/types/amqplib/properties.d.ts +++ b/types/amqplib/properties.d.ts @@ -145,12 +145,32 @@ export interface Message { properties: MessageProperties; } -export interface MessageFields { +export interface GetMessage extends Message { + fields: GetMessageFields; +} + +export interface ConsumeMessage extends Message { + fields: ConsumeMessageFields; +} + +export interface CommonMessageFields { deliveryTag: number; redelivered: boolean; exchange: string; routingKey: string; - messageCount: string; +} + +export interface MessageFields extends CommonMessageFields { + messageCount?: number; + consumerTag?: string; +} + +export interface GetMessageFields extends CommonMessageFields { + messageCount: number; +} + +export interface ConsumeMessageFields extends CommonMessageFields { + deliveryTag: number; } export interface MessageProperties { diff --git a/types/amqplib/tslint.json b/types/amqplib/tslint.json index bfc9508c49..f64a783725 100644 --- a/types/amqplib/tslint.json +++ b/types/amqplib/tslint.json @@ -2,6 +2,7 @@ "extends": "dtslint/dt.json", "rules": { // All are TODOs + "no-any-union": false, "no-empty-interface": false, "prefer-const": false } diff --git a/types/analytics-node/index.d.ts b/types/analytics-node/index.d.ts index 6834087ff7..cc9e5386e2 100644 --- a/types/analytics-node/index.d.ts +++ b/types/analytics-node/index.d.ts @@ -22,8 +22,8 @@ declare namespace AnalyticsNode { }, timestamp?: Date; messageId?: string; - anonymousId: string | number; - userId: string | number; + anonymousId?: string | number; + userId?: string | number; } interface Data { @@ -47,7 +47,8 @@ declare namespace AnalyticsNode { /* The identify method lets you tie a user to their actions and record traits about them. */ identify(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; traits?: Object; timestamp?: Date; context?: Object; @@ -56,7 +57,8 @@ declare namespace AnalyticsNode { /* The track method lets you record the actions your users perform. */ track(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; event: string; properties?: Object; timestamp?: Date; @@ -67,7 +69,8 @@ declare namespace AnalyticsNode { /* The page method lets you record page views on your website, along with optional extra information about the page being viewed. */ page(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; category?: string; name?: string; properties?: Object; @@ -79,19 +82,20 @@ declare namespace AnalyticsNode { /* alias is how you associate one identity with another. */ alias(message: { previousId: string | number; - userId: string | number; + userId?: string | number; + anonymousId?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; /* Group calls can be used to associate individual users with shared accounts or companies. */ group(message: { - userId: string | number; + userId?: string | number; + anonymousId?: string | number; groupId: string | number; traits?: Object; context?: Object; timestamp?: Date; - anonymous_id?: string | number; integrations?: Integrations; }, callback?: (err: Error, data: Data) => void): Analytics; 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-bootstrap-lightbox/tslint.json b/types/angular-bootstrap-lightbox/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/angular-bootstrap-lightbox/tslint.json +++ b/types/angular-bootstrap-lightbox/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": 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 6885916e8a..db74c97d10 100644 --- a/types/angular-material/index.d.ts +++ b/types/angular-material/index.d.ts @@ -76,6 +76,7 @@ declare module 'angular' { interface IConfirmDialog extends IPresetDialog { cancel(cancel: string): IConfirmDialog; + multiple(multiple: boolean): IConfirmDialog; } interface IPromptDialog extends IPresetDialog { @@ -340,6 +341,7 @@ declare module 'angular' { interface IMenuService { hide(response?: any, options?: any): IPromise; + open(event?: MouseEvent): void; } interface IColorPalette { diff --git a/types/angular-meteor/tslint.json b/types/angular-meteor/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/angular-meteor/tslint.json +++ b/types/angular-meteor/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, 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-pdfjs-viewer/tsconfig.json b/types/angular-pdfjs-viewer/tsconfig.json index bdae87bf50..05a851782e 100644 --- a/types/angular-pdfjs-viewer/tsconfig.json +++ b/types/angular-pdfjs-viewer/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/angular-promise-tracker/angular-promise-tracker-tests.ts b/types/angular-promise-tracker/angular-promise-tracker-tests.ts index 0365709cf5..6b8b8abd31 100644 --- a/types/angular-promise-tracker/angular-promise-tracker-tests.ts +++ b/types/angular-promise-tracker/angular-promise-tracker-tests.ts @@ -1,5 +1,5 @@ -angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', - ($q: angular.IQService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { +angular.module('promise-tracker-tests', []).run(['$q', '$http', 'promiseTracker', + ($q: angular.IQService, $http: angular.IHttpService, promiseTracker: angular.promisetracker.PromiseTrackerService) => { const trackerWithoutOptions = promiseTracker(); const options = { @@ -19,4 +19,8 @@ angular.module('promise-tracker-tests', []).run(['$q', 'promiseTracker', const addedPromise: angular.IDeferred = trackerWithOptions.addPromise(promiseToAdd); const trackerWithSomeOptions = promiseTracker({activationDelay: 500}); + + $http.post('/foo', {}, { }); + $http.post('/foo', {}, { tracker: trackerWithOptions }); + $http.post('/foo', {}, { tracker: [trackerWithoutOptions, trackerWithOptions] }); }]); diff --git a/types/angular-promise-tracker/index.d.ts b/types/angular-promise-tracker/index.d.ts index 85a87bad63..78849fa3e1 100644 --- a/types/angular-promise-tracker/index.d.ts +++ b/types/angular-promise-tracker/index.d.ts @@ -28,4 +28,8 @@ declare module 'angular' { (options?: PromiseTrackerOptions): PromiseTracker; } } + + interface IRequestShortcutConfig { + tracker?: angular.promisetracker.PromiseTracker | angular.promisetracker.PromiseTracker[]; + } } diff --git a/types/angular-q-extras/tsconfig.json b/types/angular-q-extras/tsconfig.json index 3047a809eb..973131f033 100644 --- a/types/angular-q-extras/tsconfig.json +++ b/types/angular-q-extras/tsconfig.json @@ -6,7 +6,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/angular-toastr/angular-toastr-tests.ts b/types/angular-toastr/angular-toastr-tests.ts index 6cb4290b3c..37a9885e9c 100644 --- a/types/angular-toastr/angular-toastr-tests.ts +++ b/types/angular-toastr/angular-toastr-tests.ts @@ -16,6 +16,10 @@ angular closeButton: false, closeHtml: '', extendedTimeOut: 1000, + extraData: { + txt: "sample text", + action: () => {/* Do action */}, + }, iconClasses: { error: 'toast-error', info: 'toast-info', @@ -29,7 +33,6 @@ angular progressBar: false, tapToDismiss: true, templates: { - toast: 'directives/toast/toast.html', progressbar: 'directives/progressbar/progressbar.html' }, diff --git a/types/angular-toastr/index.d.ts b/types/angular-toastr/index.d.ts index 21cf13cce2..f264e71f46 100644 --- a/types/angular-toastr/index.d.ts +++ b/types/angular-toastr/index.d.ts @@ -24,6 +24,7 @@ declare module 'angular' { closeButton?: boolean; closeHtml?: string; extendedTimeOut?: number; + extraData?: any, messageClass?: string; onHidden?: (wasClicked: boolean, toast: angular.toastr.IToast) => void; onShown?: (toast: angular.toastr.IToast) => void; diff --git a/types/angular-ui-sortable/angular-ui-sortable-tests.ts b/types/angular-ui-sortable/angular-ui-sortable-tests.ts index 9ecde2f92a..9418b5741c 100644 --- a/types/angular-ui-sortable/angular-ui-sortable-tests.ts +++ b/types/angular-ui-sortable/angular-ui-sortable-tests.ts @@ -16,6 +16,9 @@ interface SortLogInfo { Text: string; } +// Ensure that the jQuery-ui defined `sortable()` method is not overwritten +jQuery().sortable(); // $ExpectType JQuery + myApp.controller('sortableController', function ($scope: MySortableControllerScope) { $scope.sortableOptions = { activate: function(e, ui) { @@ -84,6 +87,7 @@ myApp.controller('sortableController', function ($scope: MySortableControllerSco update: function(e, ui) { var jQueryEventObject: JQueryEventObject = e; var uiSortableUIParams: ng.ui.UISortableUIParams = ui; + ui.item.sortable; // $ExpectType UISortableProperties var voidcanceled: void = ui.item.sortable.cancel(); var isCanceled: Boolean = ui.item.sortable.isCanceled(); var isCustomHelperUsed: Boolean =ui.item.sortable.isCustomHelperUsed(); diff --git a/types/angular-ui-sortable/index.d.ts b/types/angular-ui-sortable/index.d.ts index aa81038346..9ecf06e112 100644 --- a/types/angular-ui-sortable/index.d.ts +++ b/types/angular-ui-sortable/index.d.ts @@ -2,12 +2,16 @@ // Project: https://github.com/angular-ui/ui-sortable // Definitions by: Thodoris Greasidis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.4 /// +/// import * as ng from 'angular'; +// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 +type Omit = Pick; + declare module 'angular' { export namespace ui { @@ -79,11 +83,11 @@ declare module 'angular' { isCustomHelperUsed(): Boolean; } - interface UISortableUIItem extends ng.IAugmentedJQuery { + interface UISortableUIItem extends Omit { sortable: UISortableProperties; } - interface UISortableUIParams extends SortableUIParams { + interface UISortableUIParams extends Omit { item: UISortableUIItem; } 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-wizard/index.d.ts b/types/angular-wizard/index.d.ts index 33fa8b2b0a..fa14a2f2f7 100644 --- a/types/angular-wizard/index.d.ts +++ b/types/angular-wizard/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/mgonto/angular-wizard // Definitions by: Marko Jurisic , Ronald Wildenberg // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as angular from 'angular'; diff --git a/types/angular-wizard/tslint.json b/types/angular-wizard/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/angular-wizard/tslint.json +++ b/types/angular-wizard/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": 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/animejs/index.d.ts b/types/animejs/index.d.ts index a975f59513..069187b15e 100644 --- a/types/animejs/index.d.ts +++ b/types/animejs/index.d.ts @@ -4,7 +4,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -type FunctionBasedParamter = (element: HTMLElement, index: number, length: number) => number; +type FunctionBasedParameter = (element: HTMLElement, index: number, length: number) => number; type AnimeCallbackFunction = (anim: anime.AnimeInstance) => void; // Allowing null is necessary because DOM queries may not return anything. type AnimeTarget = string | object | HTMLElement | SVGElement | NodeList | null; @@ -55,10 +55,10 @@ declare namespace anime { interface AnimeAnimParams { targets: AnimeTarget | ReadonlyArray; - duration?: number | FunctionBasedParamter; - delay?: number | FunctionBasedParamter; - elasticity?: number | FunctionBasedParamter; - round?: number | boolean | FunctionBasedParamter; + duration?: number | FunctionBasedParameter; + delay?: number | FunctionBasedParameter; + elasticity?: number | FunctionBasedParameter; + round?: number | boolean | FunctionBasedParameter; easing?: EasingOptions | string | ReadonlyArray; @@ -106,7 +106,7 @@ declare namespace anime { } interface AnimeTimelineAnimParams extends AnimeAnimParams { - offset: number | string | FunctionBasedParamter; + offset: number | string | FunctionBasedParameter; } interface AnimeTimelineInstance extends AnimeInstance { diff --git a/types/ansi-styles/index.d.ts b/types/ansi-styles/index.d.ts index a07ac962ab..b67cdada41 100644 --- a/types/ansi-styles/index.d.ts +++ b/types/ansi-styles/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: bryn austin bellomy // plylrnsdy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - +// TypeScript Version: 2.1 import { EscapeCode } from './escape-code'; diff --git a/types/ansi/ansi-tests.ts b/types/ansi/ansi-tests.ts new file mode 100644 index 0000000000..0c033c6839 --- /dev/null +++ b/types/ansi/ansi-tests.ts @@ -0,0 +1,32 @@ +import ansi = require('ansi'); +const cursor = ansi(process.stdout); + +Object.keys({ + white: 37 + , black: 30 + , blue: 34 + , cyan: 36 + , green: 32 + , magenta: 35 + , red: 31 + , yellow: 33 + , grey: 90 + , brightBlack: 90 + , brightRed: 91 + , brightGreen: 92 + , brightYellow: 93 + , brightBlue: 94 + , brightMagenta: 95 + , brightCyan: 96 + , brightWhite: 97 +}).forEach((color) => { + const cname = color.replace(/([a-z])([A-Z])/g, (_: string, l: string, u: string): string => `${l} ${u.toLowerCase()}`); + + ((cursor[color] as (...anything: any[]) => ansi.Cursor)() + .bold() + .bg)[color === 'blue' || color === 'brightBlue' ? 'black' : 'blue']() + .write( + `Hello, bold ${cname} world!\n` + ) + .reset(); +}); diff --git a/types/ansi/index.d.ts b/types/ansi/index.d.ts new file mode 100644 index 0000000000..4e486d61ef --- /dev/null +++ b/types/ansi/index.d.ts @@ -0,0 +1,181 @@ +// Type definitions for ansi 0.3 +// Project: https://www.npmjs.com/package/ansi +// Definitions by: Gustavo6046 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/** + * References: + * + * - http://en.wikipedia.org/wiki/ANSI_escape_code + * - http://www.termsys.demon.co.uk/vtansi.htm + * + */ + +/// +import { Stream } from "stream"; + +interface CursorOptions { + enabled: boolean; + buffering: boolean; +} + +declare function ansi(stream: Stream, options?: CursorOptions): ansi.Cursor; + +declare namespace ansi { + class Cursor { + bg: Colorer; + fg: Colorer; + + constructor(stream: Stream, options?: CursorOptions); + + /** + * Helper function that calls `write()` on the underlying Stream. + * Returns `this` instead of the write() return value to keep + * the chaining going. + */ + write(data: string): Cursor; + + /** + * Buffer `write()` calls into memory. + * + * @api public + */ + buffer(): Cursor; + + /** + * Write out the in-memory buffer. + * + * @api public + */ + flush(): Cursor; + + /** + * Makes a beep sound! + */ + beep(): Cursor; + + /** + * Moves cursor to specific position + */ + goto(x?: number, y?: number): Cursor; + + /** + * Resets all ANSI formatting on the stream. + */ + reset(): Cursor; + + /** + * Sets the foreground color with the given RGB values. + * The closest match out of the 216 colors is picked. + */ + rgb(r: number, g: number, b: number): Cursor; + + /** + * Accepts CSS color codes for use with ANSI escape codes. + * For example: `#FF000` would be bright red. + */ + hex(color: string): Cursor; + + up(): Cursor; + down(): Cursor; + forward(): Cursor; + back(): Cursor; + nextLine(): Cursor; + previousLine(): Cursor; + horizontalAbsolute(): Cursor; + eraseData(): Cursor; + eraseLine(): Cursor; + scrollUp(): Cursor; + scrollDown(): Cursor; + savePosition(): Cursor; + restorePosition(): Cursor; + queryPosition(): Cursor; + hide(): Cursor; + show(): Cursor; + + bold(): Cursor; + italic(): Cursor; + underline(): Cursor; + inverse(): Cursor; + resetbold(): Cursor; + resetitalic(): Cursor; + resetunderline(): Cursor; + resetinverse(): Cursor; + + white(): Cursor; + black(): Cursor; + blue(): Cursor; + cyan(): Cursor; + green(): Cursor; + magenta(): Cursor; + red(): Cursor; + yellow(): Cursor; + grey(): Cursor; + brightBlack(): Cursor; + brightRed(): Cursor; + brightGreen(): Cursor; + brightYellow(): Cursor; + brightBlue(): Cursor; + brightMagenta(): Cursor; + brightCyan(): Cursor; + brightWhite(): Cursor; + } + + /** + * The `Colorer` class manages both the background and foreground colors. + */ + class Colorer { + constructor(cursor: Cursor, base: string); + + /** + * Write an ANSI color code, ensuring that the same code doesn't get rewritten. + */ + _setColorCode(code: string): Colorer; + + /** + * Resets the color. + */ + reset(): Cursor; + + /** + * Sets the foreground color with the given RGB values. + * The closest match out of the 216 colors is picked. + */ + rgb(r: number, g: number, b: number): Cursor; + + /** + * Accepts CSS color codes for use with ANSI escape codes. + * For example: `#FF000` would be bright red. + */ + hex(color: string): Cursor; + + white(): Cursor; + black(): Cursor; + blue(): Cursor; + cyan(): Cursor; + green(): Cursor; + magenta(): Cursor; + red(): Cursor; + yellow(): Cursor; + grey(): Cursor; + brightBlack(): Cursor; + brightRed(): Cursor; + brightGreen(): Cursor; + brightYellow(): Cursor; + brightBlue(): Cursor; + brightMagenta(): Cursor; + brightCyan(): Cursor; + brightWhite(): Cursor; + } + + interface Cursor { + [key: string]: ((...anything: any[]) => Cursor) | Colorer; + } + + interface Colorer { + [key: string]: (...anything: any[]) => (Cursor | Colorer); + } +} + +export = ansi; diff --git a/types/ansi/tsconfig.json b/types/ansi/tsconfig.json new file mode 100644 index 0000000000..8c698148e6 --- /dev/null +++ b/types/ansi/tsconfig.json @@ -0,0 +1,24 @@ +{ + "files": [ + "index.d.ts", + "ansi-tests.ts" + ], + "compilerOptions": { + "module": "commonjs", + "target": "es5", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "noEmit": true, + "types": [], + "forceConsistentCasingInFileNames": true + } +} \ No newline at end of file diff --git a/types/ansi/tslint.json b/types/ansi/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/ansi/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file 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/aphrodite/index.d.ts b/types/aphrodite/index.d.ts index 3e7807b6b6..f41aadec46 100644 --- a/types/aphrodite/index.d.ts +++ b/types/aphrodite/index.d.ts @@ -12,7 +12,7 @@ type FontFamily = | BaseCSSProperties['fontFamily'] | CSS.FontFace; -type Omit = Pick; +type Omit = Pick>; type CSSProperties = Omit & { fontFamily?: FontFamily | FontFamily[]; diff --git a/types/apollo-codegen/index.d.ts b/types/apollo-codegen/index.d.ts index ea5d415418..4309db4116 100644 --- a/types/apollo-codegen/index.d.ts +++ b/types/apollo-codegen/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apollographql/apollo-codegen // Definitions by: Bradley Ayers , Maria Carrasco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { Options } from 'graphql/utilities/schemaPrinter'; diff --git a/types/apollo-upload-client/index.d.ts b/types/apollo-upload-client/index.d.ts index 7c1e3cb7b6..c6476f2ae9 100644 --- a/types/apollo-upload-client/index.d.ts +++ b/types/apollo-upload-client/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/jaydenseric/apollo-upload-client#readme // Definitions by: Edward Sammut Alessi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.6 import { ApolloLink } from "apollo-link"; import { HttpOptions } from "apollo-link-http-common"; diff --git a/types/apollo-upload-client/tsconfig.json b/types/apollo-upload-client/tsconfig.json index 2a023ff111..a78e75500c 100644 --- a/types/apollo-upload-client/tsconfig.json +++ b/types/apollo-upload-client/tsconfig.json @@ -2,7 +2,9 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", "dom" + "es6", + "dom", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/apostrophe/index.d.ts b/types/apostrophe/index.d.ts index bab1b3a7de..9c415a3931 100644 --- a/types/apostrophe/index.d.ts +++ b/types/apostrophe/index.d.ts @@ -7,7 +7,10 @@ export = apostrophe; export as namespace apos; -declare function apostrophe(options: any, ...args: any[]): any; +declare function apostrophe( + options: apostrophe.AposConstructor, + ...args: any[] +): any; declare namespace apostrophe { const moogBundle: { @@ -15,6 +18,20 @@ declare namespace apostrophe { modules: string[]; }; + // Pass in custom modules as first argument + // second argument is additional custom options e.g. restApi exposed by apostrophe-headless + interface AposConstructor { + afterInit?: () => void; + afterListen?: () => void; + initFailed?: (error: any) => void; + baseUrl?: string; + modules: { [K in AposCoreModules & M]?: AposModuleOptions | O }; + prefix?: string; + root?: string; + rootDir?: string; + shortName: string; + } + const ui: { globalBusy: (state: any) => any; link: ( @@ -124,8 +141,18 @@ declare namespace apostrophe { name: string; type: string; label: string; + help?: string; required?: boolean; options?: AposObject; + choices?: SelectChoice[]; + widgetType?: string; + titleField?: string; + schema?: Field[]; + } + + interface SelectChoice { + label: string; + value: string; } type Fields = Field[]; @@ -290,6 +317,7 @@ declare namespace apostrophe { label: string; fields: string[]; }[]; + beforeConstruct?: (self: any, options: any) => any; defer?: boolean; filters?: { projection?: { diff --git a/types/app-module-path/app-module-path-tests.ts b/types/app-module-path/app-module-path-tests.ts new file mode 100644 index 0000000000..5dc1012ca1 --- /dev/null +++ b/types/app-module-path/app-module-path-tests.ts @@ -0,0 +1,7 @@ +import { addPath, enableForDir, removePath } from 'app-module-path'; + +addPath('/tmp'); + +enableForDir('/tmp'); + +removePath('/tmp'); diff --git a/types/app-module-path/index.d.ts b/types/app-module-path/index.d.ts new file mode 100644 index 0000000000..00280c4191 --- /dev/null +++ b/types/app-module-path/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for app-module-path 2.2 +// Project: https://github.com/patrick-steele-idem/app-module-path-node +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function addPath(path: string, parent?: any): void; + +export function enableForDir(dir: string): void; + +export function removePath(path: string): void; diff --git a/types/app-module-path/tsconfig.json b/types/app-module-path/tsconfig.json new file mode 100644 index 0000000000..93d4d0a365 --- /dev/null +++ b/types/app-module-path/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", + "app-module-path-tests.ts" + ] +} diff --git a/types/app-module-path/tslint.json b/types/app-module-path/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/app-module-path/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/applicationinsights-js/applicationinsights-js-tests.ts b/types/applicationinsights-js/applicationinsights-js-tests.ts index c2adb63a30..de6de9a2c6 100644 --- a/types/applicationinsights-js/applicationinsights-js-tests.ts +++ b/types/applicationinsights-js/applicationinsights-js-tests.ts @@ -47,7 +47,8 @@ appInsights = { startTrackEvent(name: string) { return null; }, stopTrackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, trackEvent(name: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }) { return null; }, - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number) { return null; }, + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, + resultCode: number, properties?: { [name: string]: string }, measurements?: { [name: string]: number }) { return null; }, trackException(exception: Error, handledAt?: string, properties?: { [name: string]: string; }, measurements?: { [name: string]: number; }, severityLevel?: AI.SeverityLevel) { return null; }, trackMetric(name: string, average: number, sampleCount?: number, min?: number, max?: number, properties?: { [name: string]: string; }) { return null; }, trackTrace(message: string, properties?: { [name: string]: string; }, severityLevel?: AI.SeverityLevel) { return null; }, @@ -86,7 +87,7 @@ appInsights.trackTrace("message", null); appInsights.trackTrace("message", { a: '1', b: '2' }, AI.SeverityLevel.Error); // trackDependency -appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null); +appInsights.trackDependency("id", "POST", "http://example.com/test/abc", "/test/abc", null, true, null, {prop1: 'abc'}, {meas1: 4.5}); // flush appInsights.flush(); diff --git a/types/applicationinsights-js/index.d.ts b/types/applicationinsights-js/index.d.ts index 5fbbc3a0f5..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. */ @@ -734,8 +736,11 @@ declare module Microsoft.ApplicationInsights { * @param totalTime total request time * @param success indicates if the request was sessessful * @param resultCode response code returned by the dependency request + * @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. */ - trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number): any; + trackDependency(id: string, method: string, absoluteUrl: string, pathName: string, totalTime: number, success: boolean, resultCode: number, + properties?: { [name: string]: string }, measurements?: { [name: string]: number }): any; /** * Log an exception you have caught. * @param exception An Error from a catch clause, or the string error message. diff --git a/types/arangodb/arangodb-tests.ts b/types/arangodb/arangodb-tests.ts index e049a2374d..c2ade4d0bb 100644 --- a/types/arangodb/arangodb-tests.ts +++ b/types/arangodb/arangodb-tests.ts @@ -16,6 +16,9 @@ coll.save({ username: "user" }); const doc = coll.any(); console.log(doc.username); +const coll2 = db._collection(coll.name()); +console.log(coll2 === coll); + const users = coll as ArangoDB.Collection; const admin = users.firstExample({ username: "admin" })!; users.update(admin, { password: md5("hunter2") }); diff --git a/types/arangodb/index.d.ts b/types/arangodb/index.d.ts index 32ad04210b..c5e83a1cfc 100644 --- a/types/arangodb/index.d.ts +++ b/types/arangodb/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/arangodb/arangodb // Definitions by: Alan Plum // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 /// @@ -619,6 +619,7 @@ declare namespace ArangoDB { interface Collection { // Collection + name(): string; checksum( withRevisions?: boolean, withData?: boolean @@ -1440,6 +1441,72 @@ declare module "@arangodb/foxx/router" { export = createRouter; } +declare module "@arangodb/foxx/queues" { + interface QueueItem { + name: string; + mount: string; + backOff?: ((failureCount: number) => number) | number; + maxFailures?: number; + schema?: Foxx.Schema; + preprocess?: (data: any) => any; + } + + interface Script { + name: string; + mount: string; + } + + type JobCallback = (result: any, jobData: any, job: ArangoDB.Document) => void; + + interface Job { + status: string; + queue: string; + type: Script; + failures: object[]; + runs: number; + data: any; + created: number; + modified: number; + delayUntil: number; + maxFailures: number; + repeatDelay: number; + repeatTimes: number; + repeatUntil: number; + success?: string; + failure?: string; + runFailures: number; + abort(): void; + } + + interface JobOptions { + success?: JobCallback; + failure?: JobCallback; + delayUntil?: number | Date; + backOff?: ((failureCount: number) => number) | number; + maxFailures?: number; + repeatTimes?: number; + repeatUntil?: number | Date; + repeatDelay?: number; + } + + interface Queue { + push(item: QueueItem, data: any, opts?: JobOptions): void; + get(jobId: string): ArangoDB.Document; + delete(jobId: string): boolean; + pending(script?: Script): string[]; + progress(script?: Script): string[]; + complete(script?: Script): string[]; + failed(script?: Script): string[]; + all(script?: Script): string[]; + } + + function createQueue(name: string, maxWorkers?: number): Queue; + function deleteQueue(name: string): boolean; + function get(name: string): Queue; + + export { createQueue as create, deleteQueue as delete, get, JobOptions, Job, Queue, QueueItem, Script, }; +} + declare module "@arangodb/foxx/graphql" { import { formatError, GraphQLSchema } from "graphql"; type GraphQLModule = object; @@ -1698,7 +1765,7 @@ declare module "@arangodb/crypto" { key: string | null, token: string, noVerify?: boolean - ): string | null; + ): object | null; function md5(message: string): string; function sha1(message: string): string; function sha224(message: string): string; diff --git a/types/arangodb/tsconfig.json b/types/arangodb/tsconfig.json index f778fd7c47..d30610b604 100644 --- a/types/arangodb/tsconfig.json +++ b/types/arangodb/tsconfig.json @@ -1,7 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": ["es6", "esnext.asynciterable"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/types/array.prototype.flatmap/array.prototype.flatmap-tests.ts b/types/array.prototype.flatmap/array.prototype.flatmap-tests.ts new file mode 100644 index 0000000000..5236a352ca --- /dev/null +++ b/types/array.prototype.flatmap/array.prototype.flatmap-tests.ts @@ -0,0 +1,47 @@ +import flatMap = require("array.prototype.flatmap"); +import "array.prototype.flatmap/auto"; +import flatMapImpl = require("array.prototype.flatmap/implementation"); +import getPolyfill = require("array.prototype.flatmap/polyfill"); +import shim = require("array.prototype.flatmap/shim"); + +// infers type of the output array from the return type of the callback +flatMap(["foo"], word => word.split("")); // $ExpectType string[] +flatMapImpl(["foo"], word => word.split("")); // $ExpectType string[] +["foo"].flatMap(word => word.split("")); // $ExpectType string[] + +// infers the type of the value argument to the callback +flatMap([1, 2], word => word.split("")); // $ExpectError +flatMapImpl([1, 2], word => word.split("")); // $ExpectError +[1, 2].flatMap(word => word.split("")); // $ExpectError + +// the callback must return an array +flatMap([1, 2], word => word); // $ExpectError +flatMapImpl([1, 2], word => word); // $ExpectError +[1, 2].flatMap(word => word); // $ExpectError + +// the callback accepts an index argument +flatMap(["foo"], (_, index) => [index]); // $ExpectType number[] +flatMapImpl(["foo"], (_, index) => [index]); // $ExpectType number[] +["foo"].flatMap((_, index) => [index]); // $ExpectType number[] + +// the callback accepts an argument that refers to the original array +flatMap(["foo"], (_, __, input) => input); // $ExpectType string[] +flatMapImpl(["foo"], (_, __, input) => input); // $ExpectType string[] +["foo"].flatMap((_, __, input) => input); // $ExpectType string[] + +// the third argument is used as the calling context for the callback +flatMap(["foo"], function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[] +flatMapImpl(["foo"], function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[] +["foo"].flatMap(function() { return this.foo; }, { foo: [1, 2] }); // $ExpectType number[] + +// assumes that value of `this` in callback is `undefined` by default (this is +// accurate in strict mode) +flatMap([1], function() { return [this]; }); // $ExpectType undefined[] +flatMapImpl([1], function() { return [this]; }); // $ExpectType undefined[] +[1].flatMap(function() { return [this]; }); // $ExpectType undefined[] + +// `getPolyfill` returns a flatMap implementation +getPolyfill()(["foo"], word => word.split("")); // $ExpectType string[] + +// `shim` installs a flatMap implementation in `Array` prototype and returns it +shim()(["foo"], word => word.split("")); // $ExpectType string[] diff --git a/types/array.prototype.flatmap/auto.d.ts b/types/array.prototype.flatmap/auto.d.ts new file mode 100644 index 0000000000..43177fb3ad --- /dev/null +++ b/types/array.prototype.flatmap/auto.d.ts @@ -0,0 +1,6 @@ +interface Array { + flatMap( + fn: (this: R, x: T, index: number, array: this) => U[], + thisArg?: R + ): U[]; +} diff --git a/types/array.prototype.flatmap/implementation.d.ts b/types/array.prototype.flatmap/implementation.d.ts new file mode 100644 index 0000000000..80ad9f39d0 --- /dev/null +++ b/types/array.prototype.flatmap/implementation.d.ts @@ -0,0 +1,7 @@ +// This is the same type as the callable signature in `FlatMap` in `index.d.ts`. +declare function flatMap( + xs: ReadonlyArray, + fn: (this: T, x: A, index: number, array: A[]) => B[], + thisArg?: T +): B[]; +export = flatMap; diff --git a/types/array.prototype.flatmap/index.d.ts b/types/array.prototype.flatmap/index.d.ts new file mode 100644 index 0000000000..6bcc29f8b5 --- /dev/null +++ b/types/array.prototype.flatmap/index.d.ts @@ -0,0 +1,21 @@ +// Type definitions for array.prototype.flatmap 1.2 +// Project: https://github.com/es-shims/Array.prototype.flatMap#readme +// Definitions by: Jesse Hallett +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import flatMapImpl = require("./implementation"); + +interface FlatMap { + ( + xs: ReadonlyArray, + fn: (this: T, x: A, index: number, array: A[]) => B[], + thisArg?: T + ): B[]; + getPolyfill(): typeof flatMapImpl; + implementation: typeof flatMapImpl; + shim(): typeof flatMapImpl; +} + +declare const flatMap: FlatMap; +export = flatMap; diff --git a/types/array.prototype.flatmap/polyfill.d.ts b/types/array.prototype.flatmap/polyfill.d.ts new file mode 100644 index 0000000000..ad228b4065 --- /dev/null +++ b/types/array.prototype.flatmap/polyfill.d.ts @@ -0,0 +1,4 @@ +import flatMap = require("./implementation"); + +declare function getPolyfill(): typeof flatMap; +export = getPolyfill; diff --git a/types/array.prototype.flatmap/shim.d.ts b/types/array.prototype.flatmap/shim.d.ts new file mode 100644 index 0000000000..9f75c3a88a --- /dev/null +++ b/types/array.prototype.flatmap/shim.d.ts @@ -0,0 +1,4 @@ +import flatMap = require("./implementation"); + +declare function shim(): typeof flatMap; +export = shim; diff --git a/types/array.prototype.flatmap/tsconfig.json b/types/array.prototype.flatmap/tsconfig.json new file mode 100644 index 0000000000..8a046f1837 --- /dev/null +++ b/types/array.prototype.flatmap/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "array.prototype.flatmap-tests.ts", + "auto.d.ts", + "implementation.d.ts", + "index.d.ts", + "polyfill.d.ts", + "shim.d.ts" + ] +} diff --git a/types/fast-diff/tslint.json b/types/array.prototype.flatmap/tslint.json similarity index 100% rename from types/fast-diff/tslint.json rename to types/array.prototype.flatmap/tslint.json diff --git a/types/ascii-art/ascii-art-tests.ts b/types/ascii-art/ascii-art-tests.ts new file mode 100644 index 0000000000..d5a2d567f8 --- /dev/null +++ b/types/ascii-art/ascii-art-tests.ts @@ -0,0 +1,193 @@ +import art from 'ascii-art'; + +art.font('test', 'doom').toPromise(); + +art.font('my text', 'Doom', (rendered: string) => { + rendered.big(); +}); + +art.font('my text', 'Doom', '', (rendered) => { + rendered.big(); +}); + +art.artwork({ + artwork: 'textfiles.com/art/st-char.asc' +}).lines(31, 45, (rendered: string) => { + // cleanup non-unix terminators + rendered = rendered.replace(/\r/g, ''); + art.image({ + filepath : '~/Images/earth_in_space.jpg', + alphabet : 'ultra-wide' + }).overlay(rendered, { + x: 0, + y: -1, + style: 'red+blink', + transparent: '&' + }, (_final: any) => {}); +}); + +art.font('Ghost Wire BBS', 'Doom', (logo) => { + art.font('No place like home', 'rusted', (subtext) => { + art.table({ + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + data: [ + {name: art.style('current users', 'red'), value: '203'}, + {name: 'operator', value: 'vince.vega'}, + {name: 'dial-in', value: '(917)555-4202'}, + ] + }).lines(2, (table: any) => { + art.image({ + filepath : '~/Images/starburst_red.jpg', + alphabet : 'ultra-wide' + }).lines(2, 30).overlay(logo, { + x: 0, + y: 0, + style: 'blue', + }).overlay(subtext, { + x: 19, + y: 8, + style: 'yellow', + }).overlay(table, { + x: -1, + y: -1, + style: 'green', + }, (_final: any) => { + }); + }); + }); +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.table({ + data: [ + {text: ' .\'ANDRE. '}, + {text: ' ..THE.GIANT\'. '}, + {text: '.With.Bobby."The.Brain"'}, + {text: '.Heenan.'} + ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ' +}).lines(2, (table: any) => { + art.strings([ + 'ANDRE', + 'the', + 'GIANT', + 'POSSE', + '7\'4"', + '520 LB' + ], 'rusted', (andre: any, the: any, giant: any, posse: any, height: any, weight: any) => { + art.strings([ 'has', 'a'], 'twopoint', (has: any, a: any) => { + art.image({ + filepath : '/Images/andre_has_a_posse.jpeg', + alphabet : 'ultra-wide' + }).overlay(andre, { + x: 8, y: 4, + style: 'white' + }).overlay(the, { + x: 10, y: 7, + style: 'white', + transparent : true + }).overlay(giant, { + x: 8, y: 10, + style: 'white', + transparent : true + }).overlay(has, { + x: 10, y: 14, + style: 'white' + }).overlay(a, { + x: 13, y: 17, + style: 'white' + }).overlay(posse, { + x: 5, y: 20, + style: 'bright_black', + transparent: true + }).overlay(height, { + x: 59, y: 3, + style: 'bright_black', + transparent: true + }).overlay(weight, { + x: 59, y: 8, + style: 'bright_black', + transparent: true + }).overlay(table, { + x: 6, y: -6, + style: 'bright_black', + transparent: true + }, (_final: any) => { + }); + }); + }); +}); + +art.Figlet.fontPath = 'Fonts'; + +const image = new art.Image({ + filepath: '~/Images/metropolis.jpg', + alphabet: 'variant4' +}); +image.write((_err: any, _rendered: string) => { +}); + +art.font('Prompt', 'Basic', 'red').font('v1', 'Doom', 'magenta', (_rendered) => { +}); + +art.image({ + width : 40, + filepath : '/Images/initech.png', + alphabet : 'wide' +}).font('INITECH', 'Doom', 'cyan', (_ascii) => { +}); + +art.style('my text', 'red+underline'); + +art.table({ + width : 80, + data : [ /* ... */ ], + verticalBar : ' ', + horizontalBar : ' ', + intersection : ' ', + columns : [ + { + value : 'Product', + style : 'black+gray_bg' + }, { + value : 'Maker', + style : 'white' + }, { + value : 'Location', + style : 'white' + } + ] +}, (_rendered) => { + // use rendered text +}); + +art.table({ + width : 80, + data : [ /* ... */ ], + bars : { + ul_corner: '┏', + ur_corner: '┓', + lr_corner: '┛', + ll_corner: '┗', + bottom_t: '┻', + top_t: '┳', + right_t: '┫', + left_t: '┣', + intersection: '╋', + vertical: '┃', + horizontal: '━', + }, + borderColor : 'bright_white', +}, (_rendered) => { + // use rendered text +}); diff --git a/types/ascii-art/index.d.ts b/types/ascii-art/index.d.ts new file mode 100644 index 0000000000..3a753a183b --- /dev/null +++ b/types/ascii-art/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for ascii-art 1.4 +// Project: https://github.com/khrome/ascii-art +// Definitions by: Lukas Elmer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export type StyleType = (text: string, style?: string, close?: boolean) => Art; +export type FontType = ((text: string, font?: string, styleOrCallback?: string | Cb, callback?: Cb) => Art); +export type ImageType = (options: object, callback?: Cb) => Art; +export type TableType = (options: object, callback?: Cb) => Art; +export type ArtworkType = (options: object, callback?: Cb) => Art; +export type LinesType = (...options: any[]) => Art; +export type OverlayType = (...options: any[]) => Art; +export type JoinType = (...options: any[]) => Art; +export type StringsType = (...options: any[]) => Art; + +export const style: StyleType; +export const font: FontType; +export const image: ImageType; +export const table: TableType; +export const artwork: ArtworkType; +export const lines: LinesType; +export const overlay: OverlayType; +export const join: JoinType; +export const strings: StringsType; +export const Figlet: any; +export const Image: any; + +export interface Art { + style: StyleType; + font: FontType; + image: ImageType; + table: TableType; + artwork: ArtworkType; + lines: LinesType; + overlay: OverlayType; + join: JoinType; + working: boolean; + + toPromise: (() => Promise); +} + +export type Cb = (result: string) => void; diff --git a/types/ascii-art/tsconfig.json b/types/ascii-art/tsconfig.json new file mode 100644 index 0000000000..1f9759cc1f --- /dev/null +++ b/types/ascii-art/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "allowSyntheticDefaultImports": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "ascii-art-tests.ts" + ] +} diff --git a/types/ascii-art/tslint.json b/types/ascii-art/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/ascii-art/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/ascii2mathml/index.d.ts b/types/ascii2mathml/index.d.ts index dcb9f7bb98..0ff3b1d10e 100644 --- a/types/ascii2mathml/index.d.ts +++ b/types/ascii2mathml/index.d.ts @@ -7,29 +7,31 @@ export = A2MML; declare var A2MML: ascii2mathml; -interface Options { - decimalMark?: string; - colSep?: string; - rowSep?: string; - display?: 'inline' | 'block'; - dir?: 'ltr' | 'rtl'; - bare?: boolean; - standalone?: boolean; - annotate?: boolean; -} - interface ascii2mathml { /** * Generates a function with default options set to convert * ASCIIMath expression to MathML markup. * @param options Options */ - (options: Options): ascii2mathml; + (options: A2MML.Options): ascii2mathml; /** * Converts ASCIIMath expression to MathML markup. * @param asciimath ASCIIMath expression * @param options Options */ - (asciimath: string, options?: Options): string; + (asciimath: string, options?: A2MML.Options): string; +} + +declare namespace A2MML { + interface Options { + decimalMark?: string; + colSep?: string; + rowSep?: string; + display?: 'inline' | 'block'; + dir?: 'ltr' | 'rtl'; + bare?: boolean; + standalone?: boolean; + annotate?: boolean; + } } 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/astring/index.d.ts b/types/astring/index.d.ts new file mode 100644 index 0000000000..c2768e7d5f --- /dev/null +++ b/types/astring/index.d.ts @@ -0,0 +1,50 @@ +// Type definitions for astring 1.3 +// Project: https://github.com/davidbonnet/astring +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as ESTree from 'estree'; +import 'node'; +import { Stream } from 'stream'; + +export interface Options { + /** string to use for indentation (defaults to " ") */ + indent?: string; + /** string to use for line endings (defaults to "\n") */ + lineEnd?: string; + /** indent level to start from (defaults to 0) */ + startingIndentLevel?: number; + /** generate comments if true (defaults to false) */ + comments?: boolean; + /** custom code generator (defaults to astring.baseGenerator) */ + generator?: object; + /** source map generator (defaults to null), see https://github.com/mozilla/source-map#sourcemapgenerator */ + sourceMap?: any; +} + +/** Returns a string representing the rendered code of the provided AST `node`. However, if an `output` stream is provided in the options, it writes to that stream and returns it. */ +export function generate(node: ESTree.Node, options?: Options): string; +/** Returns a string representing the rendered code of the provided AST `node`. However, if an `output` stream is provided in the options, it writes to that stream and returns it. */ +export function generate(node: ESTree.Node, options: Options & { + /** output stream to write the rendered code to (defaults to null) */ + output: Stream; +}): Stream; + +/** + * A code generator consists of a mapping of node names and functions that take two arguments: `node` and `state`. + * The `node` points to the node from which to generate the code and the `state` exposes the `write` method that takes generated code strings. + */ +export type Generator = { [key in ESTree.Node["type"]]: (node: Extract, state: { write(s: string): void }) => void }; + +/** Base generator that can be used to extend Astring. See https://github.com/davidbonnet/astring#extending */ +export const baseGenerator: Generator; + +declare global { + interface astring { + generate: typeof generate; + /** Base generator that can be used to extend Astring. See https://github.com/davidbonnet/astring#extending */ + baseGenerator: Generator; + } + const astring: astring; +} diff --git a/types/astring/test/astring-global.test.ts b/types/astring/test/astring-global.test.ts new file mode 100644 index 0000000000..c756c9c60e --- /dev/null +++ b/types/astring/test/astring-global.test.ts @@ -0,0 +1,5 @@ +// global scope function +astring.generate(null); + +// global scope function +astring.baseGenerator.Program(null, { write(s: string) { return; } }); diff --git a/types/astring/test/astring.test.ts b/types/astring/test/astring.test.ts new file mode 100644 index 0000000000..782af01017 --- /dev/null +++ b/types/astring/test/astring.test.ts @@ -0,0 +1,32 @@ +import { baseGenerator, generate } from "astring"; +import { FunctionExpression, MemberExpression, Program } from "estree"; +import { Stream } from "stream"; + +const ast: Program = null; +const functionE: FunctionExpression = null; +const memberE: MemberExpression = null; + +// should accept different nodes +generate(ast); +generate(functionE); +generate(memberE); + +// options without output option should generate string +const string: string = generate(ast, { + comments: true, + generator: baseGenerator, + indent: "\t", + lineEnd: "\n", + startingIndentLevel: 42, + sourceMap: null +}); + +// options with output option should return Stream +const stream: Stream = generate(ast, { + output: new Stream() +}); + +// Generator should map node types to functions whose first parameter is same node type +baseGenerator.Program(ast, { write(s: string) { return; } }); +baseGenerator.FunctionExpression(functionE, { write(s: string) { return; } }); +baseGenerator.MemberExpression(memberE, { write(s: string) { return; } }); diff --git a/types/astring/tsconfig.json b/types/astring/tsconfig.json new file mode 100644 index 0000000000..b00d44f643 --- /dev/null +++ b/types/astring/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": false, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "test/astring.test.ts", + "test/astring-global.test.ts" + ] +} \ No newline at end of file diff --git a/types/astring/tslint.json b/types/astring/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/astring/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/async/index.d.ts b/types/async/index.d.ts index 961dd73ebb..e6cfd3bcaa 100644 --- a/types/async/index.d.ts +++ b/types/async/index.d.ts @@ -2,34 +2,34 @@ // Project: https://github.com/caolan/async // Definitions by: Boris Yankov , Arseniy Maximov , Joe Herman , Angus Fenying , Pascal Martin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 export as namespace async; export interface Dictionary { [key: string]: T; } export type IterableCollection = T[] | IterableIterator | Dictionary -export interface ErrorCallback { (err?: T): void; } -export interface AsyncBooleanResultCallback { (err?: E, truthValue?: boolean): void; } -export interface AsyncResultCallback { (err?: E, result?: T): void; } -export interface AsyncResultArrayCallback { (err?: E, results?: Array): void; } -export interface AsyncResultObjectCallback { (err: E | undefined, results: Dictionary): void; } +export interface ErrorCallback { (err?: E | null): void; } +export interface AsyncBooleanResultCallback { (err?: E | null, truthValue?: boolean): void; } +export interface AsyncResultCallback { (err?: E | null, result?: T): void; } +export interface AsyncResultArrayCallback { (err?: E | null, results?: Array): void; } +export interface AsyncResultObjectCallback { (err: E | undefined, results: Dictionary): void; } -export interface AsyncFunction { (callback: (err?: E, result?: T) => void): void; } -export interface AsyncFunctionEx { (callback: (err?: E, ...results: T[]) => void): void; } -export interface AsyncIterator { (item: T, callback: ErrorCallback): void; } -export interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } -export interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } -export interface AsyncMemoIterator { (memo: R | undefined, item: T, callback: AsyncResultCallback): void; } -export interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } +export interface AsyncFunction { (callback: (err?: E | null, result?: T) => void): void; } +export interface AsyncFunctionEx { (callback: (err?: E | null, ...results: T[]) => void): void; } +export interface AsyncIterator { (item: T, callback: ErrorCallback): void; } +export interface AsyncForEachOfIterator { (item: T, key: number|string, callback: ErrorCallback): void; } +export interface AsyncResultIterator { (item: T, callback: AsyncResultCallback): void; } +export interface AsyncMemoIterator { (memo: R | undefined, item: T, callback: AsyncResultCallback): void; } +export interface AsyncBooleanIterator { (item: T, callback: AsyncBooleanResultCallback): void; } -export interface AsyncWorker { (task: T, callback: ErrorCallback): void; } -export interface AsyncVoidFunction { (callback: ErrorCallback): void; } +export interface AsyncWorker { (task: T, callback: ErrorCallback): void; } +export interface AsyncVoidFunction { (callback: ErrorCallback): void; } export type AsyncAutoTasks, E> = { [K in keyof R]: AsyncAutoTask } export type AsyncAutoTask, E> = AsyncAutoTaskFunctionWithoutDependencies | (keyof R | AsyncAutoTaskFunction)[]; -export interface AsyncAutoTaskFunctionWithoutDependencies { (cb: AsyncResultCallback | ErrorCallback): void; } -export interface AsyncAutoTaskFunction, E> { (results: R, cb: AsyncResultCallback | ErrorCallback): void; } +export interface AsyncAutoTaskFunctionWithoutDependencies { (cb: AsyncResultCallback | ErrorCallback): void; } +export interface AsyncAutoTaskFunction, E = Error> { (results: R, cb: AsyncResultCallback | ErrorCallback): void; } export interface AsyncQueue { length(): number; @@ -37,9 +37,8 @@ export interface AsyncQueue { running(): number; idle(): boolean; concurrency: number; - push(task: T | T[], callback?: ErrorCallback): void; - push(task: T, callback?: AsyncResultCallback): void; - unshift(task: T | T[], callback?: ErrorCallback): void; + push(task: T | T[], callback?: AsyncResultCallback): void; + unshift(task: T | T[], callback?: ErrorCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -61,7 +60,7 @@ export interface AsyncPriorityQueue { concurrency: number; started: boolean; paused: boolean; - push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; + push(task: T | T[], priority: number, callback?: AsyncResultArrayCallback): void; saturated: () => any; empty: () => any; drain: () => any; @@ -94,112 +93,113 @@ export interface AsyncCargo { } // Collections -export function each(arr: IterableCollection, iterator: AsyncIterator, callback?: ErrorCallback): void; +export function each(arr: IterableCollection, iterator: AsyncIterator, callback?: ErrorCallback): void; export const eachSeries: typeof each; -export function eachLimit(arr: IterableCollection, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; +export function eachLimit(arr: IterableCollection, limit: number, iterator: AsyncIterator, callback?: ErrorCallback): void; export const forEach: typeof each; export const forEachSeries: typeof each; export const forEachLimit: typeof eachLimit; -export function forEachOf(obj: IterableCollection, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; +export function forEachOf(obj: IterableCollection, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; export const forEachOfSeries: typeof forEachOf; -export function forEachOfLimit(obj: IterableCollection, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; +export function forEachOfLimit(obj: IterableCollection, limit: number, iterator: AsyncForEachOfIterator, callback?: ErrorCallback): void; export const eachOf: typeof forEachOf; export const eachOfSeries: typeof forEachOf; export const eachOfLimit: typeof forEachOfLimit; -export function map(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function map(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function map(arr: Dictionary, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; export const mapSeries: typeof map; -export function mapLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; -export function mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; +export function mapLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function mapValuesLimit(obj: Dictionary, limit: number, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; +export function mapValues(obj: Dictionary, iteratee: (value: T, key: string, callback: AsyncResultCallback) => void, callback: AsyncResultObjectCallback): void; export const mapValuesSeries: typeof mapValues; -export function filter(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; +export function filter(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; export const filterSeries: typeof filter; -export function filterLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; +export function filterLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultArrayCallback): void; export const select: typeof filter; export const selectSeries: typeof filter; export const selectLimit: typeof filterLimit; export const reject: typeof filter; export const rejectSeries: typeof filter; export const rejectLimit: typeof filterLimit; -export function reduce(arr: T[] | IterableIterator, memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; +export function reduce(arr: T[] | IterableIterator, memo: R, iterator: AsyncMemoIterator, callback?: AsyncResultCallback): void; export const inject: typeof reduce; export const foldl: typeof reduce; export const reduceRight: typeof reduce; export const foldr: typeof reduce; -export function detect(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; +export function detect(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; export const detectSeries: typeof detect; -export function detectLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; +export function detectLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncResultCallback): void; export const find: typeof detect; export const findSeries: typeof detect; export const findLimit: typeof detectLimit; -export function sortBy(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function some(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; +export function sortBy(arr: T[] | IterableIterator, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function some(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; export const someSeries: typeof some; -export function someLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; +export function someLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; export const any: typeof some; export const anySeries: typeof someSeries; export const anyLimit: typeof someLimit; -export function every(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; +export function every(arr: IterableCollection, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; export const everySeries: typeof every; -export function everyLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; +export function everyLimit(arr: IterableCollection, limit: number, iterator: AsyncBooleanIterator, callback?: AsyncBooleanResultCallback): void; export const all: typeof every; export const allSeries: typeof every; export const allLimit: typeof everyLimit; -export function concat(arr: IterableCollection, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; -export function concatLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function concat(arr: IterableCollection, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; +export function concatLimit(arr: IterableCollection, limit: number, iterator: AsyncResultIterator, callback?: AsyncResultArrayCallback): void; export const concatSeries: typeof concat; // Control Flow -export function series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; -export function series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; -export function parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; -export function parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; -export function parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; -export function parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; -export function whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doWhilst(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; -export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doUntil(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; -export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; -export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; -export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; -export function waterfall(tasks: Function[], callback?: AsyncResultCallback): void; +export function series(tasks: AsyncFunction[], callback?: AsyncResultArrayCallback): void; +export function series(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; +export function parallel(tasks: Array>, callback?: AsyncResultArrayCallback): void; +export function parallel(tasks: Dictionary>, callback?: AsyncResultObjectCallback): void; +export function parallelLimit(tasks: Array>, limit: number, callback?: AsyncResultArrayCallback): void; +export function parallelLimit(tasks: Dictionary>, limit: number, callback?: AsyncResultObjectCallback): void; +export function whilst(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; +export function doWhilst(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; +export function until(test: () => boolean, fn: AsyncVoidFunction, callback: ErrorCallback): void; +export function doUntil(fn: AsyncFunctionEx, test: (...results: T[]) => boolean, callback: ErrorCallback): void; +export function during(test: (testCallback : AsyncBooleanResultCallback) => void, fn: AsyncVoidFunction, callback: ErrorCallback): void; +export function doDuring(fn: AsyncVoidFunction, test: (testCallback: AsyncBooleanResultCallback) => void, callback: ErrorCallback): void; +export function forever(next: (next : ErrorCallback) => void, errBack: ErrorCallback) : void; +export function waterfall(tasks: Function[], callback?: AsyncResultCallback): void; export function compose(...fns: Function[]): Function; export function seq(...fns: Function[]): Function; export function applyEach(fns: Function[], ...argsAndCallback: any[]): void; // applyEach(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. export function applyEachSeries(fns: Function[], ...argsAndCallback: any[]): void; // applyEachSeries(fns, args..., callback). TS does not support ... for a middle argument. Callback is optional. -export function queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; -export function queue(worker: AsyncResultIterator, concurrency?: number): AsyncQueue; -export function priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; -export function cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; -export function auto, E>(tasks: AsyncAutoTasks, concurrency?: number, callback?: AsyncResultCallback): void; -export function autoInject(tasks: any, callback?: AsyncResultCallback): void; -export function retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; -export function retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; -export function retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; -export function apply(fn: Function, ...args: any[]): AsyncFunction; +export function queue(worker: AsyncWorker, concurrency?: number): AsyncQueue; +export function queue(worker: AsyncResultIterator, concurrency?: number): AsyncQueue; +export function priorityQueue(worker: AsyncWorker, concurrency: number): AsyncPriorityQueue; +export function cargo(worker : (tasks: any[], callback : ErrorCallback) => void, payload? : number) : AsyncCargo; +export function auto, E = Error>(tasks: AsyncAutoTasks, concurrency?: number, callback?: AsyncResultCallback): void; +export function auto, E = Error>(tasks: AsyncAutoTasks, callback?: AsyncResultCallback): void; +export function autoInject(tasks: any, callback?: AsyncResultCallback): void; +export function retry(opts: number, task: (callback : AsyncResultCallback, results: any) => void, callback: AsyncResultCallback): void; +export function retry(opts: { times: number, interval: number|((retryCount: number) => number) }, task: (callback: AsyncResultCallback, results : any) => void, callback: AsyncResultCallback): void; +export function retryable(opts: number | {times: number, interval: number}, task: AsyncFunction): AsyncFunction; +export function apply(fn: Function, ...args: any[]): AsyncFunction; export function nextTick(callback: Function, ...args: any[]): void; export const setImmediate: typeof nextTick; -export function reflect(fn: AsyncFunction) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void; -export function reflectAll(tasks: AsyncFunction[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[]; +export function reflect(fn: AsyncFunction) : (callback: (err: null, result: {error?: E, value?: T}) => void) => void; +export function reflectAll(tasks: AsyncFunction[]): ((callback: (err: null, result: {error?: E, value?: T}) => void) => void)[]; -export function timeout(fn: AsyncFunction, milliseconds: number, info?: any): AsyncFunction; -export function timeout(fn: AsyncResultIterator, milliseconds: number, info?: any): AsyncResultIterator; +export function timeout(fn: AsyncFunction, milliseconds: number, info?: any): AsyncFunction; +export function timeout(fn: AsyncResultIterator, milliseconds: number, info?: any): AsyncResultIterator; export function times (n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; -export function timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; -export function timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; +export function timesSeries(n: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; +export function timesLimit(n: number, limit: number, iterator: AsyncResultIterator, callback: AsyncResultArrayCallback): void; -export function transform(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; -export function transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; +export function transform(arr: T[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; +export function transform(arr: T[], acc: R[], iteratee: (acc: R[], item: T, key: number, callback: (error?: E) => void) => void, callback?: AsyncResultArrayCallback): void; -export function transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; -export function transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; +export function transform(arr: {[key: string] : T}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; +export function transform(arr: {[key: string] : T}, acc: {[key: string] : R}, iteratee: (acc: {[key: string] : R}, item: T, key: string, callback: (error?: E) => void) => void, callback?: AsyncResultObjectCallback): void; -export function race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; +export function race(tasks: (AsyncFunction)[], callback: AsyncResultCallback) : void; // Utils export function memoize(fn: Function, hasher?: Function): Function; diff --git a/types/async/test/index.ts b/types/async/test/index.ts index 3c6c2f5dfe..574a5ed8b9 100644 --- a/types/async/test/index.ts +++ b/types/async/test/index.ts @@ -114,7 +114,7 @@ async.series([ ], function (err, results) { }); -async.series([ +async.series([ function (callback) { callback(undefined, 'one'); }, @@ -138,7 +138,7 @@ async.series({ }, function (err, results) { }); -async.series({ +async.series({ one: function (callback) { setTimeout(function () { callback(undefined, 1); @@ -178,7 +178,7 @@ async.parallel([ ], function (err, results) { }); -async.parallel([ +async.parallel([ function (callback) { setTimeout(function () { callback(undefined, 'one'); @@ -207,7 +207,7 @@ async.parallel({ }, function (err, results) { }); -async.parallel({ +async.parallel({ one: function (callback) { setTimeout(function () { callback(undefined, 1); @@ -273,7 +273,7 @@ async.waterfall([ ], function (err, result) { }); -var q = async.queue(function (task: any, callback: (err?:Error,msg?:string) => void) { +var q = async.queue(function (task: any, callback: (err?:Error,msg?:string) => void) { console.log('hello ' + task.name); callback(undefined,'a message.'); }, 2); @@ -293,7 +293,7 @@ q.push([{ name: 'baz' }, { name: 'bay' }, { name: 'bax' }], function (err) { console.log('finished processing bar'); }); -q.push({name: 'foo'}, function (err,msg) { +q.push({name: 'foo'}, function (err, msg) { console.log('foo finished with a message "'+ msg! + '"'); }); @@ -330,7 +330,7 @@ q.resume(); q.kill(); // tests for strongly typed tasks -var q2 = async.queue(function (task: string, callback: () => void) { +var q2 = async.queue(function (task: string, callback: () => void) { console.log('Task: ' + task); callback(); }, 1); @@ -356,7 +356,7 @@ q2.unshift(['task3', 'task4', 'task5'], function (error) { }); -var aq = async.queue(function (level: number, callback: (error?: Error, newLevel?: number) => void) { +var aq = async.queue(function (level: number, callback: (error?: Error, newLevel?: number) => void) { console.log('hello ' + level); callback(undefined, level+1); }); @@ -387,14 +387,47 @@ cargo.push({ name: 'baz' }, function (err: Error) { var filename = ''; async.auto({ - get_data: function (callback: any) { }, - make_folder: function (callback: any) { }, + get_data: function (callback: AsyncResultCallback) { }, + make_folder: function (callback: AsyncResultCallback) { }, //arrays with different types are not accepted by TypeScript. - write_file: ['get_data', 'make_folder', function (callback: any) { + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { callback(null, filename); - }], + } as any], //arrays with different types are not accepted by TypeScript. - email_link: ['write_file', function (callback: any, results: any) { }] + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] +}); + +async.auto({ + get_data: function (callback: AsyncResultCallback) { }, + make_folder: function (callback: AsyncResultCallback) { }, + //arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + callback(null, filename); + } as any], + //arrays with different types are not accepted by TypeScript. + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] +}, function (err, results) { + console.log('finished auto'); +}); + +interface A { + get_data: any; + make_folder: any; + write_file: any; + email_link: any; +} + +async.auto({ + get_data: function (callback: AsyncResultCallback) { }, + make_folder: function (callback: AsyncResultCallback) { }, + //arrays with different types are not accepted by TypeScript. + write_file: ['get_data', 'make_folder', function (callback: AsyncResultCallback) { + callback(null, filename); + } as any], + //arrays with different types are not accepted by TypeScript. + email_link: ['write_file', function (callback: AsyncResultCallback, results: any) { } as any] +}, 1, function (err, results) { + console.log('finished auto'); }); async.retry(3, function (callback, results) { }, function (err, result) { }); @@ -459,10 +492,10 @@ async.dir(function (name: string, callback: any) { // each -async.each({ +async.each({ "a": 1, "b": 2 -}, function(val: number, next: ErrorCallback): void { +}, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -478,10 +511,10 @@ async.each({ }); -async.eachSeries({ +async.eachSeries({ "a": 1, "b": 2 -}, function(val: number, next: ErrorCallback): void { +}, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -497,14 +530,14 @@ async.eachSeries({ }); -async.eachLimit({ +async.eachLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, next: ErrorCallback): void { +}, 2, function(val: number, next: ErrorCallback): void { setTimeout(function(): void { @@ -522,10 +555,10 @@ async.eachLimit({ // forEachOf/eachOf -async.eachOf({ +async.eachOf({ "a": 1, "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +}, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -541,10 +574,10 @@ async.eachOf({ }); -async.forEachOfSeries({ +async.forEachOfSeries({ "a": 1, "b": 2 -}, function(val: number, key: string, next: ErrorCallback): void { +}, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -560,14 +593,14 @@ async.forEachOfSeries({ }); -async.forEachOfLimit({ +async.forEachOfLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, key: string, next: ErrorCallback): void { +}, 2, function(val: number, key: string, next: ErrorCallback): void { setTimeout(function(): void { @@ -585,11 +618,11 @@ async.forEachOfLimit({ // map -async.map({ +async.map({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +}, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -605,11 +638,11 @@ async.map({ }); -async.mapSeries({ +async.mapSeries({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncResultCallback): void { +}, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -625,14 +658,14 @@ async.mapSeries({ }); -async.mapLimit({ +async.mapLimit({ "a": 1, "b": 2, "c": 3, "d": 4, "e": 5, "f": 6 -}, 2, function(val: number, next: AsyncResultCallback): void { +}, 2, function(val: number, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -650,11 +683,11 @@ async.mapLimit({ // mapValues -async.mapValues({ +async.mapValues({ "a": 1, "b": 2, "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +}, function(val: number, key: string, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -670,11 +703,11 @@ async.mapValues({ }); -async.mapValuesSeries({ +async.mapValuesSeries({ "a": 1, "b": 2, "c": 3 -}, function(val: number, key: string, next: AsyncResultCallback): void { +}, function(val: number, key: string, next: AsyncResultCallback): void { setTimeout(function(): void { @@ -692,11 +725,11 @@ async.mapValuesSeries({ // filter/select/reject -async.filter({ +async.filter({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +}, function(val: number, next: AsyncBooleanResultCallback): void { setTimeout(function(): void { @@ -712,11 +745,11 @@ async.filter({ }); -async.reject({ +async.reject({ "a": 1, "b": 2, "c": 3 -}, function(val: number, next: AsyncBooleanResultCallback): void { +}, function(val: number, next: AsyncBooleanResultCallback): void { setTimeout(function(): void { @@ -734,11 +767,11 @@ async.reject({ // concat -async.concat({ +async.concat({ "a": "1", "b": "2", "c": "3" -}, function(item: string, next: AsyncResultCallback): void { +}, function(item: string, next: AsyncResultCallback): void { console.log(`async.concat: ${item}`); @@ -752,11 +785,11 @@ async.concat({ // detect/find -async.detect({ +async.detect({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.detect/find: ${item}`); @@ -777,11 +810,11 @@ async.detect({ // every/all -async.every({ +async.every({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.every/all: ${item}`); @@ -795,11 +828,11 @@ async.every({ // some/any -async.some({ +async.some({ "a": 1, "b": 2, "c": 3 -}, function(item: number, next: AsyncBooleanResultCallback): void { +}, function(item: number, next: AsyncBooleanResultCallback): void { console.log(`async.some/any: ${item}`); diff --git a/types/asynciterator/tslint.json b/types/asynciterator/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/asynciterator/tslint.json +++ b/types/asynciterator/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} 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/gitlab/tslint.json b/types/atlaskit__tree/tslint.json similarity index 100% rename from types/gitlab/tslint.json rename to types/atlaskit__tree/tslint.json diff --git a/types/atlassian-crowd-client/lib/models/session.d.ts b/types/atlassian-crowd-client/lib/models/session.d.ts index 2ef16a0814..2369f976bc 100644 --- a/types/atlassian-crowd-client/lib/models/session.d.ts +++ b/types/atlassian-crowd-client/lib/models/session.d.ts @@ -3,7 +3,7 @@ declare class Session { readonly token: string; readonly createdAt: Date; readonly expiresAt: Date; - + constructor(token: string, createdAt: Date, expiresAt: Date); toCrowd(): SessionObj; static fromCrowd(obj: SessionObj): Session; diff --git a/types/atlassian-crowd-client/settings.d.ts b/types/atlassian-crowd-client/settings.d.ts index 755c26038a..4c56a85e06 100644 --- a/types/atlassian-crowd-client/settings.d.ts +++ b/types/atlassian-crowd-client/settings.d.ts @@ -3,7 +3,7 @@ export interface Settings { readonly application: { readonly name: string; readonly password: string; - } + }; readonly nesting?: boolean; readonly sessionTimeout?: number; readonly debug?: boolean; diff --git a/types/atom/atom-tests.ts b/types/atom/atom-tests.ts index 9d01e194a9..9a04b9c7b6 100644 --- a/types/atom/atom-tests.ts +++ b/types/atom/atom-tests.ts @@ -557,8 +557,8 @@ function testDesializerManager() { } function isStorableClass(o: object): o is StorableClass { - if (typeof o === "object" && ( o).name && - ( o).name === "test") { + if (typeof o === "object" && (o as StorableClass).name && + (o as StorableClass).name === "test") { return true; } else { return false; @@ -1748,6 +1748,14 @@ function testProject() { // Accessing the git repository repositories = project.getRepositories(); + subscription = project.observeRepositories(gitRepo => { + const repo: Atom.GitRepository = gitRepo; + }); + + subscription = project.onDidAddRepository(gitRepo => { + const repo: Atom.GitRepository = gitRepo; + }); + async function getDirectoryRepo() { const potentialRepo = await project.repositoryForDirectory(dir); if (potentialRepo) repository = potentialRepo; @@ -3041,6 +3049,25 @@ function testTextEditor() { editor.addGutter({ name: "Test", priority: 42 }); editor.addGutter({ name: "Test", visible: true }); editor.addGutter({ name: "Test", priority: 42, visible: true }); + editor.addGutter({ name: "Test", type: 'decorated' }); + editor.addGutter({ name: "Test", type: 'line-number' }); + editor.addGutter({ name: "Test", class: 'someClass' }); + editor.addGutter({ name: "Test", labelFn(lineData) { + num = lineData.bufferRow; + num = lineData.screenRow; + num = lineData.maxDigits; + bool = lineData.foldable; + bool = lineData.softWrapped; + return 'label'; + }}); + editor.addGutter({ name: "Test", onMouseDown(lineData) { + num = lineData.bufferRow; + num = lineData.screenRow; + } }); + editor.addGutter({ name: "Test", onMouseMove(lineData) { + num = lineData.bufferRow; + num = lineData.screenRow; + } }); gutters = editor.getGutters(); diff --git a/types/atom/index.d.ts b/types/atom/index.d.ts index c403569ab2..d77663c460 100644 --- a/types/atom/index.d.ts +++ b/types/atom/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Atom 1.28 +// Type definitions for Atom 1.31 // Project: https://github.com/atom/atom // Definitions by: GlenCFL // smhxx @@ -7,7 +7,7 @@ // TypeScript Version: 2.3 // NOTE: only those classes exported within this file should be retain that status below. -// https://github.com/atom/atom/blob/v1.28.0/exports/atom.js +// https://github.com/atom/atom/blob/v1.31.0/exports/atom.js /// @@ -2415,11 +2415,7 @@ export class TextEditor { // Gutters /** Add a custom Gutter. */ - addGutter(options: { - name: string, - priority?: number, - visible?: boolean, - }): Gutter; + addGutter(options: GutterOptions): Gutter; /** Get this editor's gutters. */ getGutters(): Gutter[]; @@ -2459,6 +2455,74 @@ export class TextEditor { tokenForBufferPosition(pos: PointCompatible): {value: string, scopes: string[]}; } +export interface GutterOptions { + /** (required) A unique String to identify this gutter. */ + name: string; + + /** + * A Number that determines stacking order between gutters. + * Lower priority items are forced closer to the edges of the window. (default: -100) + */ + priority?: number; + + /** + * Boolean specifying whether the gutter is visible initially after being created. + * (default: true) + */ + visible?: boolean; + + /** + * String specifying the type of gutter to create. + * 'decorated' gutters are useful as a destination for decorations created with + * Gutter::decorateMarker. + * 'line-number' gutters. + */ + type?: 'decorated' | 'line-number'; + + /** String added to the CSS classnames of the gutter's root DOM element. */ + class?: string; + + /** + * Function called by a 'line-number' gutter to generate the label for each + * line number element. Should return a String that will be used to label the + * corresponding line. + */ + labelFn?: (lineData: LineDataExtended) => string; + + /** + * Function to be called when a mousedown event is received by a line-number + * element within this type: 'line-number' Gutter. If unspecified, the default + * behavior is to select the clicked buffer row. + */ + onMouseDown?: (lineData: LineData) => void; + + /** + * Function to be called when a mousemove event occurs on a line-number + * element within within this type: 'line-number' Gutter. + */ + onMouseMove?: (lineData: LineData) => void; +} + +export interface LineData { + /** Number indicating the zero-indexed buffer index of a line. */ + bufferRow: number; + + /** Number indicating the zero-indexed screen index. */ + screenRow: number; +} + +/** Object containing information about each line to label. */ +export interface LineDataExtended extends LineData { + /** Boolean that is true if a fold may be created here. */ + foldable: boolean; + + /** Boolean if this screen row is the soft-wrapped continuation of the same buffer row. */ + softWrapped: boolean; + + /** Number the maximum number of digits necessary to represent any known screen row. */ + maxDigits: number; +} + export interface PixelPosition { left: number; top: number; @@ -4497,6 +4561,12 @@ export interface Project { */ getRepositories(): GitRepository[]; + /** Invoke the given callback with all current and future repositories in the project. */ + observeRepositories(callback: (repository: GitRepository) => void): Disposable; + + /** Invoke the given callback when a repository is added to the project. */ + onDidAddRepository(callback: (repository: GitRepository) => void): Disposable; + /** Get the repository for a given directory asynchronously. */ repositoryForDirectory(directory: Directory): Promise; @@ -5844,7 +5914,7 @@ export interface TextEditorObservedEvent { // information under certain contexts. // NOTE: the config schema with these defaults can be found here: -// https://github.com/atom/atom/blob/v1.28.0/src/config-schema.js +// https://github.com/atom/atom/blob/v1.31.0/src/config-schema.js /** * Allows you to strongly type Atom configuration variables. Additional key:value * pairings merged into this interface will result in configuration values under diff --git a/types/atom/tslint.json b/types/atom/tslint.json index 4c3e6e9036..3811d3257c 100644 --- a/types/atom/tslint.json +++ b/types/atom/tslint.json @@ -4,6 +4,9 @@ "await-promise": [true, "CancellablePromise"], "indent": [true, "spaces", 4], "max-line-length": [true, 100], - "no-any": true + "no-any": true, + + // TODOs + "no-declare-current-package": false } } diff --git a/types/auth-header/auth-header-tests.ts b/types/auth-header/auth-header-tests.ts new file mode 100644 index 0000000000..e8b510531c --- /dev/null +++ b/types/auth-header/auth-header-tests.ts @@ -0,0 +1,6 @@ +import * as auth from 'auth-header'; + +const basic: string = auth.format('Basic'); +const basic2: string = auth.format({scheme: 'Basic'}); + +const parsed: {scheme: string, token: null | string | string[]} = auth.parse(''); diff --git a/types/auth-header/index.d.ts b/types/auth-header/index.d.ts new file mode 100644 index 0000000000..fab462be9e --- /dev/null +++ b/types/auth-header/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for auth-header 1.0 +// Project: https://github.com/izaakschroeder/auth-header +// Definitions by: ForbesLindesay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +type Params = + | Array<[string, string | ReadonlyArray]> + | {[key: string]: string | ReadonlyArray}; +export {Params}; + +export interface TokenOptions { + scheme: string; + token?: string; + params?: Params; +} + +export interface Token { + scheme: string; + params: {[key: string]: string | string[]}; + token: null | string | string[]; +} + +export function format(token: TokenOptions): string; +export function format(scheme: string, token?: string, params?: Params): string; + +export function parse(header: string): Token; diff --git a/types/auth-header/tsconfig.json b/types/auth-header/tsconfig.json new file mode 100644 index 0000000000..58c6fad6d7 --- /dev/null +++ b/types/auth-header/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", + "auth-header-tests.ts" + ] +} diff --git a/types/react-i18next/tslint.json b/types/auth-header/tslint.json similarity index 100% rename from types/react-i18next/tslint.json rename to types/auth-header/tslint.json diff --git a/types/auth0-js/auth0-js-tests.ts b/types/auth0-js/auth0-js-tests.ts index f13599ebae..6d21de4ed3 100644 --- a/types/auth0-js/auth0-js-tests.ts +++ b/types/auth0-js/auth0-js-tests.ts @@ -11,6 +11,7 @@ webAuth.authorize({ responseType: 'token', redirectUri: 'https://example.com/auth/callback', language: 'en', + login_hint: "email@email.com", prompt: 'login', }); diff --git a/types/auth0-js/index.d.ts b/types/auth0-js/index.d.ts index 033a4bcbde..7ca266e6ce 100644 --- a/types/auth0-js/index.d.ts +++ b/types/auth0-js/index.d.ts @@ -4,6 +4,7 @@ // Matt Durrant // Peter Blazejewicz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 export as namespace auth0; @@ -172,7 +173,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(callback: Auth0Callback): void; + parseHash(callback: Auth0Callback): void; /** * Parse the url hash and extract the returned tokens depending on the transaction. @@ -183,7 +184,7 @@ export class WebAuth { * * @param callback: any(err, token_payload) */ - parseHash(options: ParseHashOptions, callback: Auth0Callback): void; + parseHash(options: ParseHashOptions, callback: Auth0Callback): void; /** * Decodes the id_token and verifies the nonce. @@ -482,7 +483,7 @@ export class CrossOriginAuthentication { callback(): void; } -export type Auth0Callback = (error: null | Auth0Error, result: T) => void; +export type Auth0Callback = (error: null | E, result: T) => void; export interface TokenProvider { enableCache?: boolean; @@ -522,18 +523,51 @@ export interface PasswordlessAuthOptions { email: string; } +/** + * These are error codes defined by the auth0-js lib. + */ +export type LibErrorCodes = 'timeout' | 'request_error' | 'invalid_token'; + +/** + * The user was not logged in at Auth0, so silent authentication is not possible. + */ +export type LoginRequiredErrorCode = 'login_required'; + +/** + * The user was logged in at Auth0 and has authorized the application, but needs to + * be redirected elsewhere before authentication can be completed; for example, when + * using a redirect rule. + */ +export type InteractionRequiredErrorCode = 'interaction_required'; + +/** + * The user was logged in at Auth0, but needs to give consent to authorize the application. + */ +export type ConsentRequiredErrorCode = 'consent_required'; + +/** + * These are error codes defined by the OpenID Connect specification. + */ +export type SpecErrorCodes = + LoginRequiredErrorCode | + InteractionRequiredErrorCode | + ConsentRequiredErrorCode | + 'account_selection_required' | + 'invalid_request_uri' | + 'invalid_request_object' | + 'request_not_supported' | + 'request_uri_not_supported' | + 'registration_not_supported'; + export interface Auth0Error { - error?: any; - errorDescription?: string; - code?: string; - description?: string; - name?: string; - policy?: string; - original?: any; - statusCode?: number; - statusText?: string; + error: LibErrorCodes | SpecErrorCodes | string; + errorDescription: string; } +export type Auth0ParseHashError = Auth0Error & { + state?: string; +}; + /** * The contents of the authResult object returned by {@link WebAuth#parseHash } */ @@ -761,6 +795,7 @@ export interface AuthorizeOptions { scope?: string; audience?: string; language?: string; + login_hint?: string; prompt?: string; mode?: "login" | "signUp"; } diff --git a/types/auth0-lock/auth0-lock-tests.ts b/types/auth0-lock/auth0-lock-tests.ts index 4b5c60e716..6e23e81d5e 100644 --- a/types/auth0-lock/auth0-lock-tests.ts +++ b/types/auth0-lock/auth0-lock-tests.ts @@ -140,12 +140,17 @@ new Auth0Lock(CLIENT_ID, DOMAIN, otherOptions); const multiVariantOptions : Auth0LockConstructorOptions = { container: "myContainer", closable: false, + language: "en", languageDictionary: { signUpTerms: "I agree to the terms of service ...", title: "My Company", }, + autoclose: true, autofocus: false, + allowAutocomplete: false, + scrollGlobalMessagesIntoView: false, allowShowPassword: true, + allowPasswordAutocomplete: false, }; new Auth0Lock(CLIENT_ID, DOMAIN, multiVariantOptions); diff --git a/types/auth0-lock/index.d.ts b/types/auth0-lock/index.d.ts index 622ac3d36c..2916ec58c8 100644 --- a/types/auth0-lock/index.d.ts +++ b/types/auth0-lock/index.d.ts @@ -5,6 +5,7 @@ // Larry Faudree // Will Caulfield // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 /// @@ -98,6 +99,7 @@ interface Auth0LockAuthOptions { params?: Auth0LockAuthParamsOptions; redirect?: boolean; redirectUrl?: string; + responseMode?: string; responseType?: string; sso?: boolean; audience?: string; @@ -113,8 +115,10 @@ interface Auth0LockPopupOptions { interface Auth0LockConstructorOptions { additionalSignUpFields?: Auth0LockAdditionalSignUpField[]; allowedConnections?: string[]; + allowAutocomplete?: boolean; allowForgotPassword?: boolean; allowLogin?: boolean; + allowPasswordAutocomplete?: boolean; allowSignUp?: boolean; allowShowPassword?: boolean; assetsUrl?: string; @@ -129,6 +133,7 @@ interface Auth0LockConstructorOptions { defaultADUsernameFromEmailPrefix?: string; defaultDatabaseConnection?: string; defaultEnterpriseConnection?: string; + flashMessage?: Auth0LockFlashMessageOptions; forgotPasswordLink?: string; hashCleanup?: boolean; initialScreen?: "login" | "signUp" | "forgotPassword"; @@ -142,6 +147,7 @@ interface Auth0LockConstructorOptions { popupOptions?: Auth0LockPopupOptions; prefill?: { email?: string, username?: string}; rememberLastLogin?: boolean; + scrollGlobalMessagesIntoView?: boolean; signupLink?: string; socialButtonStyle?: "big" | "small"; theme?: Auth0LockThemeOptions; diff --git a/types/auth0/auth0-tests.ts b/types/auth0/auth0-tests.ts index f4251364d2..60bbf86823 100644 --- a/types/auth0/auth0-tests.ts +++ b/types/auth0/auth0-tests.ts @@ -203,3 +203,26 @@ management.linkUsers('primaryId', { user_id: 'secondaryId' }) management.linkUsers('primaryId', { user_id: 'secondaryId' }, (err: Error, result: any) => {}); +// Get all clients (with promise) +management.getClients() + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +//Get all clients (with callback) +management.getClients((err: Error, clients: auth0.Client[]) => {}); + +// Get all clients with params (with promise) +management.getClients({fields:['name','client_metadata'], include_fields:true}) + .then((clients: auth0.Client[]) => { + console.log(clients); + }) + .catch((err) => { + // Handle the error + }); + +// Get all cients with params (with callback) +management.getClients({fields:['name','client_metadata'], include_fields:true}, (err:Error, clients:auth0.Client[]) => {}); diff --git a/types/auth0/index.d.ts b/types/auth0/index.d.ts index e03ad5aa06..39d9d36fd7 100644 --- a/types/auth0/index.d.ts +++ b/types/auth0/index.d.ts @@ -1,11 +1,9 @@ // Type definitions for auth0 2.9.2 // Project: https://github.com/auth0/node-auth0 -// Definitions by: Wilson Hobbs , Seth Westphal , Amiram Korach +// Definitions by: Seth Westphal // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as Promise from 'bluebird'; - export interface ManagementClientOptions { token?: string; domain: string; @@ -588,7 +586,19 @@ export interface ImpersonateSettingOptions { clientId?: string; } - +export type ClientAppType = 'native' | 'spa' | 'regular_web' | 'non_interactive' | 'rms' | 'box' | + 'cloudbees' | 'concur' | 'dropbox' | 'mscrm' | 'echosign' | 'egnyte' | 'newrelic' | 'office365' | + 'salesforce' | 'sentry' | 'sharepoint' | 'slack' | 'springcm' | 'zendesk' | 'zoom'; +export interface GetClientsOptions { + fields?: string[]; + include_fields?: boolean; + page?: number; + per_page?: number; + include_totals?: boolean; + is_global?: boolean; + is_first_party?: boolean; + app_type?: ClientAppType[]; +} export class AuthenticationClient { @@ -661,8 +671,9 @@ export class ManagementClient { // Clients - getClients(): Promise; - getClients(cb: (err: Error, clients: Client[]) => void): void; + getClients(params?: GetClientsOptions): Promise; + getClients(cb: (err: Error, clients: Client[]) => void ): void; + getClients(params: GetClientsOptions, cb: (err: Error, clients: Client[]) => void ): void; getClient(params: ClientParams): Promise; getClient(params: ClientParams, cb: (err: Error, client: Client) => void): void; diff --git a/types/autobahn/index.d.ts b/types/autobahn/index.d.ts index 59bb2c404d..c62f6115af 100644 --- a/types/autobahn/index.d.ts +++ b/types/autobahn/index.d.ts @@ -190,6 +190,8 @@ declare namespace autobahn { export class Connection { constructor(options?: IConnectionOptions); + isOpen: boolean; + open(): void; close(reason?: string, message?: string): void; diff --git a/types/autoprefixer/autoprefixer-tests.ts b/types/autoprefixer/autoprefixer-tests.ts index 47ef1cbc08..21940ac008 100644 --- a/types/autoprefixer/autoprefixer-tests.ts +++ b/types/autoprefixer/autoprefixer-tests.ts @@ -1,17 +1,17 @@ -import * as autopref from 'autoprefixer'; +import autoprefixer = require("autoprefixer"); +import { Transformer } from 'postcss'; -const ap: autopref.Transformer = autopref({ - browsers: ['> 5%', 'last 2 versions'], - env: '', - cascade: true, - add: true, - remove: true, - supports: true, - flexbox: true, - grid: true, - stats: {}, +const ap1: Transformer = autoprefixer(); + +const ap2: Transformer = autoprefixer({ + browsers: [], + env: "test", + cascade: false, + add: false, + remove: false, + supports: false, + flexbox: false, + grid: false, + stats: {}, + ignoreUnknownVersions: false, }); -const ap2: autopref.Transformer = autopref({ - flexbox: 'no-2009', -}); -const info: string = ap.info(); diff --git a/types/autoprefixer/index.d.ts b/types/autoprefixer/index.d.ts index 1957632053..faf11371db 100644 --- a/types/autoprefixer/index.d.ts +++ b/types/autoprefixer/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for autoprefixer 6.7 +// Type definitions for autoprefixer 9.1 // Project: https://github.com/postcss/autoprefixer -// Definitions by: Armando Meziat +// Definitions by: Armando Meziat , murt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 -import { Plugin, Transformer as PostcssTransformer } from 'postcss'; +import { Plugin } from "postcss"; declare namespace autoprefixer { interface Options { @@ -16,15 +17,10 @@ declare namespace autoprefixer { flexbox?: boolean | 'no-2009'; grid?: boolean; stats?: any; + ignoreUnknownVersions?: boolean; } - interface Transformer extends PostcssTransformer { - info(): string; - } - - interface Autoprefixer extends Plugin { - (opts?: Options): Transformer; - } + type Autoprefixer = Plugin; } declare const autoprefixer: autoprefixer.Autoprefixer; diff --git a/types/autoprefixer/package.json b/types/autoprefixer/package.json index c4c2b4c357..1e1a719545 100644 --- a/types/autoprefixer/package.json +++ b/types/autoprefixer/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "postcss": "^5.2.15" + "postcss": "7.x.x" } } diff --git a/types/await-timeout/await-timeout-tests.ts b/types/await-timeout/await-timeout-tests.ts new file mode 100644 index 0000000000..96dcdefdee --- /dev/null +++ b/types/await-timeout/await-timeout-tests.ts @@ -0,0 +1,131 @@ +import Timeout from "await-timeout"; + +/** + * This test is just a TS-friendly version of the await-timeout README: + * https://github.com/vitalets/await-timeout/blob/v0.3.0/README.md + * + * How to generate this file: + * 1. Paste the source code of README.md + * 2. Replace every code fence with async () => {} + * 3. Comment out all other lines + * 4. Add and remove import statements and repeated statements + * 5. Declare required globals + */ + +// -- Globals -- +declare const fetch: (url: string) => Promise; +declare const console: any; +declare const MyTimeoutError: any; + +// --- README --- + +// ## Usage +// 1. Just wait some time: +async () => { + // wait 1000 ms and resolve + await Timeout.set(1000); + + // wait 1000 ms and reject with 'Error' + await Timeout.set(1000, 'Error'); +}; + +// 2. Use `Timeout` instance inside `try...finally` block to make proper cleanup: +async () => { + const timer = new Timeout(); + try { + await Promise.race([ + fetch('https://example.com'), + timer.set(1000) + .then(() => Promise.reject('Timeout')) + ]); + } finally { + timer.clear(); + } +}; + +// ## API +// ### new Timeout() +// Constructs new timeout instance. It does not start timer but creates variable for timer manipulation. +async () => { + const timer = new Timeout(); +}; +// > Note : having separate variable is useful for clearing timeout in `finally` block + +// ### .set(ms, [message]) ⇒ `Promise` +// Starts new timer like `setTimeout()` and returns promise. The promise will be resolved after `ms` milliseconds: +async () => { + const timer = new Timeout(); + timer.set(1000) + .then(() => console.log('1000 ms passed.')); +}; + +// If you need to reject after timeout: +async () => { + const timer = new Timeout(); + timer.set(1000) + .then(() => {throw new Error('Timeout'); }); +}; + +// Or reject with custom error: +async () => { + const timer = new Timeout(); + timer.set(1000) + .then(() => {throw new MyTimeoutError(); }); +}; +// The second parameter `message` is just convenient way to reject with `new Error(message)`: +async () => { + const timer = new Timeout(); + timer.set(1000, 'Timeout'); + // is equivalent to + timer.set(1000).then(() => {throw new Error('Timeout'); }); +}; + +// If you need to just wait some time - use static version of `.set()` : +async () => { + Timeout.set(1000).then(/*...*/); +}; + +// ### .wrap(promise, ms, [message]) ⇒ `Promise` +// Wraps existing promise with timeout: +// * promise automatically rejected after timeout +// * timeout automatically cleared if promise fulfills first +async () => { + const promise = fetch('https://example.com'); + + const timeoutedPromise = Timeout.wrap(promise, 1000, 'Timeout'); +}; +// Actually it is a shortcut for : +async () => { + const promise = fetch('https://example.com'); + + const timer = new Timeout(); + try { + const timeoutedPromise = await Promise.race([ + promise, + timer.set(1000, 'Timeout') + ]); + } finally { + timer.clear(); + } +}; + +// ### .clear() +// Clears existing timeout like `clearTimeout()`. +async () => { + const timer = new Timeout(); + timer.set(1000) + .then(() => console.log('This will never be called, because timeout is cleared on the next line')); + timer.clear(); +}; + +// With [ES7 async / await ] `.clear()` can be used in `finally` block: +async () => { + async function foo() { + const timer = new Timeout(); + try { + // some async stuff + } finally { + timer.clear(); + } + } +}; diff --git a/types/await-timeout/index.d.ts b/types/await-timeout/index.d.ts new file mode 100644 index 0000000000..ce202c6024 --- /dev/null +++ b/types/await-timeout/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for await-timeout 0.3 +// Project: https://github.com/vitalets/await-timeout +// Definitions by: Sean Zhu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export default Timeout; + +declare class Timeout { + static set(delay: number): Promise; + static set(delay: number, message: string): Promise; + + static wrap(promise: Promise, delay: number, error?: string): Promise; + + set(delay: number): Promise; + set(delay: number, message: string): Promise; + clear(): void; +} diff --git a/types/await-timeout/tsconfig.json b/types/await-timeout/tsconfig.json new file mode 100644 index 0000000000..2ecb27e688 --- /dev/null +++ b/types/await-timeout/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", + "await-timeout-tests.ts" + ] +} diff --git a/types/react-i18next/v4/tslint.json b/types/await-timeout/tslint.json similarity index 100% rename from types/react-i18next/v4/tslint.json rename to types/await-timeout/tslint.json diff --git a/types/aws-lambda/aws-lambda-tests.ts b/types/aws-lambda/aws-lambda-tests.ts index 5fa225eafd..00b71132e9 100644 --- a/types/aws-lambda/aws-lambda-tests.ts +++ b/types/aws-lambda/aws-lambda-tests.ts @@ -8,6 +8,7 @@ declare let error: Error; declare let bool: boolean; declare let boolOrUndefined: boolean | undefined; declare let apiGwEvtReqCtx: AWSLambda.APIGatewayEventRequestContext; +declare let apiGwEvtReqCtxOpt: AWSLambda.APIGatewayEventRequestContext | null | undefined; declare let apiGwEvt: AWSLambda.APIGatewayEvent; declare let customAuthorizerEvt: AWSLambda.CustomAuthorizerEvent; declare let clientCtx: AWSLambda.ClientContext; @@ -102,11 +103,13 @@ str = apiGwEvtReqCtx.resourcePath; /* API Gateway Event */ strOrNull = apiGwEvt.body; str = apiGwEvt.headers["example"]; +str = apiGwEvt.multiValueHeaders["example"][0]; str = apiGwEvt.httpMethod; bool = apiGwEvt.isBase64Encoded; str = apiGwEvt.path; str = apiGwEvt.pathParameters!["example"]; str = apiGwEvt.queryStringParameters!["example"]; +str = apiGwEvt.multiValueQueryStringParameters!["example"][0]; str = apiGwEvt.stageVariables!["example"]; apiGwEvtReqCtx = apiGwEvt.requestContext; str = apiGwEvt.resource; @@ -115,10 +118,12 @@ str = apiGwEvt.resource; str = customAuthorizerEvt.type; str = customAuthorizerEvt.methodArn; strOrUndefined = customAuthorizerEvt.authorizationToken; -str = apiGwEvt.pathParameters!["example"]; -str = apiGwEvt.queryStringParameters!["example"]; -str = apiGwEvt.stageVariables!["example"]; -apiGwEvtReqCtx = apiGwEvt.requestContext; +str = customAuthorizerEvt.headers!["example"]; +str = customAuthorizerEvt.multiValueHeaders!["example"][0]; +str = customAuthorizerEvt.pathParameters!["example"]; +str = customAuthorizerEvt.queryStringParameters!["example"]; +str = customAuthorizerEvt.multiValueQueryStringParameters!["example"][0]; +apiGwEvtReqCtxOpt = customAuthorizerEvt.requestContext; /* DynamoDB Stream Event */ const dynamoDBStreamEvent: AWSLambda.DynamoDBStreamEvent = { @@ -245,6 +250,9 @@ num = proxyResult.statusCode; proxyResult.headers!["example"] = str; proxyResult.headers!["example"] = bool; proxyResult.headers!["example"] = num; +proxyResult.multiValueHeaders!["example"][0] = str; +proxyResult.multiValueHeaders!["example"][0] = bool; +proxyResult.multiValueHeaders!["example"][0] = num; boolOrUndefined = proxyResult.isBase64Encoded; str = proxyResult.body; @@ -383,6 +391,8 @@ cognitoUserPoolEvent.triggerSource === "TokenGeneration_Authentication"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_NewPasswordChallenge"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_AuthenticateDevice"; cognitoUserPoolEvent.triggerSource === "TokenGeneration_RefreshTokens"; +cognitoUserPoolEvent.triggerSource === "UserMigration_Authentication"; +cognitoUserPoolEvent.triggerSource === "UserMigration_ForgotPassword"; str = cognitoUserPoolEvent.region; str = cognitoUserPoolEvent.userPoolId; strOrUndefined = cognitoUserPoolEvent.userName; @@ -404,6 +414,7 @@ strOrUndefined = cognitoUserPoolEvent.request.session![0].challengeMetadata; strOrUndefined = cognitoUserPoolEvent.request.challengeName; str = cognitoUserPoolEvent.request.privateChallengeParameters!["answer"]; str = cognitoUserPoolEvent.request.challengeAnswer!; +strOrUndefined = cognitoUserPoolEvent.request.password; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; strOrUndefined = cognitoUserPoolEvent.response.smsMessage; strOrUndefined = cognitoUserPoolEvent.response.emailMessage; @@ -415,6 +426,14 @@ str = cognitoUserPoolEvent.response.publicChallengeParameters!["captchaUrl"]; str = cognitoUserPoolEvent.response.privateChallengeParameters!["answer"]; strOrUndefined = cognitoUserPoolEvent.response.challengeMetadata; boolOrUndefined = cognitoUserPoolEvent.response.answerCorrect; +str = cognitoUserPoolEvent.response.userAttributes!["username"]; +cognitoUserPoolEvent.response.finalUserStatus === "CONFIRMED"; +cognitoUserPoolEvent.response.finalUserStatus === "RESET_REQUIRED"; +cognitoUserPoolEvent.response.messageAction === "SUPPRESS"; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["EMAIL"]; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["SMS"]; +cognitoUserPoolEvent.response.desiredDeliveryMediums === ["SMS", "EMAIL"]; +boolOrUndefined = cognitoUserPoolEvent.response.forceAliasCreation; // CloudFormation Custom Resource switch (cloudformationCustomResourceEvent.RequestType) { diff --git a/types/aws-lambda/index.d.ts b/types/aws-lambda/index.d.ts index cce721e68c..d9d22f8c65 100644 --- a/types/aws-lambda/index.d.ts +++ b/types/aws-lambda/index.d.ts @@ -22,6 +22,8 @@ // Louis Larry // Daniel Papukchiev // Oliver Hookins +// Trevor Leach +// James Gregory // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -58,11 +60,13 @@ export interface APIGatewayEventRequestContext { export interface APIGatewayProxyEvent { body: string | null; headers: { [name: string]: string }; + multiValueHeaders: { [name: string]: string[] }; httpMethod: string; isBase64Encoded: boolean; path: string; pathParameters: { [name: string]: string } | null; queryStringParameters: { [name: string]: string } | null; + multiValueQueryStringParameters: { [name: string]: string[] } | null; stageVariables: { [name: string]: string } | null; requestContext: APIGatewayEventRequestContext; resource: string; @@ -75,8 +79,10 @@ export interface CustomAuthorizerEvent { methodArn: string; authorizationToken?: string; headers?: { [name: string]: string }; + multiValueHeaders?: { [name: string]: string[] }; pathParameters?: { [name: string]: string } | null; queryStringParameters?: { [name: string]: string } | null; + multiValueQueryStringParameters?: { [name: string]: string[] } | null; requestContext?: APIGatewayEventRequestContext; } @@ -234,7 +240,9 @@ export interface CognitoUserPoolTriggerEvent { | "TokenGeneration_Authentication" | "TokenGeneration_NewPasswordChallenge" | "TokenGeneration_AuthenticateDevice" - | "TokenGeneration_RefreshTokens"; + | "TokenGeneration_RefreshTokens" + | "UserMigration_Authentication" + | "UserMigration_ForgotPassword"; region: string; userPoolId: string; userName?: string; @@ -256,6 +264,7 @@ export interface CognitoUserPoolTriggerEvent { challengeName?: string; privateChallengeParameters?: { [key: string]: string }; challengeAnswer?: string; + password?: string; }; response: { autoConfirmUser?: boolean; @@ -269,6 +278,11 @@ export interface CognitoUserPoolTriggerEvent { privateChallengeParameters?: { [key: string]: string }; challengeMetadata?: string; answerCorrect?: boolean; + userAttributes?: { [key: string]: string }; + finalUserStatus?: "CONFIRMED" | "RESET_REQUIRED"; + messageAction?: "SUPPRESS"; + desiredDeliveryMediums?: Array<"EMAIL" | "SMS">; + forceAliasCreation?: boolean; }; } export type CognitoUserPoolEvent = CognitoUserPoolTriggerEvent; @@ -433,6 +447,9 @@ export interface APIGatewayProxyResult { headers?: { [header: string]: boolean | number | string; }; + multiValueHeaders?: { + [header: string]: Array; + }; body: string; isBase64Encoded?: boolean; } diff --git a/types/axe-webdriverjs/tsconfig.json b/types/axe-webdriverjs/tsconfig.json index d8637d03e4..4eaf433c1c 100644 --- a/types/axe-webdriverjs/tsconfig.json +++ b/types/axe-webdriverjs/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/axios-token-interceptor/index.d.ts b/types/axios-token-interceptor/index.d.ts index 85121f8165..a09fb7591b 100644 --- a/types/axios-token-interceptor/index.d.ts +++ b/types/axios-token-interceptor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/sandrinodimattia/axios-token-interceptor#readme // Definitions by: Mike Dodge // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import { AxiosRequestConfig } from 'axios'; diff --git a/types/azure-sb/index.d.ts b/types/azure-sb/index.d.ts index 9f9d07d3dc..bd62e100ab 100644 --- a/types/azure-sb/index.d.ts +++ b/types/azure-sb/index.d.ts @@ -75,7 +75,7 @@ export namespace Azure.ServiceBus { DefaultMessageTimeToLive: string; DuplicateDetectionHistoryTimeWindow: string; EnablePartitioning: boolean; - MaxSizeInMegaBytes: number; + MaxSizeInMegabytes: number; RequiresDuplicateDetection: boolean; } diff --git a/types/babel__core/babel__core-tests.ts b/types/babel__core/babel__core-tests.ts index a873c3392f..ba51ac21be 100644 --- a/types/babel__core/babel__core-tests.ts +++ b/types/babel__core/babel__core-tests.ts @@ -7,15 +7,18 @@ const options: babel.TransformOptions = { babel.transform("code();", options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); const transformSyncResult = babel.transformSync("code();", options); if (transformSyncResult) { const { code, map, ast } = transformSyncResult; + const { body } = ast!.program; } babel.transformFile("filename.js", options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); babel.transformFileSync("filename.js", options)!.code; @@ -25,7 +28,14 @@ const parsedAst = babel.parse(sourceCode, options); babel.transformFromAst(parsedAst!, sourceCode, options, (err, result) => { const { code, map, ast } = result!; + const { body } = ast!.program; }); const transformFromAstSyncResult = babel.transformFromAstSync(parsedAst!, sourceCode, options); const { code, map, ast } = transformFromAstSyncResult!; +const { body } = ast!.program; + +babel.transformFromAstAsync(parsedAst!, sourceCode, options).then(transformFromAstAsyncResult => { + const { code, map, ast } = transformFromAstAsyncResult!; + const { body } = ast!.program; +}); diff --git a/types/babel__core/index.d.ts b/types/babel__core/index.d.ts index 277228341b..eb39d90a58 100644 --- a/types/babel__core/index.d.ts +++ b/types/babel__core/index.d.ts @@ -4,16 +4,16 @@ // Marvin Hagemeister // Melvin Groenhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { GeneratorOptions } from "@babel/generator"; import traverse, { Visitor, NodePath } from "@babel/traverse"; import template from "@babel/template"; import * as t from "@babel/types"; -import { ParseOptions } from "@babel/parser"; +import { ParserOptions } from "@babel/parser"; export { - ParseOptions, + ParserOptions, GeneratorOptions, t as types, template, @@ -217,7 +217,7 @@ export interface TransformOptions { * * Default: `{}` */ - parserOpts?: ParseOptions | null; + parserOpts?: ParserOptions | null; /** * List of plugins to load and use @@ -349,7 +349,7 @@ export function transformFromAstSync(ast: Node, code?: string, opts?: TransformO /** * Given an AST, transform it. */ -export function transformFromAstSync(ast: Node, code?: string, opts?: TransformOptions): Promise; +export function transformFromAstAsync(ast: Node, code?: string, opts?: TransformOptions): Promise; // A babel plugin is a simple function which must return an object matching // the following interface. Babel will throw if it finds unknown properties. @@ -365,7 +365,7 @@ export interface PluginObj { } export interface BabelFileResult { - ast?: Node | null; + ast?: t.File | null; code?: string | null; ignored?: boolean; map?: { diff --git a/types/babel__core/package.json b/types/babel__core/package.json index c2ca8a8f9b..582285d229 100644 --- a/types/babel__core/package.json +++ b/types/babel__core/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0-beta.54" + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" } } diff --git a/types/babel__core/tsconfig.json b/types/babel__core/tsconfig.json index 2f96e019cb..22eb208383 100644 --- a/types/babel__core/tsconfig.json +++ b/types/babel__core/tsconfig.json @@ -22,9 +22,6 @@ "@babel/generator": [ "babel__generator" ], - "@babel/parser": [ - "babel__parser" - ], "@babel/template": [ "babel__template" ], diff --git a/types/babel__generator/babel__generator-tests.ts b/types/babel__generator/babel__generator-tests.ts index 90a668ad55..728638c868 100644 --- a/types/babel__generator/babel__generator-tests.ts +++ b/types/babel__generator/babel__generator-tests.ts @@ -1,9 +1,9 @@ // Example from https://github.com/babel/babel/tree/master/packages/babel-generator import generate from "@babel/generator"; -import { parse } from "@babel/parser"; +import * as t from "@babel/types"; const code = "class Example {}"; -const ast = parse(code); +declare const ast: t.Node; ast.type; ast.loc!.start; diff --git a/types/babel__generator/index.d.ts b/types/babel__generator/index.d.ts index 03fcf2765a..9b6a9fbc1c 100644 --- a/types/babel__generator/index.d.ts +++ b/types/babel__generator/index.d.ts @@ -4,7 +4,7 @@ // Johnny Estilles // Melvin Groenhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import * as t from "@babel/types"; diff --git a/types/babel__generator/package.json b/types/babel__generator/package.json index c2ca8a8f9b..2442a952db 100644 --- a/types/babel__generator/package.json +++ b/types/babel__generator/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0-beta.54" + "@babel/types": "^7.0.0" } } diff --git a/types/babel__generator/tsconfig.json b/types/babel__generator/tsconfig.json index be65e3da1f..01acda5d38 100644 --- a/types/babel__generator/tsconfig.json +++ b/types/babel__generator/tsconfig.json @@ -18,9 +18,6 @@ "paths": { "@babel/generator": [ "babel__generator" - ], - "@babel/parser": [ - "babel__parser" ] } }, diff --git a/types/babel__parser/babel__parser-tests.ts b/types/babel__parser/babel__parser-tests.ts deleted file mode 100644 index 1c9873e5e8..0000000000 --- a/types/babel__parser/babel__parser-tests.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { parse, parseExpression } from "@babel/parser"; - -declare function assert(expr: boolean): void; - -const code = `function square(n) { - return n * n; -}`; - -const node = parse(code); -assert(node.type === "File"); -assert(node.start === 0); -assert(node.end === 38); -assert(!!node.loc && node.loc.start > node.loc.end); - -parse(code, { - sourceType: "module", // default: "script" - plugins: ["jsx"] // default: [] -}); diff --git a/types/babel__parser/index.d.ts b/types/babel__parser/index.d.ts deleted file mode 100644 index bf383ffa0c..0000000000 --- a/types/babel__parser/index.d.ts +++ /dev/null @@ -1,107 +0,0 @@ -// Type definitions for @babel/parser 7.0 -// Project: https://github.com/babel/babel/tree/master/packages/babel-parser -// Definitions by: Troy Gerwien -// Marvin Hagemeister -// Melvin Groenhoff -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { File, Expression } from "@babel/types"; - -export function parse(code: string, opts?: ParseOptions): File; - -export function parseExpression(input: string, options?: ParseOptions): Expression; - -export interface ParseOptions { - /** - * By default, import and export declarations can only appear at a program's top level. - * Setting this option to true allows them anywhere where a statement is allowed. - */ - allowImportExportEverywhere?: boolean; - - /** - * By default, await use is not allowed outside of an async function. Set this to true to accept such code. - */ - allowAwaitOutsideFunction?: boolean; - - /** - * By default, a return statement at the top level raises an error. Set this to true to accept such code. - */ - allowReturnOutsideFunction?: boolean; - - allowSuperOutsideMethod?: boolean; - - /** - * Indicate the mode the code should be parsed in. Can be one of "script", "module", or "unambiguous". - * Defaults to "script". "unambiguous" will make @babel/parser attempt to guess, based on the presence of ES6 import or export - * statements. Files with ES6 imports and exports are considered "module" and are otherwise "script". - */ - sourceType?: "script" | "module" | "unambiguous"; - - /** - * Correlate output AST nodes with their source filename. Useful when - * generating code and source maps from the ASTs of multiple input files. - */ - sourceFilename?: string; - - /** - * By default, the first line of code parsed is treated as line 1. You can provide a line number to alternatively start with. Useful - * for integration with other source tools. - */ - startLine?: number; - - /** - * Array containing the plugins that you want to enable. - */ - plugins?: PluginList; - - strictMode?: boolean; - - /** - * Adds a `ranges` property to each node: `[node.start, node.end]` - */ - ranges?: boolean; - - /** - * Adds all parsed tokens to a `tokens` property on the `File` node - */ - tokens?: boolean; -} - -export type PluginList = Array; - -export type PluginName = - "asyncGenerators" | - "bigInt" | - "classPrivateMethods" | - "classPrivateProperties" | - "classProperties" | - "decorators" | - "doExpressions" | - "dynamicImport" | - "estree" | - "exportDefaultFrom" | - "exportNamespaceFrom" | - "flow" | - "flowComments" | - "functionBind" | - "functionSent" | - "importMeta" | - "jsx" | - "nullishCoalescingOperator" | - "numericSeparator" | - "objectRestSpread" | - "optionalCatchBinding" | - "optionalChaining" | - "pipelineOperator" | - "throwExpressions" | - "typescript"; - -export interface PluginOptions { - decorators?: { - decoratorsBeforeExport?: boolean; - }; - flow?: { - all?: boolean; - }; -} diff --git a/types/babel__template/index.d.ts b/types/babel__template/index.d.ts index 5f3bc18bc3..8750e52d8e 100644 --- a/types/babel__template/index.d.ts +++ b/types/babel__template/index.d.ts @@ -4,12 +4,12 @@ // Marvin Hagemeister // Melvin Groenhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 -import { ParseOptions } from "@babel/parser"; +import { ParserOptions } from "@babel/parser"; import { Expression, File, Program, Statement } from "@babel/types"; -export interface TemplateBuilderOptions extends ParseOptions { +export interface TemplateBuilderOptions extends ParserOptions { /** * A set of placeholder names to automatically accept. Items in this list do not need to match the given placeholder pattern. */ diff --git a/types/babel__template/package.json b/types/babel__template/package.json index c2ca8a8f9b..582285d229 100644 --- a/types/babel__template/package.json +++ b/types/babel__template/package.json @@ -1,6 +1,7 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0-beta.54" + "@babel/parser": "^7.1.0", + "@babel/types": "^7.0.0" } } diff --git a/types/babel__template/tsconfig.json b/types/babel__template/tsconfig.json index 386236c02f..50fce77ad8 100644 --- a/types/babel__template/tsconfig.json +++ b/types/babel__template/tsconfig.json @@ -20,9 +20,6 @@ "@babel/generator": [ "babel__generator" ], - "@babel/parser": [ - "babel__parser" - ], "@babel/template": [ "babel__template" ] diff --git a/types/babel__traverse/babel__traverse-tests.ts b/types/babel__traverse/babel__traverse-tests.ts index 2fc7b07a8a..70f8c5f0b6 100644 --- a/types/babel__traverse/babel__traverse-tests.ts +++ b/types/babel__traverse/babel__traverse-tests.ts @@ -1,14 +1,17 @@ -import { parse } from "@babel/parser"; import traverse, { Visitor } from "@babel/traverse"; import * as t from "@babel/types"; // Examples from: https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md const MyVisitor: Visitor = { Identifier: { - enter() { + enter(path) { + // $ExpectType NodePath + path; console.log("Entered!"); }, - exit() { + exit(path) { + // $ExpectType NodePath + path; console.log("Exited!"); } } @@ -21,11 +24,7 @@ const MyVisitor2: Visitor = { }; // Example from https://github.com/thejameskyle/babel-handbook/blob/master/translations/en/plugin-handbook.md#babel-traverse -const code = `function square(n) { - return n * n; -}`; - -const ast = parse(code); +declare const ast: t.Node; traverse(ast, { enter(path) { @@ -94,7 +93,8 @@ const v1: Visitor = { const id = path.scope.generateUidIdentifierBasedOnNode(path.node.id!); path.remove(); - path.scope.parent.push({ id, init: path.node }); + path.scope.parent.push({ id }); + path.scope.parent.push({ id, init: t.stringLiteral('foo'), kind: "const" }); path.scope.rename("n", "x"); path.scope.rename("n"); @@ -109,7 +109,44 @@ const BindingKindTest: Visitor = { kind === 'const'; kind === 'let'; kind === 'var'; - // The following should fail when uncommented - // kind === 'anythingElse'; + // $ExpectError + kind === 'anythingElse'; }, }; + +interface SomeVisitorState { someState: string; } + +const VisitorStateTest: Visitor = { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + Identifier(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + FunctionDeclaration: { + enter(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + }, + exit(path, state) { + // $ExpectType SomeVisitorState + state; + // $ExpectType SomeVisitorState + this; + } + } +}; diff --git a/types/babel__traverse/index.d.ts b/types/babel__traverse/index.d.ts index 475ca9fb14..89e242129b 100644 --- a/types/babel__traverse/index.d.ts +++ b/types/babel__traverse/index.d.ts @@ -5,7 +5,7 @@ // Ryan Petrich // Melvin Groenhoff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import * as t from "@babel/types"; @@ -90,11 +90,16 @@ export class Scope { removeData(key: string): void; - push(opts: any): void; + push(opts: { + id: t.LVal, + init?: t.Expression, + unique?: boolean, + kind?: "var" | "let" | "const", + }): void; getProgramParent(): Scope; - getFunctionParent(): Scope; + getFunctionParent(): Scope | null; getBlockParent(): Scope; @@ -138,17 +143,17 @@ export class Binding { constantViolations: NodePath[]; } -export type Visitor = VisitNodeObject & { - [P in Node["type"]]?: VisitNode>; +export type Visitor = VisitNodeObject & { + [Type in Node["type"]]?: VisitNode>; }; -export type VisitNode = VisitNodeFunction | VisitNodeObject; +export type VisitNode = VisitNodeFunction | VisitNodeObject; -export type VisitNodeFunction = (this: T, path: NodePath

, state: any) => void; +export type VisitNodeFunction = (this: S, path: NodePath

, state: S) => void; -export interface VisitNodeObject { - enter?(path: NodePath, state: any): void; - exit?(path: NodePath, state: any): void; +export interface VisitNodeObject { + enter?: VisitNodeFunction; + exit?: VisitNodeFunction; } export class NodePath { diff --git a/types/babel__traverse/package.json b/types/babel__traverse/package.json index c2ca8a8f9b..2442a952db 100644 --- a/types/babel__traverse/package.json +++ b/types/babel__traverse/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "@babel/types": "^7.0.0-beta.54" + "@babel/types": "^7.0.0" } } diff --git a/types/babel__traverse/tsconfig.json b/types/babel__traverse/tsconfig.json index 898675d222..b6c30190af 100644 --- a/types/babel__traverse/tsconfig.json +++ b/types/babel__traverse/tsconfig.json @@ -17,9 +17,6 @@ "noEmit": true, "forceConsistentCasingInFileNames": true, "paths": { - "@babel/parser": [ - "babel__parser" - ], "@babel/traverse": [ "babel__traverse" ] diff --git a/types/babylon/index.d.ts b/types/babylon/index.d.ts index 07eb74bb32..b179f6f357 100644 --- a/types/babylon/index.d.ts +++ b/types/babylon/index.d.ts @@ -46,6 +46,7 @@ export type PluginName = 'estree' | 'jsx' | 'flow' | + 'typescript' | 'classConstructorCall' | 'doExpressions' | 'objectRestSpread' | diff --git a/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts b/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts index 072e3c29ce..6c2d852961 100644 --- a/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts +++ b/types/backbone-fetch-cache/backbone-fetch-cache-tests.ts @@ -64,7 +64,7 @@ const modelOpts: Backbone.ModelFetchWithCacheOptions = { context: {}, }; -const hoge = new Backbone.Model; +const hoge = new Backbone.Model() as Backbone.ModelWithCache; hoge.fetch(modelOpts); const collectionOpts: Backbone.CollectionFetchWithCacheOptions = { @@ -76,5 +76,5 @@ const collectionOpts: Backbone.CollectionFetchWithCacheOptions = { prefillSuccess: (self: any) => { }, }; -const fuga = new Backbone.Collection; +const fuga = new Backbone.Collection() as Backbone.CollectionWithCache; fuga.fetch(collectionOpts); diff --git a/types/backbone-relational/index.d.ts b/types/backbone-relational/index.d.ts index a1c8c3eefb..403759ac97 100644 --- a/types/backbone-relational/index.d.ts +++ b/types/backbone-relational/index.d.ts @@ -122,7 +122,19 @@ declare module 'backbone' { } - export class Store extends Events { + export class Store implements Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + initializeRelation(model, relation, options); addModelScope(scope:any):void; diff --git a/types/backbone.layoutmanager/tslint.json b/types/backbone.layoutmanager/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/backbone.layoutmanager/tslint.json +++ b/types/backbone.layoutmanager/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/backbone.marionette/index.d.ts b/types/backbone.marionette/index.d.ts index bacd045ba1..4edaba87b7 100644 --- a/types/backbone.marionette/index.d.ts +++ b/types/backbone.marionette/index.d.ts @@ -4,13 +4,15 @@ // Natan Vivo , // Sven Tschui , // Volker Nauruhn , -// Ard Timmerman +// Ard Timmerman , +// J. Joe Koullas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 import * as Backbone from 'backbone'; import * as JQuery from 'jquery'; import * as Radio from 'backbone.radio'; +import * as _ from 'underscore'; export as namespace Marionette; @@ -179,6 +181,131 @@ export class Container { * Find a view by it's cid. */ remove(view: TView): void; + + /** + * @see _.forEach + */ + forEach(iterator: _.ListIterator, context?: any): Container; + + /** + * @see _.each + */ + each(iterator: _.ListIterator, context?: any): Container; + + /** + * @see _.map + */ + map(iterator: _.ListIterator, context?: any): TResult[]; + + /** + * @see _.find + */ + find(iterator: _.ListIterator, context?: any): Container | undefined; + + /** + * @see _.detect + */ + detect(iterator: _.ListIterator, context?: any): Container | undefined; + + /** + * @see _.filter + */ + filter(iterator: _.ListIterator, context?: any): TView[]; + + /** + * @see _.select + */ + select(iterator: _.ListIterator, context?: any): TView[]; + + /** + * @see _.reject + */ + reject(iterator: _.ListIterator, context?: any): TView[]; + + /** + * @see _.every + */ + every(iterator: _.ListIterator, context?: any): boolean; + + /** + * @see _.all + */ + all(iterator: _.ListIterator, context?: any): boolean; + + /** + * @see _.some + */ + some(iterator: _.ListIterator, context?: any): boolean; + + /** + * @see _.any + */ + any(iterator: _.ListIterator, context?: any): boolean; + + /** + * @see _.include + */ + include(value: TView, fromIndex?: number): boolean; + + /** + * @see _.contains + */ + contains(value: TView, fromIndex?: number): boolean; + + /** + * @see _.invoke + */ + invoke(methodName: string, ...args: any[]): any; + + /** + * @see _.toArray + */ + toArray(): TView[]; + + /** + * @see _.first + */ + first(): TView | undefined; + + /** + * @see _.initial + */ + initial(n?: number): TView[]; + + /** + * @see _.rest + */ + rest(n?: number): TView[]; + + /** + * @see _.last + */ + last(n: number): TView[]; + + /** + * @see _.without + */ + without(...values: TView[]): TView[]; + + /** + * @see _.isEmpty + */ + isEmpty(): boolean; + + /** + * @see _.pluck + */ + pluck(propertyName: string): any[]; + + /** + * @see _.reduce + */ + reduce(iterator: _.MemoIterator, memo?: TResult, context?: any): TResult; + + /** + * @see _.partition + */ + partition(iterator: _.ListIterator, context?: any): TView[][]; } /** @@ -280,9 +407,21 @@ export interface ObjectOptions extends RadioMixinOptions { * A base class which other classes can extend from. Object incorporates many * backbone conventions and utilities like initialize and Backbone.Events. */ -export class Object extends Backbone.Events implements CommonMixin, RadioMixin { +export class Object implements CommonMixin, RadioMixin, Backbone.Events { constructor(options?: ObjectOptions); + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + /** * Receives a hash of event names and functions and/or function names, * and returns the same hash with the function names replaced with the @@ -1154,7 +1293,7 @@ export class View extends Backbone.View i export interface CollectionViewOptions< TModel extends Backbone.Model, TCollection extends Backbone.Collection = Backbone.Collection -> extends Backbone.ViewOptions, ViewMixinOptions { + > extends Backbone.ViewOptions, ViewMixinOptions { /** * Specify a child view to use. */ diff --git a/types/backbone.paginator/backbone.paginator-tests.ts b/types/backbone.paginator/backbone.paginator-tests.ts index f24e2855f5..0c1b0cf9a8 100644 --- a/types/backbone.paginator/backbone.paginator-tests.ts +++ b/types/backbone.paginator/backbone.paginator-tests.ts @@ -70,8 +70,8 @@ namespace InitializingWithOptions { }); var testCollection6 = new TestCollection([ - {}, - {}, + {} as TestModel, + {} as TestModel, ]); } diff --git a/types/backbone.radio/index.d.ts b/types/backbone.radio/index.d.ts index 12fc6d384f..ac953aa00b 100644 --- a/types/backbone.radio/index.d.ts +++ b/types/backbone.radio/index.d.ts @@ -71,7 +71,18 @@ declare module "backbone" { stopReplying(commandName?: string, callback?: (...args: any[]) => any, context?: any): Requests; } - class Channel extends Backbone.Events implements Commands, Requests { + class Channel implements Commands, Requests, Backbone.Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + on(eventName: any, callback?: any, context?: any): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; channelName: string; reset(): Channel; diff --git a/types/backbone/backbone-tests.ts b/types/backbone/backbone-tests.ts index 65a1463978..563c21634c 100644 --- a/types/backbone/backbone-tests.ts +++ b/types/backbone/backbone-tests.ts @@ -1,6 +1,6 @@ function test_events() { - var object = new Backbone.Events(); + var object = Backbone.Events; object.on("alert", (eventName: string) => alert("Triggered " + eventName)); object.trigger("alert", "an event"); diff --git a/types/backbone/index.d.ts b/types/backbone/index.d.ts index 81bce43606..a881284c8f 100644 --- a/types/backbone/index.d.ts +++ b/types/backbone/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Boris Yankov // Natan Vivo // kenjiru +// jjoekoullas // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -91,24 +92,37 @@ declare namespace Backbone { } interface EventsHash { - [selector: string]: string | {(eventObject: JQueryEventObject): void}; + [selector: string]: string | {(eventObject: JQuery.TriggeredEvent): void}; } - class Events { + export const Events: Events; + interface Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: EventsHash): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; + } + + class ModelBase implements Events { on(eventName: string, callback?: Function, context?: any): any; on(eventMap: EventsHash): any; - off(eventName?: string, callback?: Function, context?: any): any; - trigger(eventName: string, ...args: any[]): any; - bind(eventName: string, callback: Function, context?: any): any; - unbind(eventName?: string, callback?: Function, context?: any): any; + on(eventName: any, callback?: any, context?: any): any + off(eventName?: string, callback?: Function, context?: any): any + trigger(eventName: string, ...args: any[]): any + bind(eventName: string, callback: Function, context?: any): any + unbind(eventName?: string, callback?: Function, context?: any): any + once(events: string, callback: Function, context?: any): any + listenTo(object: any, events: string, callback: Function):any + listenToOnce(object: any, events: string, callback: Function): any + stopListening(object?: any, events?: string, callback?: Function): any - once(events: string, callback: Function, context?: any): any; - listenTo(object: any, events: string, callback: Function): any; - listenToOnce(object: any, events: string, callback: Function): any; - stopListening(object?: any, events?: string, callback?: Function): any; - } - - class ModelBase extends Events { parse(response: any, options?: any): any; toJSON(options?: any): any; sync(...arg: any[]): JQueryXHR; @@ -353,7 +367,7 @@ declare namespace Backbone { without(...values: TModel[]): TModel[]; } - class Router extends Events { + class Router extends EventSignatures { /** * Do not use, prefer TypeScript's extend functionality. @@ -382,7 +396,7 @@ declare namespace Backbone { var history: History; - class History extends Events { + class History extends EventSignatures { handlers: any[]; interval: number; @@ -419,7 +433,7 @@ declare namespace Backbone { attributes?: {[id: string]: any}; } - class View extends Events { + class View extends EventSignatures { /** * Do not use, prefer TypeScript's extend functionality. @@ -471,3 +485,21 @@ declare namespace Backbone { function noConflict(): typeof Backbone; var $: JQueryStatic; } + +/** + * This is not for external use and is only here as a convenient way to + * specify signatures for internal implementers of Backbone.Events + */ +declare abstract class EventSignatures implements Backbone.Events { + on(eventName: string, callback?: (...args: any[]) => void, context?: any): any; + on(eventMap: Backbone.EventsHash): any; + off(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + trigger(eventName: string, ...args: any[]): any; + bind(eventName: string, callback: (...args: any[]) => void, context?: any): any; + unbind(eventName?: string, callback?: (...args: any[]) => void, context?: any): any; + + once(events: string, callback: (...args: any[]) => void, context?: any): any; + listenTo(object: any, events: string, callback: (...args: any[]) => void): any; + listenToOnce(object: any, events: string, callback: (...args: any[]) => void): any; + stopListening(object?: any, events?: string, callback?: (...args: any[]) => void): any; +} \ No newline at end of file diff --git a/types/backbone/tslint.json b/types/backbone/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/backbone/tslint.json +++ b/types/backbone/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/baconjs/baconjs-tests.ts b/types/baconjs/baconjs-tests.ts index 2755bec595..b7d6db4c0f 100644 --- a/types/baconjs/baconjs-tests.ts +++ b/types/baconjs/baconjs-tests.ts @@ -120,7 +120,7 @@ function CommonMethodsInEventStreamsAndProperties() { Bacon.fromArray([1, 2, 3]).withStateMachine(0, (sum, event) => { if (event.hasValue()) { // had to cast to `number` because event:Bacon.Next|Bacon.Error<{}> - return [sum + event.value(), []]; + return [sum + (event.value() as number), []]; } else if (event.isEnd()) { return [undefined, [new Bacon.Next(sum), event]]; @@ -140,8 +140,8 @@ function CommonMethodsInEventStreamsAndProperties() { { // This is handy for keeping track whether we are currently awaiting an AJAX response: - var ajaxRequest = >{}, - ajaxResponse = >{}, + var ajaxRequest = {} as Bacon.Observable, + ajaxResponse = {} as Bacon.Observable, showAjaxIndicator = ajaxRequest.awaiting(ajaxResponse); } diff --git a/types/baidu-app/baidu-app-tests.ts b/types/baidu-app/baidu-app-tests.ts new file mode 100644 index 0000000000..9987a650ee --- /dev/null +++ b/types/baidu-app/baidu-app-tests.ts @@ -0,0 +1,2007 @@ +(() => { + swan.request({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + method: 'GET', + dataType: 'json', + data: { + key: 'value' + }, + header: { + 'content-type': 'application/json' // 默认值 + }, + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + const requestTask = swan.request({ + url: 'test.php', // 仅为示例,并非真实的接口地址 + data: { + x: '', + y: '' + }, + header: { + 'content-type': 'application/json' + }, + success(res) { + console.log(res.data); + } + }); + // 取消请求任务 + requestTask.abort(); +})(); + +(() => { + swan.chooseImage({ + success(res) { + swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的接口地址 + filePath: res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); +})(); + +(() => { + const uploadTask = swan.uploadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 开发者服务器 url + filePath: '', // res.tempFilePaths[0], // 要上传文件资源的路径 + name: 'myfile', + success(res) { + console.log(res.statusCode); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + uploadTask.onProgressUpdate(res => { + console.log('上传进度', res.progress); + console.log('已经上传的数据长度', res.totalBytesSent); + console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend); + }); + + uploadTask.abort(); // 取消上传任务 +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + // 下载成功 + if (res.statusCode === 200) { + console.log("临时文件路径" + res.tempFilePath); + } + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const downloadTask = swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx', // 仅为示例,并非真实的资源 + success(res) { + console.log(res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + downloadTask.onProgressUpdate(res => { + console.log('下载进度', res.progress); + console.log('已经下载的数据长度', res.totalBytesWritten); + console.log('预期需要下载的数据总长度', res.totalBytesExpectedToWrite); + }); + + downloadTask.abort(); // 取消下载任务 +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen((res) => { + console.log('WebSocket连接已打开!', res.header); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' // 仅为示例,并非真实的服务地址 + }); + swan.onSocketError((res) => { + console.log('WebSocket连接打开失败,请检查!'); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + swan.onSocketOpen(() => { + swan.sendSocketMessage({ + data: 'baidu' + }); + }); + swan.onSocketMessage((res) => { + console.log('收到服务器内容:', res.data); + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com', + success(res) { + swan.closeSocket(); + } + }); +})(); + +(() => { + swan.connectSocket({ + url: 'wss://example.baidu.com' + }); + + swan.onSocketClose((res) => { + console.log('WebSocket 已关闭!'); + }); + + swan.onSocketOpen(() => { + swan.closeSocket(); + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrIdCard({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrBankCard({ + image, + success(res) { + console.log(res.result.bank_name); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrDrivingLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.ocrVehicleLicense({ + image, + success(res) { + console.log(res.words_result); + } + }); + } + }); +})(); + +(() => { + swan.ai.textReview({ + content: '', + success(res) { + console.log(res.result.spam); // 0 表示审核通过 + } + }); +})(); + +(() => { + swan.ai.textToAudio({ + ctp: '1', + lan: 'zh', + tex: '这是一段测试文字', + success(res) { + console.log(res.filePath); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.imageAudit({ + image, + success(res) { + console.log(res.conclusionType); // 1 为合规 + } + }); + } + }); +})(); + +(() => { + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.advancedGeneralIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.objectDetectIdentify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.carClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.dishClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.logoClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.animalClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); + swan.chooseImage({ + success(res) { + const image = res.tempFilePaths[0]; + swan.ai.plantClassify({ + image, + success(res) { + console.log(res.result); + } + }); + } + }); +})(); + +(() => { + const voiceRecognizer = swan.ai.getVoiceRecognizer(); + + voiceRecognizer.onStart(() => { + console.log('voice start'); + }); + voiceRecognizer.onRecognize(res => { + console.log('voice recognize', res); + }); + voiceRecognizer.onFinish(res => { + console.log('voice end', res); + }); + voiceRecognizer.onError(err => { + console.log('voice error', err); + }); + + const options = { + mode: 'dnn', + longSpeech: false + }; + + voiceRecognizer.start(options); +})(); + +(() => { + swan.chooseImage({ + count: 1, + sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 + sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 + success(res) { + // 成功则返回图片的本地文件路径列表 tempFilePaths + console.log(res.tempFilePaths); + // 文件列表对象 + console.log(res.tempFiles); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.previewImage({ + current: '', // 当前显示图片的http链接 + urls: [], // 需要预览的图片http链接列表 + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + + swan.getImageInfo({ + src: '/xxx/xxx.jpg', + success(res) { + // 成功则返回图片高,宽,本地路径 + console.log(res.width); + console.log(res.height); + console.log(res.path); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.saveImageToPhotosAlbum({ + filePath: '/xxx/xxx.jpg', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const recorderManager = swan.getRecorderManager(); + + recorderManager.onStart(() => { + // 开始录音事件 + console.log('recorder start'); + }); + recorderManager.onPause(() => { + // 暂停录音事件 + console.log('recorder pause'); + }); + recorderManager.onStop((res) => { + // 停止录音事件 + console.log('recorder stop', res); + const { tempFilePath } = res; + }); + + const options = { + duration: 10000, + sampleRate: 44100, + numberOfChannels: 1, + encodeBitRate: 96000, + format: 'aac' + }; + + recorderManager.start(options); +})(); + +(() => { + const backgroundAudioManager = swan.getBackgroundAudioManager(); + + backgroundAudioManager.title = '此时此刻'; + backgroundAudioManager.epname = '此时此刻'; + backgroundAudioManager.singer = '许巍'; + backgroundAudioManager.coverImgUrl = 'xxx'; + backgroundAudioManager.src = 'xxx'; +})(); + +(() => { + const innerAudioContext = swan.createInnerAudioContext(); + innerAudioContext.src = 'xxx'; + innerAudioContext.autoplay = true; + innerAudioContext.seek({ + position: 10 + }); + innerAudioContext.onPlay((res) => { + console.log('开始播放'); + }); +})(); + +(() => { + Page({ + data: { + sourceType: ['album', 'camera'], + compressed: false, + maxDuration: 60, + src: '' + }, + + chooseVideo() { + const self = this; + swan.chooseVideo({ + sourceType: this.getData('sourceType'), + compressed: this.getData('compressed'), + maxDuration: this.getData('maxDuration'), + success(res) { + // 成功返回选定视频的临时文件路径 + self.setData('src', res.tempFilePath); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + } + }); + swan.saveVideoToPhotosAlbum({ + filePath: 'bdfile://xxx', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + const myVideo = swan.createVideoContext('myVideo'); + myVideo.play(); +})(); + +(() => { + swan.chooseImage({ + count: 1, + success(res) { + const tempFilePaths = res.tempFilePaths; + swan.saveFile({ + tempFilePath: tempFilePaths[0], + success(res) { + const savedFilePath = res.savedFilePath; + } + }); + } + }); + swan.getFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.digest); + } + }); + swan.getSavedFileList({ + success(res) { + const fileList = res.fileList; + } + }); + swan.getSavedFileInfo({ + filePath: 'bdfile://somefile', + success(res) { + console.log(res.size); + console.log(res.createTime); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getSavedFileList({ + success(res) { + if (res.fileList.length > 0) { + swan.removeSavedFile({ + filePath: res.fileList[0].filePath, + success(res) { + console.log(res.filePath); + } + }); + } + } + }); +})(); + +(() => { + swan.downloadFile({ + url: 'https://smartprogram.baidu.com/xxx.pdf', + success(res) { + const filePath = res.tempFilePath; + swan.openDocument({ + filePath, + success(res) { + console.log('打开文档成功'); + } + }); + } + }); +})(); + +(() => { + swan.setStorage({ + key: 'key', + data: 'value' + }); +})(); + +(() => { + try { + swan.setStorageSync('key', 'value'); + } catch (e) { + } + swan.getStorage({ + key: 'key', + success(res) { + console.log(res.data); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageSync('key'); + } catch (e) { + } + swan.getStorageInfo({ + success(res) { + console.log(res.keys); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + const result = swan.getStorageInfoSync(); + console.log(result); + } catch (e) { + } +})(); + +(() => { + swan.removeStorage({ + key: 'key', + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + try { + swan.removeStorageSync('key'); + } catch (e) { + } + try { + swan.clearStorageSync(); + } catch (e) { + } +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + console.log('纬度:' + res.latitude); + console.log('经度:' + res.longitude); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.getLocation({ + type: 'gcj02', + success(res) { + swan.openLocation({ + latitude: res.latitude, + longitude: res.longitude, + scale: 18 + }); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + let mapContext: swan.MapContext; + Page({ + data: { + latitude: '40.042500', + longitude: '116.274040', + }, + onReady() { + mapContext = swan.createMapContext('myMap'); + }, + getCenterLocation() { + mapContext.getCenterLocation({ + success(res) { + console.log("经度" + res.longitude); + console.log("纬度" + res.latitude); + } + }); + }, + moveToLocation() { + mapContext.moveToLocation(); + }, + translateMarker() { + mapContext.translateMarker({ + markerId: 0, + rotate: 90, + autoRotate: true, + duration: 1000, + destination: { + latitude: 23.10229, + longitude: 113.3345211, + }, + animationEnd() { + console.log('animation end'); + } + }); + }, + includePoints() { + mapContext.includePoints({ + padding: [10], + points: [{ + latitude: 23, + longitude: 113.33, + }, { + latitude: 23, + longitude: 113.3345211, + }] + }); + }, + getRegion() { + mapContext.getRegion({ + success(res) { + console.log("西南角的经纬度" + res.southwest); + console.log("东北角的经纬度" + res.northeast); + } + }); + } + }); +})(); + +(() => { + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + ctx.draw(); + } + }); + Page({ + onReady() { + const ctx = this.createCanvasContext('myCanvas'); + } + }); + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('#ff0000'); + ctx.arc(100, 100, 50, 0, 2 * Math.PI); + ctx.fill(); + + ctx.draw(); + + swan.canvasGetImageData({ + canvasId: 'myCanvas', + x: 0, + y: 0, + width: 100, + height: 100, + success(res) { + console.log(res); + } + }); + const data = new Uint8ClampedArray([255, 0, 0, 1]); + swan.canvasPutImageData({ + canvasId: 'myCanvas', + data, + x: 0, + y: 0, + width: 1, + height: 2, + success(res) { + console.log('success'); + } + }); + swan.canvasToTempFilePath({ + x: 100, + y: 200, + width: 50, + height: 50, + destWidth: 100, + destHeight: 100, + canvasId: 'myCanvas', + success(res) { + console.log(res.tempFilePath); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.setShadow(10, 50, 50, 'red'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create linear gradient + const grd = ctx.createLinearGradient(0, 0, 200, 0); + grd.addColorStop(0, 'blue'); + grd.addColorStop(1, 'red'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createCircularGradient(75, 50, 50); + grd.addColorStop(0, 'red'); + grd.addColorStop(1, 'blue'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + // Create circular gradient + const grd = ctx.createLinearGradient(30, 10, 120, 10); + grd.addColorStop(0, 'red'); + grd.addColorStop(0.16, 'orange'); + grd.addColorStop(0.33, 'yellow'); + grd.addColorStop(0.5, 'green'); + grd.addColorStop(0.66, 'cyan'); + grd.addColorStop(0.83, 'blue'); + grd.addColorStop(1, 'purple'); + + // Fill with gradient + ctx.setFillStyle(grd); + ctx.fillRect(30, 30, 150, 80); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(5); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(15); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(30, 10); + ctx.lineTo(200, 10); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('butt'); + ctx.setLineWidth(10); + ctx.moveTo(50, 30); + ctx.lineTo(200, 30); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('round'); + ctx.setLineWidth(10); + ctx.moveTo(70, 50); + ctx.lineTo(200, 50); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineCap('square'); + ctx.setLineWidth(10); + ctx.moveTo(90, 70); + ctx.lineTo(200, 70); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('bevel'); + ctx.setLineWidth(10); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('round'); + ctx.setLineWidth(10); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineJoin('miter'); + ctx.setLineWidth(10); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setLineDash([10, 20], 5); + ctx.beginPath(); + ctx.moveTo(0, 100); + ctx.lineTo(400, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(1); + ctx.moveTo(10, 10); + ctx.lineTo(100, 50); + ctx.lineTo(10, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(2); + ctx.moveTo(50, 10); + ctx.lineTo(140, 50); + ctx.lineTo(50, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(3); + ctx.moveTo(90, 10); + ctx.lineTo(180, 50); + ctx.lineTo(90, 90); + ctx.stroke(); + + ctx.beginPath(); + ctx.setLineWidth(10); + ctx.setLineJoin('miter'); + ctx.setMiterLimit(4); + ctx.moveTo(130, 10); + ctx.lineTo(220, 50); + ctx.lineTo(130, 90); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(30, 30, 150, 75); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setStrokeStyle('blue'); + ctx.strokeRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('red'); + ctx.fillRect(0, 0, 150, 200); + ctx.setFillStyle('blue'); + ctx.fillRect(150, 0, 150, 200); + ctx.clearRect(30, 30, 150, 75); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.rect(10, 10, 100, 30); + ctx.setFillStyle('red'); + ctx.fill(); + ctx.beginPath(); + ctx.rect(10, 40, 100, 30); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 70, 100, 30); + ctx.rect(10, 100, 100, 30); + ctx.setFillStyle('green'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(100, 100); + ctx.lineTo(10, 100); + ctx.lineTo(10, 10); + ctx.closePath(); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.lineTo(100, 10); + ctx.moveTo(10, 100); + ctx.lineTo(100, 100); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.moveTo(10, 10); + ctx.rect(10, 10, 100, 50); + ctx.lineTo(110, 60); + ctx.stroke(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.arc(100, 75, 50, 0, 2 * Math.PI); + ctx.setFillStyle('blue'); + ctx.fill(); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + ctx.scale(2, 2); + ctx.strokeRect(10, 10, 25, 15); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + ctx.rotate(20 * Math.PI / 180); + ctx.strokeRect(100, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + ctx.translate(20, 20); + ctx.strokeRect(10, 10, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.downloadFile({ + url: 'https://b.bdstatic.com/searchbox/icms/searchbox/img/LOGO300x300.jpg', + success(res) { + ctx.save(); + ctx.beginPath(); + ctx.arc(50, 50, 25, 0, 2 * Math.PI); + ctx.clip(); + ctx.drawImage(res.tempFilePath, 25, 25); + ctx.restore(); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('20', 20, 20); + ctx.setFontSize(30); + ctx.fillText('30', 40, 40); + ctx.setFontSize(40); + ctx.fillText('40', 60, 60); + ctx.setFontSize(50); + ctx.fillText('50', 90, 90); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFontSize(20); + ctx.fillText('Hello', 20, 20); + ctx.fillText('World', 100, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(150, 20); + ctx.lineTo(150, 170); + ctx.stroke(); + + ctx.setFontSize(15); + ctx.setTextAlign('left'); + ctx.fillText('textAlign=left', 150, 60); + + ctx.setTextAlign('center'); + ctx.fillText('textAlign=center', 150, 80); + + ctx.setTextAlign('right'); + ctx.fillText('textAlign=right', 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setStrokeStyle('red'); + ctx.moveTo(5, 75); + ctx.lineTo(295, 75); + ctx.stroke(); + + ctx.setFontSize(20); + + ctx.setTextBaseline('top'); + ctx.fillText('top', 5, 75); + + ctx.setTextBaseline('middle'); + ctx.fillText('middle', 50, 75); + + ctx.setTextBaseline('bottom'); + ctx.fillText('bottom', 120, 75); + + ctx.setTextBaseline('normal'); + ctx.fillText('normal', 200, 75); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + swan.chooseImage({ + success(res) { + ctx.drawImage(res.tempFilePaths[0], 0, 0, 150, 100); + ctx.draw(); + } + }); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + + ctx.setFillStyle('red'); + ctx.fillRect(10, 10, 150, 100); + ctx.setGlobalAlpha(0.2); + ctx.setFillStyle('blue'); + ctx.fillRect(50, 50, 150, 100); + ctx.setFillStyle('yellow'); + ctx.fillRect(100, 100, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.font = 'italic bold 20px cursive'; + const metrics = ctx.measureText('Hello World'); + console.log(metrics.width); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + const pattern = ctx.createPattern('/path/to/image', 'repeat-x'); + ctx.fillStyle = pattern; + ctx.fillRect(0, 0, 300, 150); + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.bezierCurveTo(20, 100, 200, 100, 200, 20); + ctx.setStrokeStyle('black'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // Draw quadratic curve + ctx.beginPath(); + ctx.moveTo(20, 20); + ctx.quadraticCurveTo(20, 100, 200, 20); + ctx.setStrokeStyle('blue'); + ctx.stroke(); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + // save the default fill style + ctx.save(); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + + // restore to the previous saved state + ctx.restore(); + ctx.fillRect(50, 50, 150, 100); + + ctx.draw(); +})(); + +(() => { + const ctx = swan.createCanvasContext('myCanvas'); + ctx.setFillStyle('blue'); + ctx.fillRect(10, 10, 150, 100); + ctx.draw(); + ctx.fillRect(30, 30, 150, 100); + ctx.draw(); +})(); + +(() => { + swan.showToast({ + title: '我是标题', + icon: 'loading', + duration: 1000, + }); + swan.showLoading({ + title: '加载中', + mask: 'true' + }); + + setTimeout(() => { + swan.hideLoading(); + }, 2000); + + swan.showModal({ + title: '提示', + content: '这是一个模态弹窗', + cancelColor: '#999999', + confirmColor: '#0099cc', + success(res) { + if (res.confirm) { + console.log('用户点击了确定'); + } else if (res.cancel) { + console.log('用户点击了取消'); + } + } + }); + swan.showActionSheet({ + itemList: ['同意', '一般', '不同意'], + success(res) { + console.log(`用户点击了第${(res.tapIndex + 1)}个按钮`); + } + }); +})(); + +(() => { + swan.setNavigationBarTitle({ + title: '我是页面标题' + }); + swan.setNavigationBarColor({ + frontColor: '#ffffff', + backgroundColor: '#ff0000', + animation: { + duration: 500, + timingFunc: 'linear' + } + }); +})(); + +(() => { + swan.setTabBarBadge({ + index: 0, + text: '文本' + }); + swan.removeTabBarBadge({ + index: 0 + }); + swan.showTabBarRedDot({ + index: 0 + }); + swan.hideTabBarRedDot({ + index: 0 + }); + swan.setTabBarStyle({ + color: '#FFFFBD', + selectedColor: '#FFFFBD', + backgroundColor: '#FFFFBD', + borderStyle: 'white' + }); + swan.setTabBarItem({ + index: 0, + text: '文本', + // 图片路径 + iconPath: '/images/component_normal.png', + // 选中图片路径 + selectedIconPath: '/images/component_selected.png', + }); + swan.showTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); + swan.hideTabBar({ + success(res) { + console.log(res); + }, + fail(err) { + console.log('错误码:' + err.errCode); + console.log('错误信息:' + err.errMsg); + } + }); +})(); + +(() => { + swan.navigateTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.redirectTo({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); + swan.switchTab({ + url: '/list', + }); + // 注意:调用 navigateTo 跳转时,调用页面会被加入堆栈,而 redirectTo 方法则不会。见下方示例代码 + + // 当前是首页 + swan.navigateTo({ + url: 'list?key=value' + }); + + // 当前是列表页 + swan.navigateTo({ + url: 'detail?key=value' + }); + + // 在详情页内 navigateBack,将返回首页 + swan.navigateBack({ + delta: 2 + }); + swan.reLaunch({ + // 此路径为相对路径;如需写为绝对地址,则可写为‘/example/xxx?key=valu’。 + url: 'example/xxx?key=value' + }); +})(); + +(() => { + const animation = swan.createAnimation({ + transformOrigin: "50% 50%", + duration: 1000, + timingFunction: "ease", + delay: 0 + }); + Page({ + data: { + animationData: {} + }, + starttoanimate() { + const animation = swan.createAnimation(); + animation.rotate(90).translateY(10).step(); + animation.rotate(-90).translateY(-10).step(); + this.setData({ + animationData: animation.export() + }); + } + }); +})(); + +(() => { + swan.pageScrollTo({ + scrollTop: 0, + duration: 300 + }); +})(); + +(() => { + Page({ + onPullDownRefresh() { + // do something + } + }); + swan.startPullDownRefresh(); + swan.stopPullDownRefresh(); +})(); + +(() => { + swan.createIntersectionObserver({} as any, { + selectAll: true + }).relativeTo('.container') + .observe('.ball', res => { + console.log(res.intersectionRect); // 相交区域 + console.log(res.intersectionRect.left); // 相交区域的左边界坐标 + console.log(res.intersectionRect.top); // 相交区域的上边界坐标 + console.log(res.intersectionRect.width); // 相交区域的宽度 + console.log(res.intersectionRect.height); // 相交区域的高度 + }); + Page({ + queryMultipleNodes() { + const query = swan.createSelectorQuery(); + query.select('#the-id').boundingClientRect(); + query.selectViewport().scrollOffset(); + query.exec((res) => { + // res[0].top, // #the-id节点的上边界坐标 + // res[1].scrollTop // 显示区域的竖直滚动位置 + }); + } + }); + Component({ + // queryMultipleNodes() { + // const query = swan.createSelectorQuery().in(this); + // query.select('#the-id').boundingClientRect((res) => { + // // res.top // 这个组件内 #the-id 节点的上边界坐标 + // }).exec(); + // } + }); + Page({ + getRect() { + swan.createSelectorQuery().select('#the-id').boundingClientRect((res) => { + const rect = res as swan.NodesRefRect; + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }).exec(); + }, + getAllRects() { + swan.createSelectorQuery().selectAll('.a-class').boundingClientRect((rects) => { + (rects as swan.NodesRefRect[]).forEach((rect) => { + rect.id; // 节点的ID + rect.dataset; // 节点的dataset + rect.left; // 节点的左边界坐标 + rect.right; // 节点的右边界坐标 + rect.top; // 节点的上边界坐标 + rect.bottom; // 节点的下边界坐标 + rect.width; // 节点的宽度 + rect.height; // 节点的高度 + }); + }).exec(); + } + }); + Page({ + getScrollOffset() { + swan.createSelectorQuery().selectViewport().scrollOffset((res) => { + res.id; // 节点的ID + res.dataset; // 节点的dataset + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + }).exec(); + } + }); + Page({ + getFields() { + swan.createSelectorQuery().select('#the-id').fields({ + dataset: true, + size: true, + scrollOffset: true, + properties: ['scrollX', 'scrollY'], + computedStyle: ['margin', 'backgroundColor'] + }, (res) => { + res.dataset; // 节点的dataset + res.width; // 节点的宽度 + res.height; // 节点的高度 + res.scrollLeft; // 节点的水平滚动位置 + res.scrollTop; // 节点的竖直滚动位置 + res.scrollX; // 节点 scroll-x 属性的当前值 + res.scrollY; // 节点 scroll-y 属性的当前值 + // 此处返回指定要返回的样式名 + res.margin; + res.backgroundColor; + }).exec(); + } + }); +})(); + +(() => { + swan.getSystemInfo({ + success(res) { + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } + }); + try { + const res = swan.getSystemInfoSync(); + console.log(res.model); + console.log(res.pixelRatio); + console.log(res.windowWidth); + console.log(res.windowHeight); + console.log(res.language); + console.log(res.version); + console.log(res.platform); + } catch (e) { + // Do something when catch error + } + try { + const res = swan.getEnvInfoSync(); + console.log(res.appKey); + console.log(res.appName); + console.log(res.lastAppURL); + console.log(res.sdkVersion); + console.log(res.scheme); + } catch (e) { + // Do something when catch error + } + swan.canIUse('view.hover-class'); + swan.canIUse('scroll-view.scroll-x'); + swan.canIUse('cover-view'); + swan.canIUse('button.size.default'); + swan.canIUse('button.size.default'); + swan.canIUse('request.object.success.data'); + swan.canIUse('getSavedFileList'); + swan.canIUse('getSavedFileList.object'); + swan.canIUse('getSavedFileList.object.success'); +})(); + +(() => { + swan.onMemoryWarning((res) => { + console.log('onMemoryWarningReceive'); + }); +})(); + +(() => { + swan.getNetworkType({ + success(res) { + console.log(res.networkType); + } + }); + swan.onNetworkStatusChange((res) => { + console.log(res.isConnected); + console.log(res.networkType); + }); +})(); + +(() => { + swan.onAccelerometerChange((res) => { + console.log(res.x); + console.log(res.y); + console.log(res.z); + }); + swan.startAccelerometer({ + interval: 'ui' + }); + swan.stopAccelerometer(); +})(); + +(() => { + swan.onCompassChange((res) => { + console.log(res.direction); + }); + swan.startCompass(); + swan.stopCompass(); +})(); + +(() => { + swan.scanCode({ + success(res) { + console.log(res.result); + console.log(res.scanType); + } + }); +})(); + +(() => { + swan.onUserCaptureScreen(() => { + console.log('用户截屏了'); + }); +})(); + +(() => { + swan.makePhoneCall({ + phoneNumber: '000000' // 仅为示例,并非真实的电话号码 + }); +})(); + +(() => { + swan.setClipboardData({ + data: 'baidu', + success(res) { + swan.getClipboardData({ + success(res) { + console.log(res.data); // baidu + } + }); + } + }); + swan.getClipboardData({ + success(res) { + console.log(res.data); + } + }); +})(); + +(() => { + swan.getExtConfig({ + success(res) { + console.log(res.extConfig); + } + }); + const data = swan.getExtConfigSync(); + console.log(data.extConfig); +})(); + +(() => { + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址 + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('login fail', err); + } + }); + swan.checkSession({ + success(res) { + console.log('登录态有效'); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + swan.request({ + url: "https://xxx/decrypt_user_data", // 开发者服务器地址,对 data 进行解密 + data: { + data: res.data, + iv: res.iv + } + }); + } + }); + }, + fail(err) { + console.log('登录态无效'); + swan.login({ + success(res) { + swan.request({ + url: 'https://xxx/xxx', // 开发者服务器地址,用 code 换取 session_key + data: { + code: res.code + } + }); + }, + fail(err) { + console.log('登录失败', err); + } + }); + } + }); + + try { + const result = swan.isLoginSync(); + console.log('isLoginSync', result); + } catch (e) { + console.log('error', e); + } +})(); + +(() => { + swan.authorize({ + scope: 'scope.userLocation', + success(res) { + // 用户已经同意智能小程序使用定位功能 + swan.getLocation(); + } + }); +})(); + +(() => { + swan.getSwanId({ + success(res) { + console.log(res.data.swanid); + } + }); + swan.getUserInfo({ + success(res) { + console.log('用户名', res.userInfo.nickName); + } + }); +})(); + +(() => { + swan.openSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); + swan.getSetting({ + success(res) { + console.log(res.authSetting['scope.userInfo']); + console.log(res.authSetting['scope.userLocation']); + } + }); +})(); + +(() => { + Page({ + onShareAppMessage() { + return { + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }; + } + }); + swan.openShare({ + title: '智能小程序示例', + content: '世界很复杂,百度更懂你', + path: '/pages/openShare/openShare?key=value' + }); +})(); + +(() => { + swan.chooseAddress({ + success(res) { + console.log(res.userName); + console.log(res.postalCode); + console.log(res.provinceName); + console.log(res.cityName); + console.log(res.countyName); + console.log(res.detailInfo); + console.log(res.telNumber); + } + }); +})(); + +(() => { + swan.requestPolymerPayment({ + orderInfo: { + dealId: "470193086", + appKey: "MMMabc", + totalAmount: "1", + tpOrderId: "3028903626", + dealTitle: "智能小程序Demo支付测试", + signFieldsRange: 1, + rsaSign: '', + bizInfo: '' + }, + success(res) { + swan.showToast({ + title: '支付成功', + icon: 'success' + }); + }, + fail(err) { + swan.showToast({ + title: JSON.stringify(err) + }); + console.log('pay fail', err); + } + }); +})(); + +(() => { + swan.chooseInvoiceTitle({ + success(res) { + console.log(res.type); + console.log(res.title); + console.log(res.taxNumber); + console.log(res.companyAddress); + console.log(res.telephone); + console.log(res.bankName); + console.log(res.bankAccount); + } + }); +})(); + +(() => { + swan.navigateToSmartProgram({ + appKey: '4fecoAqgCIUtzIyA4FAPgoyrc4oUc25c', // 要打开的小程序 App Key + path: '', // 打开的页面路径,如果为空则打开首页 + extraData: { + foo: 'baidu' + }, + success(res) { + // 打开成功 + } + }); + swan.navigateBackSmartProgram({ + extraData: { + foo: 'baidu' + }, + success(res) { + // 返回成功 + } + }); +})(); + +(() => { + if (swan.setMetaDescription) { + swan.setMetaDescription({ + content: '当前小程序页面描述信息', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setMetaKeywords) { + swan.setMetaKeywords({ + content: '小程序, 关键字', + success(res) { + console.log('设置成功'); + }, + fail(res) { + console.log('设置失败'); + }, + complete(res) { + console.log('设置失败'); + } + }); + } + if (swan.setDocumentTitle) { + swan.setDocumentTitle({ + title: '我是页面标题' + }); + } +})(); + +(() => { + swan.loadSubPackage({ + root: 'subpackage', + success(res) { + console.log('下载成功', res); + }, + fail(err) { + console.log('下载失败', err); + } + }); +})(); + +(() => { + const updateManager = swan.getUpdateManager(); + + updateManager.onCheckForUpdate((res) => { + // 请求完新版本信息的回调 + console.log(res.hasUpdate); + }); + + updateManager.onUpdateReady((res) => { + swan.showModal({ + title: '更新提示', + content: '新版本已经准备好,是否重启应用?', + success(res) { + if (res.confirm) { + // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启 + updateManager.applyUpdate(); + } + } + }); + }); + + updateManager.onUpdateFailed((res) => { + // 新的版本下载失败 + }); +})(); + +(() => { + // 打开调试 + swan.setEnableDebug({ + enableDebug: true + }); + + // 关闭调试 + swan.setEnableDebug({ + enableDebug: false + }); +})(); + +(() => { + swan.reportAnalytics('purchase', { + price: 120, + color: 'red' + }); +})(); diff --git a/types/baidu-app/index.d.ts b/types/baidu-app/index.d.ts new file mode 100644 index 0000000000..244e9dd473 --- /dev/null +++ b/types/baidu-app/index.d.ts @@ -0,0 +1,4758 @@ +// Type definitions for swan-app 2.2 +// Project: https://smartprogram.baidu.com/docs/develop/tutorial/codedir/ +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.8 + +declare namespace swan { + // #region 基本参数 + interface DataResponse { + /** 回调函数返回的内容 */ + data: string | ArrayBuffer; + statusCode: number; + header: any; + result: string; + } + interface ErrMsgResponse { + /** 成功:ok,错误:详细信息 */ + errMsg: "ok" | string; + } + interface TempFileResponse { + /** 文件的临时路径 */ + tempFilePath: string; + /** 开发者服务器返回的 HTTP 状态码 */ + statusCode: number; + } + interface BaseOptions { + /** 接口调用成功的回调函数 */ + success?(res: R): void; + /** 接口调用失败的回调函数 */ + fail?(res: E): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(res: any): void; + } + interface ErrCodeResponse { + errCode: number; + } + // #endregion + // #region 网络API列表 + // 发起请求 + interface RequestHeader { + [key: string]: string; + } + interface RequestOptions extends BaseOptions { + /** 开发者服务器接口地址 */ + url: string; + /** 请求的参数 */ + data?: string | object; + /** 设置请求的 header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认为 GET,有效值:OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: + | "GET" + | "OPTIONS" + | "GET" + | "HEAD" + | "POST" + | "PUT" + | "DELETE"; + /** 如果设为json,会尝试对返回的数据做一次 JSON.parse 默认值为json */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer 默认值为text + * @version 1.7.0 + */ + responseType?: string; + /** 收到开发者服务成功返回的回调函数,res = {data: '开发者服务器返回的内容'} */ + success?(res: DataResponse): void; + fail?(err: { errCode: number; errMsg: string; }): void; + } + /** + * swan.request发起的是https请求。一个微信小程序,同时只能有5个网络请求连接。 + */ + function request(options: RequestOptions): RequestTask; + + /** + * 返回一个 requestTask 对象,通过 requestTask,可中断请求任务。 + */ + interface RequestTask { + abort(): void; + } + + interface UploadTask { + /** + * 监听上传进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 上传进度百分比 */ + progress: number; + /** 已经上传的数据长度,单位 Bytes */ + totalBytesSent: number; + /** 预期需要上传的数据总长度,单位 Bytes */ + totalBytesExpectedToSend: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + // 上传下载 + interface UploadFileOptions extends BaseOptions { + /** 开发者服务器 url */ + url: string; + /** 要上传文件资源的路径 */ + filePath: string; + /** 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 */ + name: string; + /** HTTP 请求 Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** HTTP 请求中其他额外的 form data */ + formData?: any; + } + interface UploadFileResponse { + data: string; // 开发者服务器返回的数据 + statusCode: number; // 开发者服务器返回的 HTTP 状态码 + } + /** + * 将本地资源上传到开发者服务器。 + * 如页面通过 swan.chooseImage 等接口获取到一个本地资源的临时文件路径后, + * 可通过此接口将本地资源上传到指定服务器。 + * 客户端发起一个 HTTPS POST 请求, + * 其中 Content-Type 为 multipart/form-data 。 + */ + function uploadFile(options: UploadFileOptions): UploadTask; + interface DownloadTask { + /** + * 监听下载进度变化 + * @version 1.4.0 + */ + onProgressUpdate( + callback?: ( + res: { + /** 下载进度百分比 */ + progress: number; + /** 已经下载的数据长度,单位 Bytes */ + totalBytesWritten: number; + /** 预期需要下载的数据总长度,单位 Bytes */ + totalBytesExpectedToWrite: number; + } + ) => void + ): void; + /** + * 中断下载任务 + * @version 1.4.0 + */ + abort(): void; + } + interface DownloadFileOptions extends BaseOptions { + /** 下载资源的 url */ + url: string; + /** HTTP 请求 Header */ + header?: RequestHeader; + /** 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 下载文件资源到本地。客户端直接发起一个 HTTP GET 请求, + * 把下载到的资源根据 type 进行处理,并返回文件的本地临时路径。 + */ + function downloadFile(options: DownloadFileOptions): DownloadTask; + // WebSocket + interface ConnectSocketOptions extends BaseOptions { + /** 开发者服务器接口地址,必须是 HTTPS 协议,且域名必须是后台配置的合法域名 */ + url: string; + /** HTTP Header , header 中不能设置 Referer */ + header?: RequestHeader; + /** 默认是GET,有效值为: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT */ + method?: string; + /** + * 子协议数组 + * @version 1.4.0 + */ + protocols?: string[]; + } + /** + * 创建一个 WebSocket 连接; + * 一个微信小程序同时只能有一个 WebSocket 连接, + * 如果当前已存在一个 WebSocket 连接, + * 会自动关闭该连接,并重新创建一个 WebSocket 连接。 + */ + function connectSocket(options: ConnectSocketOptions): void; + /** 监听WebSocket连接打开事件。 */ + function onSocketOpen(callback: (res: any) => void): void; + /** 监听WebSocket错误。 */ + function onSocketError(callback: (error: any) => void): void; + interface SendSocketMessageOptions extends BaseOptions { + /** 需要发送的内容 */ + data: string | ArrayBuffer; + } + /** + * 通过 WebSocket 连接发送数据,需要先 swan.connectSocket, + * 并在 swan.onSocketOpen 回调之后才能发送。 + */ + function sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件。 + */ + function onSocketMessage(callback: (res: DataResponse) => void): void; + /** + * 关闭WebSocket连接。 + */ + interface CloseSocketOptions extends BaseOptions { + code?: number; // 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) 1.4.0 + reason?: string; // 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + } + + /** + * 关闭WebSocket连接。 + */ + function closeSocket(options?: CloseSocketOptions): void; + /** 监听WebSocket关闭。 */ + function onSocketClose(callback: (res: any) => void): void; + /** + * 在接入AI之前需要使用管理员权限操作详细情况官网 + * https://smartprogram.baidu.com/docs/develop/api/ai/ + */ + // #region AI + namespace ai { + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + interface ocrIdCardOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false: 不检测旋转角度,默认不检测。 + id_card_side?: string; // front:身份证含照片的一面;back:身份证带国徽的一面。 + detect_risk?: boolean; // 是否开启身份证风险类型(身份证复印件、临时身份证、身份证翻拍、修改过的身份证)功能,默认不开启,即:false。可选值:true-开启;false-不开启。 + success?(res: ocrIdCardResponse): void; + } + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + interface ocrBankCardOptions extends BaseOptions { + image: string; // 图片资源地址 + success?(res: ocrBankCardResponse): void; + } + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + interface ocrDrivingLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true;false:不检测旋转角度,默认不检测。 + unified_valid_period?: boolean; // true: 归一化格式输出;false 或无此参数按非归一化格式输出。 + success?(res: ocrDrivingLicenseResponse): void; + } + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + interface ocrVehicleLicenseOptions extends BaseOptions { + image: string; // 图片资源地址 + detect_direction?: boolean; // 是否检测图像旋转,可检验图像的选装方向和旋转角度。true:检测旋转角度并矫正识别。针对摆放情况不可控制的情况建议本参数置为true; false:不检测旋转角度,默认不检测。 + accuracy?: string; // normal 使用快速服务,1200ms左右时延;缺省或其它值使用高精度服务,1600ms左右时延。 + success?(res: ocrVehicleLicenseResponse): void; + } + interface ocrIdCardResponse { + direction: number; // 图像方向,当 detect_direction=true 时存在。-1: 未定义,0: 正向,1: 逆时针90度,2: 逆时针180度,3: 逆时针270度。 + image_status: string; // normal-识别正常;reversed_side-身份证正反面颠倒;non_idcard-上传的图片中不包含身份证;blurred-身份证模糊;other_type_card-其他类型证照;over_exposure-身份证关键字段反光或过曝;unknown-未知状态。 + risk_type: string; // 输入参数 detect_risk = true 时,则返回该字段识别身份证类型: normal-正常身份证;copy-复印件;temporary-临时身份证;screen-翻拍;unknown-其他未知情况。 + edit_tool: string; // 如果参数 detect_risk = true 时,则返回此字段。如果检测身份证被编辑过,该字段指定编辑软件名称,如:Adobe Photoshop CC 2014 (Macintosh),如果没有被编辑过则返回值无此参数。 + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示words_result的元素个数。 + words_result: { // 定位和识别结果 + [key: string]: { + location: { // 位置数组(坐标0点为左上角) + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高。 + } + words: string; // 识别结果字符串 + } + }; + } + interface ocrBankCardResponse { + log_id: string; // 请求标识码,随机数,唯一。 + result: { // 返回结果 + bank_card_number: string; // 银行卡卡号 + bank_name: string; // 银行名,不能识别时为空 。 + bank_card_type: string; // 银行卡类型,0: 不能识别; 1: 借记卡; 2: 信用卡 。 + }; + } + interface ocrDrivingLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + interface ocrVehicleLicenseResponse { + log_id: string; // 唯一的log id,用于问题定位。 + words_result_num: number; // 识别结果数,表示 words_result 的元素个数。 + words_result: { + [key: string]: { words: string }; + }; + } + /** + * 用户向服务请求识别身份证,身份证识别包括正面和背面。 + */ + function ocrIdCard(options: ocrIdCardOptions): void; + /** + * 识别银行卡并返回卡号、发卡行和卡片类型。 + */ + function ocrBankCard(options: ocrBankCardOptions): void; + /** + * 对机动车驾驶证所有关键字段进行识别。 + */ + function ocrDrivingLicense(options: ocrDrivingLicenseOptions): void; + /** + * 对机动车行驶证正本所有关键字段进行识别 + */ + function ocrVehicleLicense(options: ocrVehicleLicenseOptions): void; + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + interface textReviewOptions extends BaseOptions { + content: string; // 待审核文本,UTF-8,不可为空,不超过20000字节。 + success?(res: textReviewResponse): void; + } + interface textReviewResponse { + log_id: string; // 唯一的log id,用于问题定位。 + result: { // 审核结果详情 + spam: number; // 请求中是否包含违禁,0表示非违禁,1表示违禁,2表示建议人工复审 。 + reject: any[]; // 审核未通过的类别列表与详情 + review: any[]; // 待人工复审的类别列表与详情 + pass: Array<{ // 审核通过的类别列表与详情 + label: number; // 请求中的违禁类型 + score: number; // 违禁检测分,范围 0~1,数值从低到高代表风险程度的高低 。 + hit: string[]; // 违禁类型对应命中的违禁词集合,可能为空 。 + }>; + }; + /** + * 违禁labels类型说明: + * 值 说明 + * 1 暴恐违禁 + * 2 文本色情 + * 3 政治敏感 + * 4 恶意推广 + * 5 低俗辱骂 + */ + } + /** + * 运用业界领先的深度学习技术,判断一段文本内容是否符合网络发文规范,实现 + * 自动化、智能化的文本审核。 + */ + function textReview(options: textReviewOptions): void; + /** + * 将文本转换为可以播放的mp3文件。 + */ + interface textToAudioOptions extends BaseOptions { + tex: string; // 合成的文本,使用UTF-8编码,小于512个中文字或者英文数字(文本在百度服务器内转换为GBK后,长度必须小于1024字节)。 + ctp?: string | number; // 客户端类型选择,Web端填写固定值1。 + lan?: string; // 固定值zh。语言选择,目前只有中英文混合模式,填写固定值zh。 + spd?: string; // 语速,取值0-9,默认为5中语速。 + pit?: string; // 音调,取值0-9,默认为5中语调。 + vol?: string; // 音量,取值0-9,默认为5中音量。 + per?: string; // 发音人选择, 0为普通女声,1为普通男生,3为情感合成-度逍遥,4为情感合成-度丫丫,默认为普通女声。 + success?(res: textToAudioResponse): void; + } + interface textToAudioResponse { + filePath: string; + } + /** + * 将文本转换为可以播放的mp3文件。 + */ + function textToAudio(options: textToAudioOptions): void; + /** + * 自定义图像审核。 + */ + interface imageAuditOptions extends BaseOptions { + image: string; // 图像资源地址 + imgUrl?: string; // 网图URL地址,以网图形式请求,图片Url需要做UrlEncode,不能与image并存。 + success?(res: imageAuditResponse): void; + } + interface imageAuditResponse { + log_id: string; // 请求唯一id + conclusion: string; // 审核结果描述,成功才返回,失败不返回。 + conclusionType: number; // 审核结果标识,成功才返回,失败不返回。 + data: imageAuditdata[]; + // 审核项详细信息,响应成功并且conclusion为疑似或不合规时才返回,响应失败或conclusion为合规是不返回。 + } + interface imageAuditdata { + type: number; + msg: number; + probability: number; + stars: imageAuditdata[]; + words: number; + } + /** + * 自定义图像审核。 + */ + function imageAudit(options: imageAuditOptions): void; + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + interface GeneralIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: GeneralIdentifyResponse): void; + } + interface GeneralIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 标签结果数组 + keyword: string; // 图片中的物体或场景名称 + score: number; // 置信度,0-1 + root: string; // 识别结果的上层标签,有部分钱币、动漫、烟酒等tag无上层标签。 + }>; + } + /** + * 通用物体及场景识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图片中的多个物体及场景标签。 + */ + function advancedGeneralIdentify(options: GeneralIdentifyOptions): void; + /** + * 用户向服务请求检测图像中的主体位置。 + */ + interface DetectIdentifyOptions extends BaseOptions { + image: string; // 图像资源地址 + with_face?: number; // 如果检测主体是人,主体区域是否带上人脸部分,0-不带人脸区域,其他-带人脸区域,裁剪类需求推荐带人脸,检索/识别类需求推荐不带人脸。默认取1,带人脸。 + success?(res: DetectIdentifyResponse): void; + } + interface DetectIdentifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: { // 裁剪结果 + left: number; // 表示定位位置的长方形左上顶点的水平坐标。 + top: number; // 表示定位位置的长方形左上顶点的垂直坐标。 + width: number; // 表示定位位置的长方形的宽度。 + height: number; // 表示定位位置的长方形的高度。 + }; + } + /** + * 用户向服务请求检测图像中的主体位置。 + */ + function objectDetectIdentify(options: DetectIdentifyOptions): void; + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + interface carClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + color_result?: string; // 颜色 + top_num?: number; // 返回结果top n,默认5。 + success?(res: carClassifyResponse): void; + } + interface carClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ + name: string; // 车型名称,示例:宝马x6 + score: number; // 置信度,示例:0.5321 + year: string; // 年份 + }>; + location_result: { // 车在图片中的位置信息 + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; + } + /** + * 用于检测一张车辆图片的具体车型,即对于输入的一张图片(可正常解码,且长 + * 宽比适宜),输出图片的车辆品牌及型号、颜色及年份、位置信息。 + */ + function carClassify(options: carClassifyOptions): void; + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + interface dishClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + filter_threshold?: number; // 默认0.95,可以通过该参数调节识别效果,降低非菜识别率. + top_num?: number; // 返回结果top n,默认5。 + success?(res: dishClassifyResponse): void; + } + interface dishClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 返回结果数目,及result数组中的元素个数。 + result: Array<{ // 菜品识别结果数组 + name: string; // 菜名,示例:鱼香肉丝。 + calorie: number; // 卡路里,每100g的卡路里含量。 + probability: number; // 识别结果中每一行的置信度值,0-1。 + }>; + } + /** + * 用于菜品识别,即对于输入的一张图片(可正常解码,且长宽比适宜),输出图 + * 片的菜品名称、卡路里信息、置信度。 + */ + function dishClassify(options: dishClassifyOptions): void; + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + interface logoClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + custom_lib?: boolean; // 是否只检索用户子库,true则只检索用户子库,false(默认)为检索底库+用户子库。 + success?(res: logoClassifyResponse): void; + } + interface logoClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + type: number; // type=0 为1千种高优商标识别结果;type=1 为2万类logo库的结果;其它type为自定义logo库结果。 + name: number; // 识别的品牌名称 + probability: number; // 分类结果置信度(0–1.0) + location: { + left: number; // 左起像素位置 + top: number; // 上起像素位置 + width: number; // 像素宽 + height: number; // 像素高 + }; // 位置信息(左起像素位置、上起像素位置、像素宽、像素高) + }>; + } + /** + * 用于检测和识别图片中的品牌 LOGO 信息 + */ + function logoClassify(options: logoClassifyOptions): void; + /** + * 用于检测和识别图片中的动物信息 + */ + interface animalClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + top_num?: number; // 返回预测得分top结果数,默认为6 + success?(res: animalClassifyResponse): void; + } + interface animalClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result_num: number; // 识别结果数,标识返回结果数目。 + result: Array<{ // 菜品识别结果数组 + name: number; // 动物名称,示例:蒙古马。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的动物信息 + */ + function animalClassify(options: animalClassifyOptions): void; + /** + * 用于检测和识别图片中的植物信息 + */ + interface plantClassifyOptions extends BaseOptions { + image: string; // 图像资源地址 + success?(res: plantClassifyResponse): void; + } + interface plantClassifyResponse { + log_id: number; // 唯一的log id,用于问题定位。 + result: Array<{ // 菜品识别结果数组 + name: number; // 植物名称,示例:吉娃莲。 + score: number; // 置信度,示例:0.5321。 + }>; + } + /** + * 用于检测和识别图片中的植物信息 + */ + function plantClassify(options: plantClassifyOptions): void; + + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + interface VoiceRecognizerStart { + mode?: string; // 听音模式,有效值dnn/touch + longSpeech?: boolean; // 是否开启长语音 + context?: string; // 语音识别所用的场景值,有效值见下表格。 + } + interface VoiceRecognizeResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceErrorResponse { + result: string; // 小程序语音识别过程中的返回内容 + } + interface VoiceRecognizerTask { + start(options: VoiceRecognizerStart): void; // 开始; + stop(): void; // 停止; + cancel(): void; // 取消; + onStart(callback: () => void): void; // 引擎准备就绪,可以开始说话; + onRecognize(callback: (res: VoiceRecognizeResponse) => void): void; // ;有识别结果返回 + onFinish(callback: (res: DataResponse) => void): void; // 识别完成; + onError(callback: (res: VoiceErrorResponse) => void): void; // 识别遇到错;误 + } + /** + * 获取全局唯一的语音识别器voiceRecognizer。 + */ + function getVoiceRecognizer(): VoiceRecognizerTask; + } + // #endregion + + // #endregion + // #region 媒体API列表 + // 媒体-----图片 + type ImageSizeType = "original" | "compressed"; + type ImageSourceType = "album" | "camera"; + type VideoSourceType = "album" | "camera"; + type CameraDevice = "front" | "back"; + interface TempFile { + /** 本地文件路径 */ + path: string; + /** 本地文件大小,单位:B */ + size: number; + } + interface TempFilesData { + /** 文件的临时路径 */ + tempFilePaths: string; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + * @version 1.2.0 + */ + tempFiles: TempFile[]; + } + interface ChooseImageOptions extends BaseOptions { + /** 最多可以选择的图片张数,默认9 */ + count?: number; + /** original 原图,compressed 压缩图,默认二者都有 */ + sizeType?: ImageSizeType[]; + /** album 从相册选图,camera 使用相机,默认二者都有 */ + sourceType?: ImageSourceType[]; + /** 成功则返回图片的本地文件路径列表 tempFilePaths */ + success(res: TempFilesData): void; + } + /** + * 从本地相册选择图片或使用相机拍照。 + */ + function chooseImage(options: ChooseImageOptions): void; + interface PreviewImageOptions extends BaseOptions { + /** 当前显示图片的链接,不填则默认为 urls 的第一张 */ + current?: string; + /** 需要预览的图片链接列表 */ + urls: string[]; + } + /** + * 预览图片。 + */ + function previewImage(options: PreviewImageOptions): void; + interface GetImageInfoOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src: string; + } + /** + * 获取图片信息 + */ + function getImageInfo(options: GetImageInfoOptions): void; + interface SaveImageToPhotosAlbumOptions extends BaseOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + filePath: string; + success(res: { errMsg: string }): void; + } + /** + * 保存图片到系统相册。 + * 需要用户授权 scope.writePhotosAlbum + * @version 1.2.0 + */ + function saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + // 媒体-----录音 + interface StartRecordAudioOptions extends BaseOptions { + /** 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} */ + success?(res: TempFileResponse): void; + } + /** + * 开始录音。当主动调用swan.stopRecord, + * 或者录音超过1分钟时自动结束录音,返回录音文件的临时文件路径。 + * 注:文件的临时路径,在小程序本次启动期间可以正常使用, + * 如需持久保存,需在主动调用swan.saveFile,在小程序下次启动时才能访问得到。 + * @deprecated 1.6.0 + */ + function startRecord(options: StartRecordAudioOptions): void; + + interface StopRecordAudioOptions extends BaseOptions { + success?(res: TempFileResponse): void; + } + /** + * 主动调用停止录音。 + */ + function stopRecord(options?: StopRecordAudioOptions): void; + type EncodeBitRate = + | 8000 + | 11025 + | 12000 + | 16000 + | 22050 + | 24000 + | 32000 + | 44100 + | 48000; + interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms + * 如果传入了合法的 duration + * 在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 否 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率 + * 采样率和码率有一定要求,具体有效值如下: + * 采样率 编码码率 + * + 8000 16000 ~ 48000 + * + 11025 16000 ~ 48000 + * + 12000 24000 ~ 64000 + * + 16000 24000 ~ 96000 + * + 22050 32000 ~ 128000 + * + 24000 32000 ~ 128000 + * + 32000 48000 ~ 192000 + * + 44100 64000 ~ 320000 + * + 48000 64000 ~ 320000 + */ + encodeBitRate: number; + /** 音频格式,有效值 aac/mp3 */ + format: string; + } + interface OnRecorderManagerStopOptions { + tempFilePath: string; + } + interface OnFrameRecordedOptions { + /** 录音分片结果数据 */ + frameBuffer: ArrayBuffer; + /** 当前帧是否正常录音结束前的最后一帧 */ + isLastFrame: boolean; + } + interface RecorderManager { + /** 开始录音 */ + start(options?: RecorderManagerStartOptions): void; + /** 暂停录音 */ + pause(): void; + /** 继续录音 */ + resume(): void; + /** 停止录音 */ + stop(): void; + /** 录音开始事件 */ + onStart(callback?: () => void): void; + /** 录音暂停事件 */ + onPause(callback?: () => void): void; + /** 录音恢复事件 */ + onResume(callback?: () => void): void; + /** 录音停止事件,会回调文件地址 */ + onStop(callback?: (options: OnRecorderManagerStopOptions) => void): void; + /** 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 */ + onFrameRecorded(callback?: (options: OnFrameRecordedOptions) => void): void; + /** 录音错误事件, 会回调错误信息 */ + onError(callback?: (err: ErrMsgResponse) => void): void; + } + /** + * 获取全局唯一的录音管理器 recorderManager + * @version 1.6.0 + */ + function getRecorderManager(): RecorderManager; + // 媒体-----音频播放控制 + interface PlayVoiceOptions extends BaseOptions { + /** 需要播放的语音文件的文件路径 */ + filePath: string; + } + /** + * 开始播放语音,同时只允许一个语音文件正在播放, + * 如果前一个语音文件还没播放完,将中断前一个语音播放。 + * @deprecated 1.6.0 + */ + function playVoice(options: PlayVoiceOptions): void; + /** + * 暂停正在播放的语音。 + * 再次调用swan.playVoice播放同一个文件时,会从暂停处开始播放。 + * 如果想从头开始播放,需要先调用 swan.stopVoice。 + * @deprecated 1.6.0 + */ + function pauseVoice(): void; + /** + * 结束播放语音。 + * @deprecated 1.6.0 + */ + function stopVoice(): void; + // 媒体-----音乐播放控制 + interface BackgroundAudioPlayerState { + /** 选定音频的长度(单位:s),只有在当前有音乐播放时返回 */ + duration: number; + /** 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 */ + currentPosition: number; + /** 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) */ + status: number; + /** 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 */ + downloadPercent: number; + /** 歌曲数据链接,只有在当前有音乐播放时返回 */ + dataUrl: string; + } + interface GetBackgroundAudioPlayerStateOptions extends BaseOptions { + /** 接口调用成功的回调函数 */ + success?(state: BackgroundAudioPlayerState): void; + /** 接口调用失败的回调函数 */ + fail?(): void; + /** 接口调用结束的回调函数(调用成功、失败都会执行) */ + complete?(): void; + } + /** + * 获取音乐播放状态。 + * @deprecated 1.2.0 + */ + function getBackgroundAudioPlayerState( + options: GetBackgroundAudioPlayerStateOptions + ): void; + interface PlayBackgroundAudioOptions extends BaseOptions { + /** 音乐链接 */ + dataUrl: string; + /** 音乐标题 */ + title?: string; + /** 封面URL */ + coverImgUrl?: string; + } + /** + * 播放音乐,同时只能有一首音乐正在播放。 + * @deprecated 1.2.0 + */ + function playBackgroundAudio(options: PlayBackgroundAudioOptions): void; + /** + * 暂停播放音乐。 + * @deprecated 1.2.0 + */ + function pauseBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + interface SeekBackgroundAudioOptions extends BaseOptions { + /** 音乐位置,单位:秒 */ + position: number; + } + /** + * 控制音乐播放进度。 + * @deprecated 1.2.0 + */ + function seekBackgroundAudio(options: SeekBackgroundAudioOptions): void; + /** + * 停止播放音乐。 + * @deprecated 1.2.0 + */ + function stopBackgroundAudio(options?: PlayBackgroundAudioOptions): void; + /** + * 监听音乐播放。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPlay(callback: () => void): void; + /** + * 监听音乐暂停。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioPause(callback: () => void): void; + /** + * 监听音乐停止。 + * @deprecated 1.2.0 + */ + function onBackgroundAudioStop(callback: () => void): void; + interface BackgroundAudioManager { + /** 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 */ + readonly duration: number; + /** 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 */ + readonly currentTime: number; + /** 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 */ + readonly paused: boolean; + /** 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav */ + src?: string; + /** 音频开始播放的位置(单位:s) */ + startTime?: number; + /** 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲。 是 */ + buffered: number; + /** 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 */ + title?: string; + /** 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + epname?: string; + /** 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 */ + singer?: string; + /** 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 */ + coverImgUrl?: string; + /** 播放 */ + play(): void; + /** 暂停 */ + pause(): void; + /** 停止 */ + stop(): void; + /** 跳转到指定位置,单位 s */ + seek(position: number): void; + /** 背景音频进入可以播放状态,但不保证后面可以流畅播放 */ + onCanplay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放事件 */ + onPlay(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频暂停事件 */ + onPause(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频停止事件 */ + onStop(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频自然播放结束事件 */ + onEnded(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放进度更新事件 */ + onTimeUpdate(callback: (res: ErrCodeResponse) => void): void; + /** 背景音频播放错误事件 */ + onError(callback: (res: ErrCodeResponse) => void): void; + /** 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 */ + onWaiting(callback: (res: ErrCodeResponse) => void): void; + } + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager。 + * @version 1.2.0 + */ + function getBackgroundAudioManager(): BackgroundAudioManager; + // 媒体-----音频组件控制 + /** + * audioContext 通过 audioId 跟一个

', + title: "", + trigger: "hover focus", + viewport: { selector: "body", padding: 0 }, +}); + +$("#element").tooltip({ + container: "body", +}); + +$("#element").tooltip({ + delay: { show: 500, hide: 100 }, +}); + +$("#element").tooltip({ + placement() { return "top"; }, +}); + +$("#element").tooltip({ + placement(tooltip: HTMLElement, trigger: Element) { + console.log(this.options.delay); + return "top"; + }, +}); + +$("#element").tooltip({ + placement(tooltip: HTMLElement, trigger: Element) { + // $ExpectError + console.log(this.options.content); // only for PopoverOption, not TooltipOption + return "top"; + }, +}); + +$("#element").tooltip({ + title() { return this.id; }, +}); + +$("#element").tooltip({ + viewport: "body", +}); + +// -------------------------------------------------------------------------------------- +// Popover +// -------------------------------------------------------------------------------------- + +$("#element").popover(); + +$("#element").popover("show"); + +$("#element").popover({ + animation: true, + container: false, + content: "content", + delay: 0, + html: false, + placement: "top", + selector: ".selector", + template: '', + title: "", + trigger: "hover focus", + viewport: { selector: "body", padding: 0 }, +}); + +$("#element").popover({ + container: "body", +}); + +$("#element").popover({ + content() { return `Elem id: ${this.id}`; }, +}); + +$("#element").popover({ + delay: { show: 500, hide: 100 }, +}); + +$("#element").popover({ + placement() { return "top"; }, +}); + +$("#element").popover({ + placement(tooltip: HTMLElement, trigger: Element) { + console.log(this.options.content); + return "top"; + }, +}); + +$("#element").popover({ + title() { return `Elem id: ${this.id}`; }, +}); + +$("#element").popover({ + viewport: "body", +}); + +// -------------------------------------------------------------------------------------- +// Alert +// -------------------------------------------------------------------------------------- $(".alert").alert(); -$(".alert").alert('close'); -$('.nav-tabs').button(); -$().button('toggle'); +$(".alert").alert("close"); + +// -------------------------------------------------------------------------------------- +// Button +// -------------------------------------------------------------------------------------- + +$(".btn").button(); + +$(".btn").button("toggle"); + +$(".btn").button("reset"); + +$(".btn").button("Swaps text to any data defined text state."); + +// -------------------------------------------------------------------------------------- +// Collapse +// -------------------------------------------------------------------------------------- $(".collapse").collapse(); -$('#myCollapsible').collapse({ toggle: false }); +$(".collapse").collapse("toggle"); -$('.carousel').carousel(); -$('.carousel').carousel({ interval: 2000 }); - -$('.typeahead').typeahead({ - matcher: item => true, - sorter: (items: any[]) => items, - updater: item => item, - highlighter: item => "" +$(".collapse").collapse({ + parent: "#selector", + toggle: false, }); -$('#navbar').affix(); +// -------------------------------------------------------------------------------------- +// Carousel +// -------------------------------------------------------------------------------------- -$('.item').emulateTransitionEnd(2000); +$(".carousel").carousel(); + +$(".carousel").carousel("cycle"); + +$(".carousel").carousel(200); + +$(".carousel").carousel({ + interval: 2000, + pause: "hover", + wrap: true, + keyboard: false, +}); + +$(".carousel").carousel({ + interval: false, +}); + +$(".carousel").carousel({ + pause: null, +}); + +// -------------------------------------------------------------------------------------- +// Affix +// -------------------------------------------------------------------------------------- + +$(".affix").affix(); + +$(".affix").affix("checkPosition"); + +$(".affix").affix({ + offset: 10, + target: window, +}); + +$(".affix").affix({ + offset: { top: 10, bottom: 5 }, +}); + +$(".affix").affix({ + offset: { top: 10 }, +}); + +$(".affix").affix({ + offset: { bottom: () => 10 }, +}); + +$(".affix").affix({ + offset: { + top: 100, + bottom() { + const that = this as BootstrapOffset; + return (that.bottom = $(".footer").outerHeight(true)!); + }, + } +}); + +$(".affix").affix({ + target: ".selector", +}); + +$(".affix").affix({ + target: document.getElementById("id")!, +}); + +$(".affix").affix({ + target: $("#id"), +}); + +// -------------------------------------------------------------------------------------- +// Transition +// -------------------------------------------------------------------------------------- + +$(".item").emulateTransitionEnd(2000); $.support.transition = false; -console.log(($.support.transition as any as TransitionEventNames).end === "transitionend"); + +console.log(($.support.transition as TransitionEventNames).end === "transitionend"); diff --git a/types/bootstrap/v3/index.d.ts b/types/bootstrap/v3/index.d.ts index 06142cc1d1..a6ddbeb1f8 100644 --- a/types/bootstrap/v3/index.d.ts +++ b/types/bootstrap/v3/index.d.ts @@ -1,21 +1,49 @@ -// Type definitions for Bootstrap 3.3.5 +// Type definitions for Bootstrap 3.3 // Project: http://twitter.github.com/bootstrap/ // Definitions by: Boris Yankov +// denisname // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 - /// -interface ModalOptions { - backdrop?: boolean|string; - keyboard?: boolean; - show?: boolean; - remote?: string; +// -------------------------------------------------------------------------- +// Some Types and Interfaces +// -------------------------------------------------------------------------- + +type BootstrapPlacement = "auto" | "top" | "bottom" | "left" | "right"; + +type BootstrapTrigger = "click" | "hover" | "focus" | "manual" | + "click hover" | "click focus" | "hover focus" | + "click hover focus"; + +type BootstrapDynamicOffset = (elem: JQuery) => number; + +interface BootstrapDelay { + show?: number; + hide?: number; } -interface ModalOptionsBackdropString { - backdrop?: string; // for "static" +interface BootstrapOffset { + top?: number | BootstrapDynamicOffset; + bottom?: number | BootstrapDynamicOffset; +} + +interface BootstrapViewport { + padding?: number; + selector: string; +} + +interface TooltipInstance { + options: T; +} + +// -------------------------------------------------------------------------------------- +// Options Interfaces +// -------------------------------------------------------------------------------------- + +interface ModalOptions { + backdrop?: boolean | "static"; keyboard?: boolean; show?: boolean; remote?: string; @@ -28,103 +56,83 @@ interface ScrollSpyOptions { interface TooltipOptions { animation?: boolean; + container?: string | false; + delay?: number | BootstrapDelay; html?: boolean; - placement?: string | Function; + placement?: BootstrapPlacement | ((this: TooltipInstance, tooltip: HTMLElement, trigger: Element) => BootstrapPlacement); selector?: string; - title?: string | Function; - trigger?: string; template?: string; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; + title?: string | ((this: Element) => string); + trigger?: BootstrapTrigger; + viewport?: string | BootstrapViewport; } -interface PopoverOptions { - animation?: boolean; - html?: boolean; - placement?: string | Function; - selector?: string; - trigger?: string; - title?: string | Function; - template?: string; - content?: any; - delay?: number | Object; - container?: string | boolean; - viewport?: string | Function | Object; +interface PopoverOptions extends TooltipOptions { + content?: string | ((this: Element) => string); } interface CollapseOptions { - parent?: any; + parent?: string | false; toggle?: boolean; } interface CarouselOptions { - interval?: number; - pause?: string; + interval?: number | false; + pause?: "hover" | null; wrap?: boolean; keyboard?: boolean; } -interface TypeaheadOptions { - source?: any; - items?: number; - minLength?: number; - matcher?: (item: any) => boolean; - sorter?: (items: any[]) => any[]; - updater?: (item: any) => any; - highlighter?: (item: any) => string; +interface AffixOptions { + offset?: number | BootstrapOffset; + target?: string | Node | JQuery | Window; } -interface AffixOptions { - offset?: number | Function | Object; - target?: any; +// -------------------------------------------------------------------------------------- +// jQuery +// -------------------------------------------------------------------------------------- + +interface JQuery { + modal(action?: "toggle" | "show" | "hide" | "handleUpdate"): JQuery; + modal(options: ModalOptions): JQuery; + + dropdown(action?: "toggle"): JQuery; + + scrollspy(action?: "refresh"): JQuery; + scrollspy(options: ScrollSpyOptions): JQuery; + + tab(action?: "show"): JQuery; + + tooltip(action?: "show" | "hide" | "toggle" | "destroy"): JQuery; + tooltip(options: TooltipOptions): JQuery; + + popover(action?: "show" | "hide" | "toggle" | "destroy"): JQuery; + popover(options: PopoverOptions): JQuery; + + alert(action?: "close"): JQuery; + + button(action?: "toggle" | "reset" | string): JQuery; + + collapse(action?: "toggle" | "show" | "hide"): JQuery; + collapse(options: CollapseOptions): JQuery; + + carousel(action?: "cycle" | "pause" | number | "prev" | "next"): JQuery; + carousel(options: CarouselOptions): JQuery; + + affix(action?: "checkPosition"): JQuery; + affix(options: AffixOptions): JQuery; + + emulateTransitionEnd(duration: number): JQuery; } +// -------------------------------------------------------------------------------------- +// Other +// -------------------------------------------------------------------------------------- + interface TransitionEventNames { end: string; } -interface JQuery { - modal(options?: ModalOptions): JQuery; - modal(options?: ModalOptionsBackdropString): JQuery; - modal(command: string, relatedTarget?: Element): JQuery; - - dropdown(): JQuery; - dropdown(command: string): JQuery; - - scrollspy(command: string): JQuery; - scrollspy(options?: ScrollSpyOptions): JQuery; - - tab(): JQuery; - tab(command: string): JQuery; - - tooltip(options?: TooltipOptions): JQuery; - tooltip(command: string): JQuery; - - popover(options?: PopoverOptions): JQuery; - popover(command: string): JQuery; - - alert(): JQuery; - alert(command: string): JQuery; - - button(): JQuery; - button(command: string): JQuery; - - collapse(options?: CollapseOptions): JQuery; - collapse(command: string): JQuery; - - carousel(options?: CarouselOptions): JQuery; - carousel(command: string): JQuery; - carousel(index: number): JQuery; - - typeahead(options?: TypeaheadOptions): JQuery; - - affix(options?: AffixOptions): JQuery; - affix(command: string): JQuery; - - emulateTransitionEnd(duration: number): JQuery; -} - interface JQuerySupport { transition: boolean | TransitionEventNames; } diff --git a/types/bootstrap/v3/tsconfig.json b/types/bootstrap/v3/tsconfig.json index 585af4f8b2..38477cd68e 100644 --- a/types/bootstrap/v3/tsconfig.json +++ b/types/bootstrap/v3/tsconfig.json @@ -7,7 +7,7 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, + "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../../", "typeRoots": [ diff --git a/types/bootstrap/v3/tslint.json b/types/bootstrap/v3/tslint.json index a41bf5d19a..075fa88707 100644 --- a/types/bootstrap/v3/tslint.json +++ b/types/bootstrap/v3/tslint.json @@ -1,79 +1,6 @@ { "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 + "no-single-declare-module": false } } diff --git a/types/bootstrap3-dialog/tsconfig.json b/types/bootstrap3-dialog/tsconfig.json index cdf93479b7..774e895668 100644 --- a/types/bootstrap3-dialog/tsconfig.json +++ b/types/bootstrap3-dialog/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/braintree-web/index.d.ts b/types/braintree-web/index.d.ts index bc5ca0b01f..a2cfdb06c1 100644 --- a/types/braintree-web/index.d.ts +++ b/types/braintree-web/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/braintree/braintree-web // Definitions by: Guy Shahine // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * @module braintree-web/american-express @@ -359,7 +360,8 @@ declare namespace braintree { * }); * @static */ - create: (options: { authorization: string }, callback: callback) => void; + create(options: { authorization: string }): Promise; + create(options: { authorization: string }, callback: callback): void; /** * @description The current version of the SDK, i.e. `3.0.2`. @@ -439,7 +441,8 @@ declare namespace braintree { * @param {callback} callback The second argument, `data`, is the {@link DataCollector} instance. * @returns {void} */ - create: (options: { client: Client, kount: boolean, paypal: boolean }, callback: callback) => void; + create(options: { client: Client, kount: boolean, paypal: boolean }): Promise; + create(options: { client: Client, kount: boolean, paypal: boolean }, callback: callback): void; /** * @description The current version of the SDK, i.e. `3.0.2`. @@ -591,18 +594,15 @@ declare namespace braintree { * @property {?HostedFields~hostedFieldsFieldData} fields.expirationYear {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the expiration year field, if it is present. * @property {?HostedFields~hostedFieldsFieldData} fields.postalCode {@link HostedFields~hostedFieldsFieldData|hostedFieldsFieldData} for the postal code field, if it is present. */ - interface HostedFieldsFieldDataFields { - number: HostedFieldsHostedFieldsFieldData; - cvv: HostedFieldsHostedFieldsFieldData; - expirationDate: HostedFieldsHostedFieldsFieldData; - expirationMonth: HostedFieldsHostedFieldsFieldData; - expirationYear: HostedFieldsHostedFieldsFieldData; - postalCode: HostedFieldsHostedFieldsFieldData; - } + type HostedFieldsHostedFieldsFieldName = 'number' | 'cvv' | 'expirationDate' | 'expirationMonth' | 'expirationYear' | 'postalCode'; + + type HostedFieldsFieldDataFields = { + [key in HostedFieldsHostedFieldsFieldName]: HostedFieldsHostedFieldsFieldData; + }; interface HostedFieldsStateObject { cards: HostedFieldsHostedFieldsCard[]; - emittedBy: string; + emittedBy: HostedFieldsHostedFieldsFieldName; fields: HostedFieldsFieldDataFields; } @@ -666,7 +666,8 @@ declare namespace braintree { * } * }, callback); */ - create: (options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback) => void; + create(options: { client: Client, fields: HostedFieldFieldOptions, styles: any }): Promise; + create(options: { client: Client, fields: HostedFieldFieldOptions, styles: any }, callback: callback): void; /** @@ -726,7 +727,7 @@ declare namespace braintree { * }); * @returns {void} */ - on(event: string, handler: ((event: any) => any)): void; + on(event: string, handler: ((event: HostedFieldsStateObject) => void)): void; /** * Cleanly tear down anything set up by {@link module:braintree-web/hosted-fields.create|create} @@ -785,7 +786,9 @@ declare namespace braintree { * }); * @returns {void} */ - tokenize(options?: { vault: boolean }, callback?: callback): void; + tokenize(options?: { vault?: boolean, cardholderName?: string, billingAddress?: any }): Promise; + tokenize(options: { vault?: boolean, cardholderName?: string, billingAddress?: any }, callback: callback): void; + tokenize(callback: callback): void; /** * Add a class to a {@link module:braintree-web/hosted-fields~field field}. Useful for updating field styles when events occur elsewhere in your checkout. @@ -1138,7 +1141,8 @@ declare namespace braintree { * client: client * }, callback); */ - create: (options: { client: Client }, callback: callback) => void; + create(options: { client: Client }): Promise; + create(options: { client: Client }, callback: callback): void; /** * @description The current version of the SDK, i.e. `3.0.2`. @@ -1207,6 +1211,7 @@ declare namespace braintree { * } * }); */ + verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame?: () => void }): Promise; verifyCard(options: { nonce: string, amount: number, addFrame: (err?: BraintreeError, iframe?: HTMLIFrameElement) => void, removeFrame: () => void }, callback: callback): void; /** @@ -1751,3 +1756,4 @@ declare namespace braintree { export = braintree; export as namespace braintree; + diff --git a/types/braintree-web/test/node.ts b/types/braintree-web/test/node.ts index 9eed5b228d..59db2fb944 100644 --- a/types/braintree-web/test/node.ts +++ b/types/braintree-web/test/node.ts @@ -6,7 +6,7 @@ let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiO braintree.client.create({ authorization: clientToken -}, function (error: braintree.BraintreeError, clientInstance: any) { +}, function (error: braintree.BraintreeError, clientInstance: braintree.Client) { var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; var data: { creditCard: braintree.CreditCardInfo } = { @@ -396,7 +396,7 @@ let submitNonceToServer: (nonce: string) => void; braintree.threeDSecure.verifyCard({ nonce: existingNonce, - amount: 123.45, + amount: 123.45, // $ExpectType number addFrame: function (err, iframe) { // Set up your UI and add the iframe. let my3DSContainer = document.createElement('div'); @@ -437,4 +437,4 @@ braintree.threeDSecure.cancelVerifyCard(function (err: braintree.BraintreeError, verifyPayload.nonce; // The nonce returned from the 3ds lookup call verifyPayload.liabilityShifted; // boolean verifyPayload.liabilityShiftPossible; // boolean -}); +}); \ No newline at end of file diff --git a/types/braintree-web/test/web.ts b/types/braintree-web/test/web.ts index 22073363d4..1801cbb497 100644 --- a/types/braintree-web/test/web.ts +++ b/types/braintree-web/test/web.ts @@ -1,10 +1,13 @@ +import { ApplePay } from ".."; +import * as braintree from ".."; + let version: string = braintree.VERSION; let clientToken: string = "eyJ2ZXJzaW9uIjoyLCJhdXRob3JpemF0aW9uRmluZ2VycHJpbnQiOiI0YjlhYzVmYmI4ZTNkYzQzMmFkZjJhNzBlNjZlMWNjY2M5ODRkYzE4ZTM4YmY4NjYzZTM5NjM3NWZjYmQzY2U5fGNyZWF0ZWRfYXQ9MjAxNi0wOS0wOFQwNTowMzo0MC4xNjk1NTUwMzUrMDAwMFx1MDAyNm1lcmNoYW50X2lkPTM0OHBrOWNnZjNiZ3l3MmJcdTAwMjZwdWJsaWNfa2V5PTJuMjQ3ZHY4OWJxOXZtcHIiLCJjb25maWdVcmwiOiJodHRwczovL2FwaS5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tOjQ0My9tZXJjaGFudHMvMzQ4cGs5Y2dmM2JneXcyYi9jbGllbnRfYXBpL3YxL2NvbmZpZ3VyYXRpb24iLCJjaGFsbGVuZ2VzIjpbXSwiZW52aXJvbm1lbnQiOiJzYW5kYm94IiwiY2xpZW50QXBpVXJsIjoiaHR0cHM6Ly9hcGkuc2FuZGJveC5icmFpbnRyZWVnYXRld2F5LmNvbTo0NDMvbWVyY2hhbnRzLzM0OHBrOWNnZjNiZ3l3MmIvY2xpZW50X2FwaSIsImFzc2V0c1VybCI6Imh0dHBzOi8vYXNzZXRzLmJyYWludHJlZWdhdGV3YXkuY29tIiwiYXV0aFVybCI6Imh0dHBzOi8vYXV0aC52ZW5tby5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tIiwiYW5hbHl0aWNzIjp7InVybCI6Imh0dHBzOi8vY2xpZW50LWFuYWx5dGljcy5zYW5kYm94LmJyYWludHJlZWdhdGV3YXkuY29tLzM0OHBrOWNnZjNiZ3l3MmIifSwidGhyZWVEU2VjdXJlRW5hYmxlZCI6dHJ1ZSwicGF5cGFsRW5hYmxlZCI6dHJ1ZSwicGF5cGFsIjp7ImRpc3BsYXlOYW1lIjoiQWNtZSBXaWRnZXRzLCBMdGQuIChTYW5kYm94KSIsImNsaWVudElkIjpudWxsLCJwcml2YWN5VXJsIjoiaHR0cDovL2V4YW1wbGUuY29tL3BwIiwidXNlckFncmVlbWVudFVybCI6Imh0dHA6Ly9leGFtcGxlLmNvbS90b3MiLCJiYXNlVXJsIjoiaHR0cHM6Ly9hc3NldHMuYnJhaW50cmVlZ2F0ZXdheS5jb20iLCJhc3NldHNVcmwiOiJodHRwczovL2NoZWNrb3V0LnBheXBhbC5jb20iLCJkaXJlY3RCYXNlVXJsIjpudWxsLCJhbGxvd0h0dHAiOnRydWUsImVudmlyb25tZW50Tm9OZXR3b3JrIjp0cnVlLCJlbnZpcm9ubWVudCI6Im9mZmxpbmUiLCJ1bnZldHRlZE1lcmNoYW50IjpmYWxzZSwiYnJhaW50cmVlQ2xpZW50SWQiOiJtYXN0ZXJjbGllbnQzIiwiYmlsbGluZ0FncmVlbWVudHNFbmFibGVkIjp0cnVlLCJtZXJjaGFudEFjY291bnRJZCI6ImFjbWV3aWRnZXRzbHRkc2FuZGJveCIsImN1cnJlbmN5SXNvQ29kZSI6IlVTRCJ9LCJjb2luYmFzZUVuYWJsZWQiOmZhbHNlLCJtZXJjaGFudElkIjoiMzQ4cGs5Y2dmM2JneXcyYiIsInZlbm1vIjoib2ZmIn0="; braintree.client.create({ authorization: clientToken -}, function (error: braintree.BraintreeError, clientInstance: any) { +}, function (error: braintree.BraintreeError, clientInstance: braintree.Client) { var form: HTMLFormElement = document.getElementById('my-form-id') as HTMLFormElement; var data: { creditCard: braintree.CreditCardInfo } = { @@ -62,7 +65,7 @@ braintree.client.create({ select: true } } - }, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: any) { + }, function (hostedFieldsErr?: braintree.BraintreeError, hostedFieldsInstance?: braintree.HostedFields) { if (hostedFieldsErr) { // Handle error in Hosted Fields creation @@ -178,7 +181,7 @@ braintree.client.create({ }); }); - braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: any) { + braintree.applePay.create({ client: clientInstance }, function (createErr?: braintree.BraintreeError, applePayInstance?: ApplePay) { if (createErr) { // Handle error in client creation console.log(`Error Code: ${error.code}, Type: ${error.type}, Message: ${error.message}, Details: ${error.details}`); @@ -194,7 +197,7 @@ braintree.client.create({ total: { label: 'Your Label', amount: '10.00' }, }; - var paymentRequest = braintree.applePay.createPaymentRequest(request); + var paymentRequest = applePayInstance.createPaymentRequest(request); console.log(paymentRequest); // { total: { }, countryCode: 'US', currencyCode: 'USD', merchantCapabilities: [ ], supportedNetworks: [ ] } @@ -394,7 +397,7 @@ let submitNonceToServer: (nonce: string) => void; braintree.threeDSecure.verifyCard({ nonce: existingNonce, - amount: 123.45, + amount: 123.45, // $ExpectType number addFrame: function (err, iframe) { // Set up your UI and add the iframe. let my3DSContainer = document.createElement('div'); diff --git a/types/broccoli-plugin/broccoli-plugin-tests.ts b/types/broccoli-plugin/broccoli-plugin-tests.ts new file mode 100644 index 0000000000..4434fce10c --- /dev/null +++ b/types/broccoli-plugin/broccoli-plugin-tests.ts @@ -0,0 +1,46 @@ +import Plugin = require('broccoli-plugin'); + +declare function copySync(src: string, dest: string): void; +declare function setTimeout(callback: () => void, duration: number): void; + +class SlowItDown extends Plugin { + constructor(private readonly waitInMS: number) { + super([], { + annotation: `${waitInMS} ms`, + needsCache: false + }); + } + + async build() { + await new Promise(resolve => setTimeout(resolve, this.waitInMS)); + } +} + +class FileCopier extends Plugin { + constructor(inputNodes: Plugin.BroccoliNode[]) { + super(inputNodes, { + name: 'CopyFiles', + persistentOutput: true + }); + } + + build() { + for (const input of this.inputPaths) { + copySync(input, this.outputPath); + } + } + + getCallbackObject() { + return this; + } +} + +new FileCopier([ + new SlowItDown(5000), + 'src', + 'assets' +]); + +new Plugin(); // $ExpectError +new Plugin([{}]); // $ExpectError +new Plugin([], { foo: 'bar' }); // $ExpectError diff --git a/types/broccoli-plugin/index.d.ts b/types/broccoli-plugin/index.d.ts new file mode 100644 index 0000000000..36b1da65e2 --- /dev/null +++ b/types/broccoli-plugin/index.d.ts @@ -0,0 +1,78 @@ +// Type definitions for broccoli-plugin 1.3 +// Project: https://github.com/broccolijs/broccoli-plugin +// Definitions by: Dan Freeman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = BroccoliPlugin; + +declare namespace BroccoliPlugin { + type BroccoliNode = BroccoliPlugin | string; + + interface BroccoliPluginOptions { + /** + * The name of this plugin. Defaults to `this.constructor.name`. + */ + name?: string; + + /** + * A descriptive annotation. Useful for debugging, to tell multiple + * instances of the same plugin apart. + */ + annotation?: string; + + /** + * If `true`, the output directory is not automatically emptied between + * builds. Defaults to `false`. + */ + persistentOutput?: boolean; + + /** + * If `true`, a cache directory is created automatically and the path is + * set at `cachePath`. If `false`, a cache directory is not created and + * `this.cachePath` is `undefined`. Defaults to `true`. + */ + needsCache?: boolean; + } +} + +declare class BroccoliPlugin { + constructor(inputNodes: BroccoliPlugin.BroccoliNode[], options?: BroccoliPlugin.BroccoliPluginOptions); + + /** + * An array of paths on disk corresponding to each node in `inputNodes`. + * Your plugin will read files from these paths. + */ + readonly inputPaths: ReadonlyArray; + + /** + * The path on disk corresponding to this plugin instance (this node). + * Your plugin will write files to this path. This directory is emptied by + * Broccoli before each build, unless the `persistentOutput` options is + * `true`. + */ + readonly outputPath: string; + + /** + * The path on disk to an auxiliary cache directory. Use this to store + * files that you want preserved between builds. This directory will + * only be deleted when Broccoli exits. If a cache directory is not + * needed, set `needsCache` to false when calling `broccoli-plugin` + * constructor. + */ + readonly cachePath?: string; + + /** + * Override this method in your subclass. It will be called on each + * (re-)build. All paths stay the same between builds. + * To perform asynchronous work, return a promise. + */ + build(): void | Promise; + + /** + * Advanced usage only. + * Return the object on which Broccoli will call `obj.build()`. Called + * once after instantiation. By default, returns `this`. + */ + getCallbackObject(): { build(): void | Promise }; +} diff --git a/types/broccoli-plugin/tsconfig.json b/types/broccoli-plugin/tsconfig.json new file mode 100644 index 0000000000..0f36813dc1 --- /dev/null +++ b/types/broccoli-plugin/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", + "broccoli-plugin-tests.ts" + ] +} diff --git a/types/broccoli-plugin/tslint.json b/types/broccoli-plugin/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/broccoli-plugin/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/browserslist/browserslist-tests.ts b/types/browserslist/browserslist-tests.ts new file mode 100644 index 0000000000..d5e88e5b5d --- /dev/null +++ b/types/browserslist/browserslist-tests.ts @@ -0,0 +1,22 @@ +import browserslist from "browserslist"; + +browserslist(); // $ExpectType string[] +browserslist(""); // $ExpectType string[] +browserslist([""]); // $ExpectType string[] + +const opts: browserslist.Options[] = [ + {}, + { path: "" }, + { env: "" }, + { stats: { "": { "": 0 } } }, + { config: "" }, + { ignoreUnknownVersions: false }, + { dangerousExtend: false } +]; +for (const opt of opts) { + browserslist("", opt); // $ExpectType string[] + browserslist([""], opt); // $ExpectType string[] +} + +browserslist.coverage([""]); // $ExpectType number +browserslist.coverage([""], { "": { "": 0 } }); // $ExpectType number diff --git a/types/browserslist/index.d.ts b/types/browserslist/index.d.ts new file mode 100644 index 0000000000..7c4a0add0c --- /dev/null +++ b/types/browserslist/index.d.ts @@ -0,0 +1,34 @@ +// Type definitions for browserslist 4.3 +// Project: https://github.com/browserslist/browserslist#readme +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +declare namespace browserslist { + interface Browserslist { + (queries?: string | ReadonlyArray, opts?: Options): string[]; + + coverage: (browsers: ReadonlyArray, stats?: Stats) => number; + + clearCaches: () => void; + } + + interface Stats { + [browser: string]: { + [version: string]: number; + }; + } + + interface Options { + path?: string; + env?: string; + stats?: Stats; + config?: string; + ignoreUnknownVersions?: boolean; + dangerousExtend?: boolean; + } +} + +declare var browserslist: browserslist.Browserslist; + +export = browserslist; diff --git a/types/browserslist/tsconfig.json b/types/browserslist/tsconfig.json new file mode 100644 index 0000000000..cf68d8bf64 --- /dev/null +++ b/types/browserslist/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": ["index.d.ts", "browserslist-tests.ts"] +} diff --git a/types/browserslist/tslint.json b/types/browserslist/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/browserslist/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index a8c7f403a7..46c146272e 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -98,11 +98,17 @@ const pdfQueue = new Queue('pdf transcoding', { // ////////////////////////////////////////////////////////////////////////////////// -pdfQueue.process((job) => { +pdfQueue.process((job: Queue.Job) => { // Processors can also return promises instead of using the done callback return Promise.resolve(); }); +async function pfdPromise(job: Queue.Job) { + return Promise.resolve(); +} + +pdfQueue.process(1, pfdPromise); + videoQueue.add({ video: 'http://example.com/video1.mov' }, { jobId: 1 }) .then((video1Job) => { // When job has successfully be placed in the queue the job is returned @@ -125,6 +131,7 @@ videoQueue.add({ video: 'http://example.com/video1.mov' }, { jobId: 1 }) pdfQueue .on('error', (err: Error) => undefined) .on('active', (job: Queue.Job, jobPromise: Queue.JobPromise) => jobPromise.cancel()) +.on('waiting', (jobId: Queue.JobId) => undefined) .on('active', (job: Queue.Job) => undefined) .on('stalled', (job: Queue.Job) => undefined) .on('progress', (job: Queue.Job) => undefined) @@ -132,4 +139,53 @@ pdfQueue .on('failed', (job: Queue.Job) => undefined) .on('paused', () => undefined) .on('resumed', () => undefined) -.on('cleaned', (jobs: Queue.Job[], status: Queue.JobStatus) => undefined); +.on('cleaned', (jobs: Queue.Job[], status: Queue.JobStatusClean) => undefined) +.on('drained', () => undefined) +.on('removed', (job: Queue.Job) => undefined); + +// test different process methods + +const profileQueue = new Queue('profile'); +// Max concurrency for requestProfile is 100 +profileQueue.process('requestProfile', 100, () => {}); +profileQueue.process(100, () => {}); + +// other tests +const myQueue = new Queue('myQueue', { + settings: { + drainDelay: 5 + }, + defaultJobOptions: { + stackTraceLimit: 1, + } +}); + +myQueue.on('active', (job: Queue.Job) => { + job.moveToCompleted(); + job.moveToCompleted('done'); + job.moveToCompleted('done', true); + job.moveToCompleted('done', true).then(val => { + if (val) { + const nextJobData: any = val[0]; + const nextJobId: Queue.JobId = val[1]; + } + }); + + job.moveToFailed({ message: "Call to external service failed!" }, true); + job.moveToFailed(new Error('test error'), true); + job.moveToFailed(new Error('test error'), true).then(val => { + if (val) { + const nextJobData: any = val[0]; + const nextJobId: Queue.JobId = val[1]; + } + }); + + job.discard(); +}); + +// test all constructor options: + +new Queue('profile'); +new Queue('profile', 'url'); +new Queue('profile', { prefix: 'test' }); +new Queue('profile', 'url', { prefix: 'test' }); diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index ac820290f2..2d18e0a800 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for bull 3.3 +// Type definitions for bull 3.5 // Project: https://github.com/OptimalBits/bull // Definitions by: Bruno Grieder // Cameron Crothers @@ -10,11 +10,13 @@ // Bond Akinmade // Wuha Team // Alec Brunelle +// Dan Manastireanu +// Kjell-Morten Bratsberg Thorsen +// Christian D. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as Redis from "ioredis"; -import * as Promise from "bluebird"; /** * This is the Queue constructor. @@ -23,9 +25,9 @@ import * as Promise from "bluebird"; */ declare const Bull: { (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - (queueName: string, url?: string): Bull.Queue; // tslint:disable-line unified-signatures + (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; // tslint:disable-line unified-signatures new (queueName: string, opts?: Bull.QueueOptions): Bull.Queue; - new (queueName: string, url?: string): Bull.Queue; // tslint:disable-line unified-signatures + new (queueName: string, url: string, opts?: Bull.QueueOptions): Bull.Queue; // tslint:disable-line unified-signatures }; declare namespace Bull { @@ -90,8 +92,14 @@ declare namespace Bull { * Define a custom backoff strategy */ backoffStrategies?: { - [key: string]: (attemptsMade: number, err: typeof Error) => number; + [key: string]: (attemptsMade: number, err: Error) => number; }; + + /** + * A timeout for when the queue is in `drained` state (empty waiting for jobs). + * It is used when calling `queue.getNextJob()`, which will pass it to `.brpoplpush` on the Redis client. + */ + drainDelay?: number; } type DoneCallback = (error?: Error | null, value?: any) => void; @@ -141,6 +149,11 @@ declare namespace Bull { */ retry(): Promise; + /** + * Ensure this job is never ran again even if attemptsMade is less than job.attempts. + */ + discard(): Promise; + /** * Returns a promise that resolves to the returned data when the job has been finished. * TODO: Add a watchdog to check if the job has finished periodically. @@ -148,6 +161,18 @@ declare namespace Bull { */ finished(): Promise; + /** + * Moves a job to the `completed` queue. Pulls a job from 'waiting' to 'active' + * and returns a tuple containing the next jobs data and id. If no job is in the `waiting` queue, returns null. + */ + moveToCompleted(returnValue?: string, ignoreLock?: boolean): Promise<[any, JobId] | null>; + + /** + * Moves a job to the `failed` queue. Pulls a job from 'waiting' to 'active' + * and returns a tuple containing the next jobs data and id. If no job is in the `waiting` queue, returns null. + */ + moveToFailed(errorInfo: { message: string; }, ignoreLock?: boolean): Promise<[any, JobId] | null>; + /** * Promotes a job that is currently "delayed" to the "waiting" state and executed as soon as possible. */ @@ -170,6 +195,7 @@ declare namespace Bull { } type JobStatus = 'completed' | 'waiting' | 'active' | 'delayed' | 'failed'; + type JobStatusClean = 'completed' | 'wait' | 'active' | 'delayed' | 'failed'; interface BackoffOptions { /** @@ -205,6 +231,11 @@ declare namespace Bull { * Cron pattern specifying when the job should execute */ cron: string; + + /** + * Start date when the repeat job should start repeating (only with cron). + */ + startDate?: Date | string | number; } interface EveryRepeatOptions extends RepeatOptions { @@ -273,6 +304,11 @@ declare namespace Bull { * Default behavior is to keep the job in the completed set. */ removeOnFail?: boolean; + + /** + * Limits the amount of stack trace lines that will be recorded in the stacktrace. + */ + stackTraceLimit?: number; } interface JobCounts { @@ -306,50 +342,39 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - */ - process(callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a processing function for the jobs placed into a given Queue. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. */ - process(callback: ((job: Job) => void) | string): Promise; + process(callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. * * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. * - * A promise must be returned to signal job completion. + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. + * The done callback can be called with an Error instance, to signal that the job did not complete successfully, + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. + * + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * - * @param concurrency Bull will then call you handler in parallel respecting this max number. + * @param concurrency Bull will then call your handler in parallel respecting this maximum value. */ - process(concurrency: number, callback: ((job: Job) => void) | string): Promise; + process(concurrency: number, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. @@ -357,35 +382,21 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * @param concurrency Bull will then call you handler in parallel respecting this max number. - */ - process(concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a named processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * * @param name Bull will only call the handler if the job name matches */ // tslint:disable-next-line:unified-signatures - process(name: string, callback: ((job: Job) => void) | string): Promise; + process(name: string, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Defines a processing function for the jobs placed into a given Queue. @@ -393,52 +404,21 @@ declare namespace Bull { * The callback is called everytime a job is placed in the queue. * It is passed an instance of the job as first argument. * + * If the callback signature contains the second optional done argument, + * the callback will be passed a done callback to be called after the job has been completed. * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. + * or with a result as second argument (e.g.: done(null, result);) when the job is successful. + * Errors will be passed as a second argument to the "failed" event; results, as a second argument to the "completed" event. * - * @param name Bull will only call the handler if the job name matches - */ - // tslint:disable-next-line:unified-signatures - process(name: string, callback: (job: Job, done: DoneCallback) => void): void; - - /** - * Defines a named processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * The callback can also be defined as the string path to a module - * exporting the callback function. Using a path has several advantages: - * - The process is sandboxed so if it crashes it does not affect the worker. - * - You can run blocking code without affecting the queue (jobs will not stall). - * - Much better utilization of multi-core CPUs. - * - Less connections to redis. - * - * A promise must be returned to signal job completion. + * If, however, the callback signature does not contain the done argument, + * a promise must be returned to signal job completion. * If the promise is rejected, the error will be passed as a second argument to the "failed" event. * If it is resolved, its value will be the "completed" event's second argument. * * @param name Bull will only call the handler if the job name matches - * @param concurrency Bull will then call you handler in parallel respecting this max number. + * @param concurrency Bull will then call your handler in parallel respecting this maximum value. */ - process(name: string, concurrency: number, callback: ((job: Job) => void) | string): Promise; - - /** - * Defines a processing function for the jobs placed into a given Queue. - * - * The callback is called everytime a job is placed in the queue. - * It is passed an instance of the job as first argument. - * - * The done callback can be called with an Error instance, to signal that the job did not complete successfully, - * or with a result as second argument as second argument (e.g.: done(null, result);) when the job is successful. - * Errors will be passed as a second argument to the "failed" event; - * results, as a second argument to the "completed" event. - * - * @param name Bull will only call the handler if the job name matches - * @param concurrency Bull will then call you handler in parallel respecting this max number. - */ - process(name: string, concurrency: number, callback: (job: Job, done: DoneCallback) => void): void; + process(name: string, concurrency: number, callback: ((job: Job, done: DoneCallback) => void) | ((job: Job) => Promise) | string): void; /** * Creates a new job and adds it to the queue. @@ -601,12 +581,12 @@ declare namespace Bull { /** * Tells the queue remove all jobs created outside of a grace period in milliseconds. - * You can clean the jobs with the following states: completed, waiting, active, delayed, and failed. + * You can clean the jobs with the following states: completed, wait (typo for waiting), active, delayed, and failed. * @param grace Grace period in milliseconds. * @param status Status of the job to clean. Values are completed, wait, active, delayed, and failed. Defaults to completed. * @param limit Maximum amount of jobs to clean per call. If not provided will clean all matching jobs. */ - clean(grace: number, status?: JobStatus, limit?: number): Promise>>; + clean(grace: number, status?: JobStatusClean, limit?: number): Promise>>; /** * Listens to queue events @@ -618,6 +598,11 @@ declare namespace Bull { */ on(event: 'error', callback: ErrorEventCallback): this; + /** + * A Job is waiting to be processed as soon as a worker is idling. + */ + on(event: 'waiting', callback: WaitingEventCallback): this; + /** * A job has started. You can use `jobPromise.cancel()` to abort it */ @@ -654,6 +639,11 @@ declare namespace Bull { */ on(event: 'resumed', callback: EventCallback): this; // tslint:disable-line unified-signatures + /** + * A job successfully removed. + */ + on(event: 'removed', callback: RemovedEventCallback): this; + /** * Old jobs have been cleaned from the queue. * `jobs` is an array of jobs that were removed, and `type` is the type of those jobs. @@ -661,6 +651,12 @@ declare namespace Bull { * @see Queue#clean() for details */ on(event: 'cleaned', callback: CleanedEventCallback): this; + + /** + * Emitted every time the queue has processed all the waiting jobs + * (even if there can be some delayed jobs not yet processed) + */ + on(event: 'drained', callback: EventCallback): this; // tslint:disable-line unified-signatures } type EventCallback = () => void; @@ -684,7 +680,11 @@ declare namespace Bull { type FailedEventCallback = (job: Job, error: Error) => void; - type CleanedEventCallback = (jobs: Array>, status: JobStatus) => void; + type CleanedEventCallback = (jobs: Array>, status: JobStatusClean) => void; + + type RemovedEventCallback = (job: Job) => void; + + type WaitingEventCallback = (jobId: JobId) => void; } export = Bull; diff --git a/types/bunyan-winston-adapter/index.d.ts b/types/bunyan-winston-adapter/index.d.ts index 718c9804e1..1ce6ae0a8b 100644 --- a/types/bunyan-winston-adapter/index.d.ts +++ b/types/bunyan-winston-adapter/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/gluwer/bunyan-winston-adapter // Definitions by: Steve Hipwell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.2 import * as bunyan from "bunyan"; import { Logger } from "winston"; diff --git a/types/bunyan/bunyan-tests.ts b/types/bunyan/bunyan-tests.ts index e1d1861049..1072ec2031 100644 --- a/types/bunyan/bunyan-tests.ts +++ b/types/bunyan/bunyan-tests.ts @@ -6,6 +6,14 @@ const ringBufferOptions: Logger.RingBufferOptions = { const ringBuffer: Logger.RingBuffer = new Logger.RingBuffer(ringBufferOptions); ringBuffer.write("hello"); +const rotatingFileStreamOptions: Logger.RotatingFileStreamOptions = { + period: "1d", + count: 10, + path: "path" +}; +const rotatingFileStream: Logger.RotatingFileStream = new Logger.RotatingFileStream(rotatingFileStreamOptions); +rotatingFileStream.write("hello"); + let level: number; level = Logger.resolveLevel("trace"); level = Logger.resolveLevel("debug"); @@ -49,6 +57,11 @@ const options: Logger.LoggerOptions = { stream: ringBuffer, level: Logger.ERROR, reemitErrorEvents: true + }, { + type: 'raw', + stream: rotatingFileStream, + level: Logger.ERROR, + reemitErrorEvents: true }] }; diff --git a/types/bunyan/index.d.ts b/types/bunyan/index.d.ts index 4ee972d29c..f6f0b287aa 100644 --- a/types/bunyan/index.d.ts +++ b/types/bunyan/index.d.ts @@ -270,6 +270,29 @@ declare namespace Logger { destroy(): void; destroySoon(): void; } + + interface RotatingFileStreamOptions { + path: string; + count?: number; + period?: string; + } + + class RotatingFileStream extends EventEmitter implements NodeJS.WritableStream { + constructor(options: RotatingFileStreamOptions); + + writable: boolean; + periodNum: number; + periodScope: string; + stream: any; + rotQueue: any[]; + rotating: boolean; + + write(record: any): boolean; + end(record?: any): void; + destroy(): void; + destroySoon(): void; + rotate(): void; + } } export = Logger; diff --git a/types/business-rules-engine/Validation.d.ts b/types/business-rules-engine/Validation.d.ts index 7f61f517be..bff7bf6243 100644 --- a/types/business-rules-engine/Validation.d.ts +++ b/types/business-rules-engine/Validation.d.ts @@ -1,239 +1 @@ -// Type definitions for business-rules-engine - v1.0.20 -// Project: https://github.com/rsamec/form -// Definitions by: Roman Samec -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace Validation { - interface IErrorCustomMessage { - (config: any, args: any): string; - } - interface IPropertyValidator { - isAcceptable(s: any): boolean; - customMessage?: IErrorCustomMessage; - tagName?: string; - } - interface IStringValidator extends IPropertyValidator { - isAcceptable(s: string): boolean; - } - interface IAsyncPropertyValidator { - isAcceptable(s: any): Q.Promise; - customMessage?: IErrorCustomMessage; - isAsync: boolean; - tagName?: string; - } - interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { - isAcceptable(s: string): Q.Promise; - } - enum CompareOperator { - LessThan = 0, - LessThanEqual = 1, - Equal = 2, - NotEqual = 3, - GreaterThanEqual = 4, - GreaterThan = 5, - } - interface IError { - HasError: boolean; - ErrorMessage: string; - TranslateArgs?: IErrorTranslateArgs; - } - interface IErrorTranslateArgs { - TranslateId: string; - MessageArgs: any; - CustomMessage?: IErrorCustomMessage; - } - interface IOptional { - (): boolean; - } - interface IValidationFailure extends IError { - IsAsync: boolean; - Error: IError; - } - interface IValidationResult { - Name: string; - Add(validationResult: IValidationResult): void; - Remove(index: number): void; - Children: IValidationResult[]; - HasErrors: boolean; - HasErrorsDirty: boolean; - ErrorMessage: string; - ErrorCount: number; - Optional?: IOptional; - TranslateArgs?: IErrorTranslateArgs[]; - } - interface IValidate { - (args: IError): void; - } - interface IAsyncValidate { - (args: IError): Q.Promise; - } - interface IValidatorFce { - Name: string; - ValidationFce?: IValidate; - AsyncValidationFce?: IAsyncValidate; - } - interface IValidator { - Validate(context: any): IValidationFailure; - ValidateAsync(context: any): Q.Promise; - Error: IError; - } - interface IAbstractValidator { - RuleFor(prop: string, validator: IPropertyValidator): any; - ValidationFor(prop: string, validatorFce: IValidatorFce): any; - Validation(validatorFce: IValidatorFce): any; - ValidatorFor(prop: string, validator: IAbstractValidator): any; - CreateRule(name: string): IAbstractValidationRule; - CreateAbstractRule(name: string): IAbstractValidationRule; - CreateAbstractListRule(name: string): IAbstractValidationRule; - ForList: boolean; - } - interface IAbstractValidationRule { - Validate(context: T): IValidationResult; - ValidateAsync(context: T): Q.Promise; - ValidateAll(context: T): Q.Promise; - ValidateProperty(context: T, propName: string): void; - ValidationResult: IValidationResult; - Rules: { - [name: string]: IPropertyValidationRule; - }; - Validators: { - [name: string]: IValidator; - }; - Children: { - [name: string]: IAbstractValidationRule; - }; - } - interface IPropertyValidationRule { - Validators: { - [name: string]: any; - }; - Validate(context: IValidationContext): IValidationFailure[]; - ValidateAsync(context: IValidationContext): Q.Promise; - } - interface IValidationContext { - Value: string; - Key: string; - Data: T; - } - class Error implements IError { - public HasError: boolean; - public ErrorMessage: string; - constructor(); - } - class ValidationFailure implements IError { - public Error: IError; - public IsAsync: boolean; - constructor(Error: IError, IsAsync: boolean); - public HasError : boolean; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs; - } - class ValidationResult implements IValidationResult { - public Name: string; - constructor(Name: string); - public IsDirty: boolean; - public Children : IValidationResult[]; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public Optional: IOptional; - public TranslateArgs: IErrorTranslateArgs[]; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - } - class CompositeValidationResult implements IValidationResult { - public Name: string; - public Children: IValidationResult[]; - constructor(Name: string); - public Optional: IOptional; - public AddFirst(error: IValidationResult): void; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - public LogErrors(headerMessage?: string): void; - public Errors : { - [name: string]: IValidationResult; - }; - private FlattenErros; - public SetDirty(): void; - public SetPristine(): void; - private SetDirtyEx(node, dirty); - private flattenErrors(node, errorCollection); - private traverse(node, indent); - } - class AbstractValidator implements IAbstractValidator { - public Validators: { - [name: string]: IPropertyValidator[]; - }; - public AbstractValidators: { - [name: string]: IAbstractValidator; - }; - public ValidationFunctions: { - [name: string]: IValidatorFce[]; - }; - public RuleFor(prop: string, validator: IPropertyValidator): void; - public ValidationFor(prop: string, fce: IValidatorFce): void; - public Validation(fce: IValidatorFce): void; - public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; - public CreateAbstractRule(name: string): IAbstractValidationRule; - public CreateAbstractListRule(name: string): IAbstractValidationRule; - public CreateRule(name: string): IAbstractValidationRule; - public ForList: boolean; - } - class MessageLocalization { - static customMsg: string; - static defaultMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static ValidationMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static GetValidationMessage(validator: any): string; - } -} declare module "node-validation" {export = Validation;} diff --git a/types/business-rules-engine/index.d.ts b/types/business-rules-engine/index.d.ts index d85cd49c81..593eb92f51 100644 --- a/types/business-rules-engine/index.d.ts +++ b/types/business-rules-engine/index.d.ts @@ -4,242 +4,237 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// Source: typings/business-rules-engine/Validation.d.ts - import * as Q from "q"; -declare namespace Validation { - interface IErrorCustomMessage { - (config: any, args: any): string; - } - interface IPropertyValidator { - isAcceptable(s: any): boolean; - customMessage?: IErrorCustomMessage; - tagName?: string; - } - interface IStringValidator extends IPropertyValidator { - isAcceptable(s: string): boolean; - } - interface IAsyncPropertyValidator { - isAcceptable(s: any): Q.Promise; - customMessage?: IErrorCustomMessage; - isAsync: boolean; - tagName?: string; - } - interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { - isAcceptable(s: string): Q.Promise; - } - enum CompareOperator { - LessThan = 0, - LessThanEqual = 1, - Equal = 2, - NotEqual = 3, - GreaterThanEqual = 4, - GreaterThan = 5, - } - interface IError { - HasError: boolean; - ErrorMessage: string; - TranslateArgs?: IErrorTranslateArgs; - } - interface IErrorTranslateArgs { - TranslateId: string; - MessageArgs: any; - CustomMessage?: IErrorCustomMessage; - } - interface IOptional { - (): boolean; - } - interface IValidationFailure extends IError { - IsAsync: boolean; - Error: IError; - } - interface IValidationResult { - Name: string; - Add(validationResult: IValidationResult): void; - Remove(index: number): void; - Children: IValidationResult[]; - HasErrors: boolean; - HasErrorsDirty: boolean; - ErrorMessage: string; - ErrorCount: number; - Optional?: IOptional; - TranslateArgs?: IErrorTranslateArgs[]; - } - interface IValidate { - (args: IError): void; - } - interface IAsyncValidate { - (args: IError): Q.Promise; - } - interface IValidatorFce { - Name: string; - ValidationFce?: IValidate; - AsyncValidationFce?: IAsyncValidate; - } - interface IValidator { - Validate(context: any): IValidationFailure; - ValidateAsync(context: any): Q.Promise; - Error: IError; - } - interface IAbstractValidator { - RuleFor(prop: string, validator: IPropertyValidator): any; - ValidationFor(prop: string, validatorFce: IValidatorFce): any; - Validation(validatorFce: IValidatorFce): any; - ValidatorFor(prop: string, validator: IAbstractValidator): any; - CreateRule(name: string): IAbstractValidationRule; - CreateAbstractRule(name: string): IAbstractValidationRule; - CreateAbstractListRule(name: string): IAbstractValidationRule; - ForList: boolean; - } - interface IAbstractValidationRule { - Validate(context: T): IValidationResult; - ValidateAsync(context: T): Q.Promise; - ValidateAll(context: T): Q.Promise; - ValidateProperty(context: T, propName: string): void; - ValidationResult: IValidationResult; - Rules: { - [name: string]: IPropertyValidationRule; - }; - Validators: { - [name: string]: IValidator; - }; - Children: { - [name: string]: IAbstractValidationRule; - }; - } - interface IPropertyValidationRule { - Validators: { - [name: string]: any; - }; - Validate(context: IValidationContext): IValidationFailure[]; - ValidateAsync(context: IValidationContext): Q.Promise; - } - interface IValidationContext { - Value: string; - Key: string; - Data: T; - } - class Error implements IError { - public HasError: boolean; - public ErrorMessage: string; - constructor(); - } - class ValidationFailure implements IError { - public Error: IError; - public IsAsync: boolean; - constructor(Error: IError, IsAsync: boolean); - public HasError : boolean; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs; - } - class ValidationResult implements IValidationResult { - public Name: string; - constructor(Name: string); - public IsDirty: boolean; - public Children : IValidationResult[]; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public Optional: IOptional; - public TranslateArgs: IErrorTranslateArgs[]; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - } - class CompositeValidationResult implements IValidationResult { - public Name: string; - public Children: IValidationResult[]; - constructor(Name: string); - public Optional: IOptional; - public AddFirst(error: IValidationResult): void; - public Add(error: IValidationResult): void; - public Remove(index: number): void; - public HasErrorsDirty : boolean; - public HasErrors : boolean; - public ErrorCount : number; - public ErrorMessage : string; - public TranslateArgs : IErrorTranslateArgs[]; - public LogErrors(headerMessage?: string): void; - public Errors : { - [name: string]: IValidationResult; - }; - private FlattenErros; - public SetDirty(): void; - public SetPristine(): void; - private SetDirtyEx(node, dirty); - private flattenErrors(node, errorCollection); - private traverse(node, indent); - } - class AbstractValidator implements IAbstractValidator { - public Validators: { - [name: string]: IPropertyValidator[]; - }; - public AbstractValidators: { - [name: string]: IAbstractValidator; - }; - public ValidationFunctions: { - [name: string]: IValidatorFce[]; - }; - public RuleFor(prop: string, validator: IPropertyValidator): void; - public ValidationFor(prop: string, fce: IValidatorFce): void; - public Validation(fce: IValidatorFce): void; - public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; - public CreateAbstractRule(name: string): IAbstractValidationRule; - public CreateAbstractListRule(name: string): IAbstractValidationRule; - public CreateRule(name: string): IAbstractValidationRule; - public ForList: boolean; - } - class MessageLocalization { - static customMsg: string; - static defaultMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static ValidationMessages: { - "required": string; - "remote": string; - "email": string; - "url": string; - "date": string; - "dateISO": string; - "number": string; - "digits": string; - "signedDigits": string; - "creditcard": string; - "equalTo": string; - "maxlength": string; - "minlength": string; - "rangelength": string; - "range": string; - "max": string; - "min": string; - "step": string; - "contains": string; - "mask": string; - "custom": string; - }; - static GetValidationMessage(validator: any): string; - } +export interface IErrorCustomMessage { + (config: any, args: any): string; +} +export interface IPropertyValidator { + isAcceptable(s: any): boolean; + customMessage?: IErrorCustomMessage; + tagName?: string; +} +export interface IStringValidator extends IPropertyValidator { + isAcceptable(s: string): boolean; +} +export interface IAsyncPropertyValidator { + isAcceptable(s: any): Q.Promise; + customMessage?: IErrorCustomMessage; + isAsync: boolean; + tagName?: string; +} +export interface IAsyncStringPropertyValidator extends IAsyncPropertyValidator { + isAcceptable(s: string): Q.Promise; +} +export enum CompareOperator { + LessThan = 0, + LessThanEqual = 1, + Equal = 2, + NotEqual = 3, + GreaterThanEqual = 4, + GreaterThan = 5, +} +export interface IError { + HasError: boolean; + ErrorMessage: string; + TranslateArgs?: IErrorTranslateArgs; +} +export interface IErrorTranslateArgs { + TranslateId: string; + MessageArgs: any; + CustomMessage?: IErrorCustomMessage; +} +export interface IOptional { + (): boolean; +} +export interface IValidationFailure extends IError { + IsAsync: boolean; + Error: IError; +} +export interface IValidationResult { + Name: string; + Add(validationResult: IValidationResult): void; + Remove(index: number): void; + Children: IValidationResult[]; + HasErrors: boolean; + HasErrorsDirty: boolean; + ErrorMessage: string; + ErrorCount: number; + Optional?: IOptional; + TranslateArgs?: IErrorTranslateArgs[]; +} +export interface IValidate { + (args: IError): void; +} +export interface IAsyncValidate { + (args: IError): Q.Promise; +} +export interface IValidatorFce { + Name: string; + ValidationFce?: IValidate; + AsyncValidationFce?: IAsyncValidate; +} +export interface IValidator { + Validate(context: any): IValidationFailure; + ValidateAsync(context: any): Q.Promise; + Error: IError; +} +export interface IAbstractValidator { + RuleFor(prop: string, validator: IPropertyValidator): any; + ValidationFor(prop: string, validatorFce: IValidatorFce): any; + Validation(validatorFce: IValidatorFce): any; + ValidatorFor(prop: string, validator: IAbstractValidator): any; + CreateRule(name: string): IAbstractValidationRule; + CreateAbstractRule(name: string): IAbstractValidationRule; + CreateAbstractListRule(name: string): IAbstractValidationRule; + ForList: boolean; +} +export interface IAbstractValidationRule { + Validate(context: T): IValidationResult; + ValidateAsync(context: T): Q.Promise; + ValidateAll(context: T): Q.Promise; + ValidateProperty(context: T, propName: string): void; + ValidationResult: IValidationResult; + Rules: { + [name: string]: IPropertyValidationRule; + }; + Validators: { + [name: string]: IValidator; + }; + Children: { + [name: string]: IAbstractValidationRule; + }; +} +export interface IPropertyValidationRule { + Validators: { + [name: string]: any; + }; + Validate(context: IValidationContext): IValidationFailure[]; + ValidateAsync(context: IValidationContext): Q.Promise; +} +export interface IValidationContext { + Value: string; + Key: string; + Data: T; +} +export class Error implements IError { + public HasError: boolean; + public ErrorMessage: string; + constructor(); +} +export class ValidationFailure implements IError { + public Error: IError; + public IsAsync: boolean; + constructor(Error: IError, IsAsync: boolean); + public HasError : boolean; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs; +} +export class ValidationResult implements IValidationResult { + public Name: string; + constructor(Name: string); + public IsDirty: boolean; + public Children : IValidationResult[]; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public Optional: IOptional; + public TranslateArgs: IErrorTranslateArgs[]; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; +} +export class CompositeValidationResult implements IValidationResult { + public Name: string; + public Children: IValidationResult[]; + constructor(Name: string); + public Optional: IOptional; + public AddFirst(error: IValidationResult): void; + public Add(error: IValidationResult): void; + public Remove(index: number): void; + public HasErrorsDirty : boolean; + public HasErrors : boolean; + public ErrorCount : number; + public ErrorMessage : string; + public TranslateArgs : IErrorTranslateArgs[]; + public LogErrors(headerMessage?: string): void; + public Errors : { + [name: string]: IValidationResult; + }; + private FlattenErros; + public SetDirty(): void; + public SetPristine(): void; + private SetDirtyEx(node, dirty); + private flattenErrors(node, errorCollection); + private traverse(node, indent); +} +export class AbstractValidator implements IAbstractValidator { + public Validators: { + [name: string]: IPropertyValidator[]; + }; + public AbstractValidators: { + [name: string]: IAbstractValidator; + }; + public ValidationFunctions: { + [name: string]: IValidatorFce[]; + }; + public RuleFor(prop: string, validator: IPropertyValidator): void; + public ValidationFor(prop: string, fce: IValidatorFce): void; + public Validation(fce: IValidatorFce): void; + public ValidatorFor(prop: string, validator: IAbstractValidator, forList?: boolean): void; + public CreateAbstractRule(name: string): IAbstractValidationRule; + public CreateAbstractListRule(name: string): IAbstractValidationRule; + public CreateRule(name: string): IAbstractValidationRule; + public ForList: boolean; +} +export class MessageLocalization { + static customMsg: string; + static defaultMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static ValidationMessages: { + "required": string; + "remote": string; + "email": string; + "url": string; + "date": string; + "dateISO": string; + "number": string; + "digits": string; + "signedDigits": string; + "creditcard": string; + "equalTo": string; + "maxlength": string; + "minlength": string; + "rangelength": string; + "range": string; + "max": string; + "min": string; + "step": string; + "contains": string; + "mask": string; + "custom": string; + }; + static GetValidationMessage(validator: any): string; } -export = Validation; export as namespace Validation; 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/caller/caller-tests.ts b/types/caller/caller-tests.ts new file mode 100644 index 0000000000..81d8d64606 --- /dev/null +++ b/types/caller/caller-tests.ts @@ -0,0 +1,4 @@ +import caller = require('caller'); + +const callerFile: string = caller(); +const callerFile2: string = caller(1); diff --git a/types/caller/index.d.ts b/types/caller/index.d.ts new file mode 100644 index 0000000000..f09b6f129b --- /dev/null +++ b/types/caller/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for caller 1.0 +// Project: https://github.com/totherik/caller +// Definitions by: Ignocide +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function caller(depth?: number): string; + +export = caller; diff --git a/types/caller/tsconfig.json b/types/caller/tsconfig.json new file mode 100644 index 0000000000..80ae4b956e --- /dev/null +++ b/types/caller/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", + "caller-tests.ts" + ] +} diff --git a/types/caller/tslint.json b/types/caller/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/caller/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/caniuse-api/caniuse-api-tests.ts b/types/caniuse-api/caniuse-api-tests.ts new file mode 100644 index 0000000000..46b6a1eec4 --- /dev/null +++ b/types/caniuse-api/caniuse-api-tests.ts @@ -0,0 +1,17 @@ +import * as caniuse from "caniuse-api"; + +caniuse.features; // $ExpectType string[] + +caniuse.getSupport(""); // $ExpectType BrowserSupport + +caniuse.isSupported("", ""); // $ExpectType boolean +caniuse.isSupported("", [""]); // $ExpectType boolean + +caniuse.find(""); // $ExpectType string[] + +caniuse.getLatestStableBrowsers(); // $ExpectType string[] + +caniuse.setBrowserScope(""); // $ExpectType void +caniuse.setBrowserScope([""]); // $ExpectType void + +caniuse.getBrowserScope(); // $ExpectType string[] diff --git a/types/caniuse-api/index.d.ts b/types/caniuse-api/index.d.ts new file mode 100644 index 0000000000..ce6dac23ec --- /dev/null +++ b/types/caniuse-api/index.d.ts @@ -0,0 +1,32 @@ +// Type definitions for caniuse-api 3.0 +// Project: https://github.com/nyalab/caniuse-api#readme +// Definitions by: Dave Cardwell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export const features: string[]; + +export interface BrowserSupport { + [browser: string]: { + y?: number; + n?: number; + a?: number; + x?: number; + }; +} + +export function getSupport(feature: string): BrowserSupport; + +export function isSupported( + feature: string, + browsers: string | ReadonlyArray +): boolean; + +export function find(query: string): string[]; + +export function getLatestStableBrowsers(): string[]; + +export function setBrowserScope( + browserscope: string | ReadonlyArray +): void; + +export function getBrowserScope(): string[]; diff --git a/types/caniuse-api/tsconfig.json b/types/caniuse-api/tsconfig.json new file mode 100644 index 0000000000..2e43754f9e --- /dev/null +++ b/types/caniuse-api/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", "caniuse-api-tests.ts"] +} diff --git a/types/caniuse-api/tslint.json b/types/caniuse-api/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/caniuse-api/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/cassandra-driver/index.d.ts b/types/cassandra-driver/index.d.ts index 33a9f5988f..f57f203a03 100644 --- a/types/cassandra-driver/index.d.ts +++ b/types/cassandra-driver/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for cassandra-driver v3.4.1 +// Type definitions for cassandra-driver v3.5.0 // Project: https://github.com/datastax/nodejs-driver // Definitions by: Marc Fisher // Christian D @@ -413,7 +413,7 @@ export namespace types { pageState: string; nextPage: Function; - first(): Row; + first(): Row | null; getPageState(): string; getColumns(): Array<{ [key: string]: string; }>; wasApplied(): boolean; @@ -526,7 +526,8 @@ export interface ClientOptions { protocolOptions?: { port?: number, maxSchemaAgreementWaitSeconds?: number, - maxVersion?: number + maxVersion?: number, + noCompact?: boolean }, socketOptions?: { connectTimeout?: number, diff --git a/types/catbox-memory/catbox-memory-tests.ts b/types/catbox-memory/catbox-memory-tests.ts new file mode 100644 index 0000000000..9c4c1bcdfe --- /dev/null +++ b/types/catbox-memory/catbox-memory-tests.ts @@ -0,0 +1,8 @@ +import * as CatboxMemory from 'catbox-memory'; + +const client = new CatboxMemory({ + allowMixedContent: true, + cloneBuffersOnGet: false, + maxByteSize: 1024, + minCleanupIntervalMsec: 1000, +}); diff --git a/types/catbox-memory/index.d.ts b/types/catbox-memory/index.d.ts new file mode 100644 index 0000000000..b615d6c45d --- /dev/null +++ b/types/catbox-memory/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for catbox-memory 4.0 +// Project: https://github.com/hapijs/catbox-memory#readme +// Definitions by: Simon Schick +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { ClientApi } from 'catbox'; + +interface CatboxMemory extends ClientApi {} + +// tslint:disable-next-line:no-unnecessary-class +declare class CatboxMemory implements ClientApi { + constructor(options?: CatboxMemory.Options); +} + +declare namespace CatboxMemory { + interface Options { + /** + * Sets an upper limit on the number of bytes that can be stored in the cache. + * Once this limit is reached no additional items will be added to the cache until some expire. + * The utilized memory calculation is a rough approximation and must not be relied on. + * @default 104857600 (100MB). + */ + maxByteSize?: number; + /** + * The minimum number of milliseconds in between each cache cleanup. + * @default 1000 (1 second) + */ + minCleanupIntervalMsec?: number; + /** + * by default, all data is cached as JSON strings, and converted to an object using JSON.parse() on retrieval. + * By setting this option to true, Buffer data can be stored alongside the stringified data. + * Buffers are not stringified, and are copied before storage to prevent the value from changing while in the cache. + * @default false + */ + allowMixedContent?: boolean; + /** + * by default, buffers stored in the cache with allowMixedContent set to true are copied when they are set but not when they are retrieved. + * This means a change to the buffer returned by a get() will change the value in the cache. To prevent this, + * set cloneBuffersOnGet to true to always return a copy of the cached buffer. + * @default false + */ + cloneBuffersOnGet?: boolean; + } +} + +export = CatboxMemory; diff --git a/types/catbox-memory/tsconfig.json b/types/catbox-memory/tsconfig.json new file mode 100644 index 0000000000..c52e660d39 --- /dev/null +++ b/types/catbox-memory/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", + "catbox-memory-tests.ts" + ] +} diff --git a/types/catbox-memory/tslint.json b/types/catbox-memory/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/catbox-memory/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/catbox-redis/catbox-redis-tests.ts b/types/catbox-redis/catbox-redis-tests.ts index d7fb5eb701..91d86445b7 100644 --- a/types/catbox-redis/catbox-redis-tests.ts +++ b/types/catbox-redis/catbox-redis-tests.ts @@ -1,6 +1,6 @@ import * as CatbotRedis from 'catbox-redis'; -const cache = new CatbotRedis({ +const cache = new CatbotRedis({ host: 'localhost', partition: 'test', port: 2018, @@ -10,3 +10,8 @@ cache.get({ segment: 'test', id: 'test', }); + +cache.set({ + segment: 'test', + id: 'test', +}, 'test', 123); diff --git a/types/catbox-redis/index.d.ts b/types/catbox-redis/index.d.ts index a0d3590953..18972c6493 100644 --- a/types/catbox-redis/index.d.ts +++ b/types/catbox-redis/index.d.ts @@ -53,7 +53,7 @@ declare module 'catbox-redis' { sentinelName?: string; } } - class CatboxRedis extends Client { + class CatboxRedis extends Client { constructor(options: CatboxRedis.CatboxRedisOptions); } export = CatboxRedis; diff --git a/types/catbox/catbox-tests.ts b/types/catbox/catbox-tests.ts index 25d4826d25..e86d2a94af 100644 --- a/types/catbox/catbox-tests.ts +++ b/types/catbox/catbox-tests.ts @@ -1,16 +1,22 @@ -import { CacheItem, Client, Policy, EnginePrototypeOrObject } from "catbox"; +import { Client, Policy, EnginePrototypeOrObject, DecoratedResult, CachedObject } from "catbox"; const Memory: EnginePrototypeOrObject = { async start(): Promise {}, stop(): void {}, - async get(): Promise {}, + async get(): Promise> { + return { + item: 'asd', + stored: 12, + ttl: 123, + }; + }, async set(): Promise {}, async drop(): Promise {}, isReady(): boolean { return true; }, validateSegmentName(segment: string): null { return null; }, }; -const client = new Client(Memory, { partition: 'cache' }); +const client = new Client(Memory, { partition: 'cache' }); const cache = new Policy({ expiresIn: 5000, @@ -25,3 +31,11 @@ cache.drop('foo').then(() => {}); cache.isReady(); cache.stats(); + +const decoratedCache = new Policy({ + getDecoratedValue: true, +}, client, 'cache2'); + +decoratedCache.get('test').then((a: DecoratedResult) => { + const res: string = a.value; +}); diff --git a/types/catbox/index.d.ts b/types/catbox/index.d.ts index f6881b1aef..62b99ac5b3 100644 --- a/types/catbox/index.d.ts +++ b/types/catbox/index.d.ts @@ -4,7 +4,7 @@ // AJP // Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /** * Client @@ -17,7 +17,7 @@ * the Riak bucket, or as a key prefix in Redis and Memcached. To share the cache across multiple clients, use the same partition name. * @see {@link https://github.com/hapijs/catbox#client} */ -export class Client implements ClientApi { +export class Client implements ClientApi { constructor(engine: EnginePrototypeOrObject, options: ClientOptions); /** start() - creates a connection to the cache server. Must be called before any other method is available. */ @@ -28,14 +28,14 @@ export class Client implements ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). */ - get(key: CacheKey): Promise; + get(key: CacheKey): Promise>; /** * set(key, value, ttl, callback) - store an item in the cache for a specified length of time, where: * * key - a cache key object (see [ICacheKey]). * * value - the string or object value to be stored. * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). */ - set(key: CacheKey, value: CacheItem, ttl: number): Promise; + set(key: CacheKey, value: T, ttl: number): Promise; /** * drop(key, callback) - remove an item from cache where: * * key - a cache key object (see [ICacheKey]). @@ -47,13 +47,13 @@ export class Client implements ClientApi { validateSegmentName(segment: string): null | Error; } -export type EnginePrototypeOrObject = EnginePrototype | ClientApi; +export type EnginePrototypeOrObject = EnginePrototype | ClientApi; /** * A prototype CatBox engine function */ -export interface EnginePrototype { - new(settings: ClientOptions): ClientApi; +export interface EnginePrototype { + new(settings: ClientOptions): ClientApi; } /** @@ -61,7 +61,7 @@ export interface EnginePrototype { * The Client object provides the following methods: * @see {@link https://github.com/hapijs/catbox#api} */ -export interface ClientApi { +export interface ClientApi { /** start() - creates a connection to the cache server. Must be called before any other method is available. */ start(): Promise; /** stop() - terminates the connection to the cache server. */ @@ -70,14 +70,14 @@ export interface ClientApi { * get(key, callback) - retrieve an item from the cache engine if found where: * * key - a cache key object (see [ICacheKey]). */ - get(key: CacheKey): Promise; + get(key: CacheKey): Promise>; /** * set(key, value, ttl) - store an item in the cache for a specified length of time, where: * * key - a cache key object (see [ICacheKey]). * * value - the string or object value to be stored. * * ttl - a time-to-live value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). */ - set(key: CacheKey, value: CacheItem, ttl: number): Promise; + set(key: CacheKey, value: T, ttl: number): Promise; /** * drop(key) - remove an item from cache where: * * key - a cache key object (see [ICacheKey]). @@ -100,17 +100,15 @@ export interface CacheKey { } /** Cached object contains the following: */ -export interface CachedObject { +export interface CachedObject { /** item - the value stored in the cache using set(). */ - item: any; + item: T; /** stored - the timestamp when the item was stored in the cache (in milliseconds). */ stored: number; /** ttl - the remaining time-to-live (not the original value used when storing the object). */ ttl: number; } -export type CacheItem = any; - export interface ClientOptions { /** * this will store items under keys that start with this value. @@ -118,89 +116,71 @@ export interface ClientOptions { partition: string; } +export type PolicyOptionVariants = PolicyOptions | DecoratedPolicyOptions; + +export type Id = string | { id: string }; + /** - * The Policy object provides a convenient cache interface by setting a global policy which is automatically applied to every storage action. + * The Policy object provides a convenient cache interface by setting a + * global policy which is automatically applied to every storage action. * The object is constructed using new Policy(options, [cache, segment]) where: * * options - an object with the IPolicyOptions structure * * cache - a Client instance (which has already been started). - * * segment - required when cache is provided. The segment name used to isolate cached items within the cache partition. + * * segment - required when cache is provided. The segment name used to + * isolate cached items within the cache partition. * @see {@link https://github.com/hapijs/catbox#policy} */ -export class Policy implements PolicyAPI { - constructor(options: PolicyOptions, cache: Client, segment: string); +export class Policy> { + constructor(options: O, cache: Client, segment: string); /** - * get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, - * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: - * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. + * retrieve an item from the cache. If the item is not + * found and the generateFunc method was provided, + * a new value is generated, stored in the cache, and returned. + * Multiple concurrent requests are queued and processed once. The method arguments are: + * @param id the unique item identifier (within the policy segment). + * Can be a string or an object with the required 'id' key. */ - get(id: string | { id: string }): Promise; + get(id: Id): Promise ? DecoratedResult : T | null>; + /** - * set(id, value, ttl) - store an item in the cache where: - * * id - the unique item identifier (within the policy segment). - * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). + * store an item in the cache where: + * @param id - the unique item identifier (within the policy segment). + * @param value - the string or object value to be stored. + * @param ttl - a time-to-live override value in milliseconds after which the item is automatically + * removed from the cache (or is marked invalid). * This should be set to 0 in order to use the caching rules configured when creating the Policy object. */ - set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise; + set(id: Id, value: T, ttl?: number): Promise; /** - * drop(id) - remove the item from cache where: - * * id - the unique item identifier (within the policy segment). + * remove the item from cache where: + * @param id the unique item identifier (within the policy segment). + */ + drop(id: Id): Promise; + /** + * given a created timestamp in milliseconds, returns the time-to-live left + * based on the configured rules. */ - drop(id: string | { id: string }): Promise; - /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ ttl(created: number): number; - /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ - rules(options: PolicyOptions): void; - /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ + /** changes the policy rules after construction (note that items already stored will not be affected) */ + rules(options: PolicyOptions): void; + /** + * returns true if cache engine determines itself as ready, false if it is not ready or if + * here is no cache engine set. + */ isReady(): boolean; - /** stats - an object with cache statistics */ + /** an object with cache statistics */ stats(): CacheStatisticsObject; } -/** - * Policy API - * The Policy object provides the following methods: - * @see {@link https://github.com/hapijs/catbox#api-1} - */ -export interface PolicyAPI { - /** - * get(id) - retrieve an item from the cache. If the item is not found and the generateFunc method was provided, - * a new value is generated, stored in the cache, and returned. Multiple concurrent requests are queued and processed once. The method arguments are: - * * id - the unique item identifier (within the policy segment). Can be a string or an object with the required 'id' key. - */ - get(id: string | { id: string }): Promise; - /** - * set(id, value, ttl) - store an item in the cache where: - * * id - the unique item identifier (within the policy segment). - * * value - the string or object value to be stored. - * * ttl - a time-to-live override value in milliseconds after which the item is automatically removed from the cache (or is marked invalid). - * This should be set to 0 in order to use the caching rules configured when creating the Policy object. - */ - set(id: string | { id: string }, value: CacheItem, ttl: number | null): Promise; - /** - * drop(id) - remove the item from cache where: - * * id - the unique item identifier (within the policy segment). - */ - drop(id: string | { id: string }): Promise; - /** ttl(created) - given a created timestamp in milliseconds, returns the time-to-live left based on the configured rules. */ - ttl(created: number): number; - /** rules(options) - changes the policy rules after construction (note that items already stored will not be affected) */ - rules(options: PolicyOptions): void; - /** isReady() - returns true if cache engine determines itself as ready, false if it is not ready or if there is no cache engine set. */ - isReady(): boolean; - /** stats - an object with cache statistics */ - stats(): CacheStatisticsObject; -} - -export interface PolicyGetPromiseResult { - value: CacheItem; - cached: PolicyGetCachedOptions; +export interface DecoratedResult { + value: T; + cached: PolicyGetCachedOptions; report: PolicyGetReportLog; } -export interface PolicyGetCachedOptions { +export interface PolicyGetCachedOptions { /** item - the cached value. */ - item: CacheItem; + item: T; /** stored - the timestamp when the item was stored in the cache. */ stored: number; /** ttl - the cache ttl value for the record. */ @@ -212,13 +192,13 @@ export interface PolicyGetCachedOptions { /** * @see {@link https://github.com/hapijs/catbox#policy} */ -export interface PolicyOptions { +export interface PolicyOptions { /** expiresIn - relative expiration expressed in the number of milliseconds since the item was saved in the cache. Cannot be used together with expiresAt. */ expiresIn?: number; /** expiresAt - time of day expressed in 24h notation using the 'HH:MM' format, at which point all cache records for the route expire. Uses local time. Cannot be used together with expiresIn. */ expiresAt?: string; /** generateFunc - a function used to generate a new cache item if one is not found in the cache when calling get(). The method's signature is function(id, next) where: */ - generateFunc?: GenerateFunc; + generateFunc?: GenerateFunc; /** * staleIn - number of milliseconds to mark an item stored in cache as stale and attempt to regenerate it when generateFunc is provided. * Must be less than expiresIn. Alternatively function that returns staleIn value in milliseconds. The function signature is function(stored, ttl) where: @@ -242,11 +222,18 @@ export interface PolicyOptions { generateIgnoreWriteError?: boolean; /** * pendingGenerateTimeout - number of milliseconds while generateFunc call is in progress for a given id, before a subsequent generateFunc call is allowed. - * Defaults to 0, no blocking of concurrent generateFunc calls beyond staleTimeout. + * @default 0, no blocking of concurrent generateFunc calls beyond staleTimeout. */ pendingGenerateTimeout?: number; } +export interface DecoratedPolicyOptions extends PolicyOptions { + /** + * @default false + */ + getDecoratedValue?: boolean; +} + export interface GenerateFuncFlags { ttl: number; } @@ -262,7 +249,7 @@ export interface GenerateFuncFlags { * * ttl - the cache ttl value in milliseconds. Set to 0 to skip storing in the cache. Defaults to the cache global policy. * @see {@link https://github.com/hapijs/catbox#policy} */ -export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise; +export type GenerateFunc = (id: string, flags: GenerateFuncFlags) => Promise; /** * An object with logging information about the generation operation containing the following keys (as relevant): 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/chai-fs/chai-fs-tests.ts b/types/chai-fs/chai-fs-tests.ts new file mode 100644 index 0000000000..2b7df3ed8f --- /dev/null +++ b/types/chai-fs/chai-fs-tests.ts @@ -0,0 +1,400 @@ +import { assert, expect, use, should } from 'chai'; +import Chaifs = require('chai-fs'); + +use(Chaifs); +should(); + +const name = 'name'; +const path = 'tmp/'; +const otherPath = 'otherPath/'; +const msg = 'message'; +const array: any[] = [1, 2, 3, 4]; +const data: ArrayBuffer = new ArrayBuffer(512); +const obj: object = { key: 'value' }; +const schema = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); + +// basename() +expect(path).to.have.basename(name); +expect(path).to.have.basename(name, msg); +expect(path).to.not.have.basename(name); +expect(path).to.not.have.basename(name, msg); + +path.should.have.basename(name); +path.should.have.basename(name, msg); +path.should.not.have.basename(name); +path.should.not.have.basename(name, msg); + +assert.basename(path, name); +assert.basename(path, name, msg); +assert.notBasename(path, name); +assert.notBasename(path, name, msg); + +// dirname() +expect(path).to.have.dirname(name); +expect(path).to.have.dirname(name, msg); +expect(path).to.not.have.dirname(name); +expect(path).to.not.have.dirname(name, msg); + +path.should.have.dirname(name); +path.should.have.dirname(name, msg); +path.should.not.have.dirname(name); +path.should.not.have.dirname(name, msg); + +assert.dirname(path, name); +assert.dirname(path, name, msg); +assert.notDirname(path, name); +assert.notDirname(path, name, msg); + +// extname() +expect(path).to.have.extname(name); +expect(path).to.have.extname(name, msg); +expect(path).to.not.have.extname(name); +expect(path).to.not.have.extname(name, msg); + +path.should.have.extname(name); +path.should.have.extname(name, msg); +path.should.not.have.extname(name); +path.should.not.have.extname(name, msg); + +assert.extname(path, name); +assert.extname(path, name, msg); +assert.notExtname(path, name); +assert.notExtname(path, name, msg); + +// path() +expect(path).to.be.a.path(); +expect(path).to.be.a.path(msg); +expect(path).to.not.be.a.path(); +expect(path).to.not.be.a.path(msg); + +path.should.be.a.path(); +path.should.be.a.path(msg); +path.should.be.a.path(); +path.should.be.a.path(msg); +path.should.not.be.a.path(); +path.should.not.be.a.path(msg); + +assert.pathExists(path); +assert.pathExists(path, msg); +assert.notPathExists(path); +assert.notPathExists(path, msg); + +// directory +expect(path).to.be.a.directory(); +expect(path).to.be.a.directory(msg); +expect(path).to.not.be.a.directory(); +expect(path).to.not.be.a.directory(msg); + +path.should.be.a.directory(); +path.should.be.a.directory(msg); +path.should.not.be.a.directory(); +path.should.not.be.a.directory(msg); + +assert.isDirectory(path); +assert.isDirectory(path, msg); +assert.notIsDirectory(path); +assert.notIsDirectory(path, msg); + +// directory().and.empty +expect(path).to.be.a.directory().and.empty; +expect(path).to.be.a.directory(msg).and.empty; +expect(path).to.be.a.directory().and.not.empty; +expect(path).to.be.a.directory(msg).and.not.empty; + +path.should.be.a.directory().and.empty; +path.should.be.a.directory(msg).and.empty; +path.should.be.a.directory().and.not.empty; +path.should.be.a.directory(msg).and.not.empty; + +assert.isEmptyDirectory(path); +assert.isEmptyDirectory(path, msg); +assert.notIsEmptyDirectory(path); +assert.notIsEmptyDirectory(path, msg); + +// directory().with.contents([...]) +// #1 +expect(path).to.be.a.directory(msg).with.contents(array); +expect(path).to.be.a.directory(msg).with.contents(array, msg); +// #2 +expect(path).to.be.a.directory(msg).and.not.have.contents(array); +expect(path).to.be.a.directory(msg).and.not.have.contents(array, msg); +// #3 +expect(path).to.be.a.directory(msg).with.deep.contents(array); +expect(path).to.be.a.directory(msg).with.deep.contents(array, msg); +// #4 +expect(path).to.be.a.directory(msg).and.not.have.deep.contents(array); +expect(path).to.be.a.directory(msg).and.not.have.deep.contents(array, msg); +// #5 +expect(path).to.be.a.directory(msg).and.include.contents(array); +expect(path).to.be.a.directory(msg).and.include.contents(array, msg); +// #6 +expect(path).to.be.a.directory(msg).and.not.include.contents(array); +expect(path).to.be.a.directory(msg).and.not.include.contents(array, msg); + +// #1 +path.should.be.a.directory(msg).with.contents(array); +path.should.be.a.directory(msg).with.contents(array, msg); +// #2 +path.should.be.a.directory(msg).and.not.have.contents(array); +path.should.be.a.directory(msg).and.not.have.contents(array, msg); +// #3 +path.should.be.a.directory(msg).with.deep.contents(array); +path.should.be.a.directory(msg).with.deep.contents(array, msg); +// #4 +path.should.be.a.directory(msg).and.not.have.deep.contents(array); +path.should.be.a.directory(msg).and.not.have.deep.contents(array, msg); +// #5 +path.should.be.a.directory(msg).and.include.contents(array); +path.should.be.a.directory(msg).and.include.contents(array, msg); +// #6 +path.should.be.a.directory(msg).and.not.include.contents(array); +path.should.be.a.directory(msg).and.not.include.contents(array, msg); + +assert.directoryContent(path, array); +assert.directoryContent(path, array, msg); +assert.notDirectoryContent(path, array); +assert.notDirectoryContent(path, array, msg); +assert.directoryDeepContent(path, array); +assert.directoryDeepContent(path, array, msg); +assert.notDirectoryDeepContent(path, array); +assert.notDirectoryDeepContent(path, array, msg); +assert.directoryInclude(path, array); +assert.directoryInclude(path, array, msg); +assert.notDirectoryInclude(path, array); +assert.notDirectoryInclude(path, array, msg); + +// directory().with.files([...]) +// #1 +expect(path).to.be.a.directory(msg).with.files(array); +expect(path).to.be.a.directory(msg).with.files(array, msg); +// #2 +expect(path).to.be.a.directory(msg).with.files(array); +expect(path).to.be.a.directory(msg).with.files(array, msg); +// #3 +expect(path).to.be.a.directory(msg).and.not.have.files(array); +expect(path).to.be.a.directory(msg).and.not.have.files(array, msg); +// #4 +expect(path).to.be.a.directory(msg).and.not.have.files(array); +expect(path).to.be.a.directory(msg).and.not.have.files(array, msg); +// #5 +expect(path).to.be.a.directory(msg).with.deep.files(array, msg); +expect(path).to.be.a.directory(msg).with.deep.files(array); +// #6 +expect(path).to.be.a.directory(msg).with.deep.files(array); +expect(path).to.be.a.directory(msg).with.deep.files(array, msg); +// #7 +expect(path).to.be.a.directory(msg).and.not.have.deep.files(array); +expect(path).to.be.a.directory(msg).and.not.have.deep.files(array, msg); +// #8 +expect(path).to.be.a.directory(msg).and.not.have.deep.files(array); +expect(path).to.be.a.directory(msg).and.not.have.deep.files(array, msg); +// #9 +expect(path).to.be.a.directory(msg).and.include.files(array); +expect(path).to.be.a.directory(msg).and.include.files(array, msg); +// #10 +expect(path).to.be.a.directory(msg).and.not.include.files(array); +expect(path).to.be.a.directory(msg).and.not.include.files(array, msg); + +// #1 +path.should.be.a.directory(msg).with.files(array); +path.should.be.a.directory(msg).with.files(array, msg); +// #2 +path.should.be.a.directory().and.not.have.files(array); +path.should.be.a.directory(msg).and.not.have.files(array); +path.should.be.a.directory(msg).and.not.have.files(array, msg); +// #3 +path.should.be.a.directory().with.deep.files(array); +path.should.be.a.directory(msg).with.deep.files(array); +path.should.be.a.directory(msg).with.deep.files(array, msg); +// #4 +path.should.be.a.directory(msg).and.not.have.deep.files(array); +path.should.be.a.directory(msg).and.not.have.deep.files(array, msg); +// #5 +path.should.be.a.directory(msg).and.include.files(array); +path.should.be.a.directory(msg).and.include.files(array, msg); +// #6 +path.should.be.a.directory(msg).and.not.include.files(array); +path.should.be.a.directory(msg).and.not.include.files(array, msg); + +assert.directoryFiles(path, array); +assert.directoryFiles(path, array, msg); +assert.notDirectoryFiles(path, array); +assert.notDirectoryFiles(path, array, msg); +assert.directoryDeepFiles(path, array); +assert.directoryDeepFiles(path, array, msg); +assert.notDirectoryDeepFiles(path, array); +assert.notDirectoryDeepFiles(path, array, msg); +assert.directoryIncludeFiles(path, array); +assert.directoryIncludeFiles(path, array, msg); +assert.notDirectoryIncludeFiles(path, array); +assert.notDirectoryIncludeFiles(path, array, msg); + +// directory().with.subDirs([...]) +// #1 +expect(path).to.be.a.directory(msg).with.subDirs(array); +expect(path).to.be.a.directory(msg).with.subDirs(array, msg); +// #2 +expect(path).to.be.a.directory(msg).and.not.have.subDirs(array); +expect(path).to.be.a.directory(msg).and.not.have.subDirs(array, msg); +// #3 +expect(path).to.be.a.directory(msg).with.deep.subDirs(array); +expect(path).to.be.a.directory(msg).with.deep.subDirs(array, msg); +// #4 +expect(path).to.be.a.directory(msg).and.not.have.deep.subDirs(array); +expect(path).to.be.a.directory(msg).and.not.have.deep.subDirs(array, msg); +// #5 +expect(path).to.be.a.directory(msg).and.include.subDirs(array); +expect(path).to.be.a.directory(msg).and.include.subDirs(array, msg); +// #6 +expect(path).to.be.a.directory(msg).and.not.include.subDirs(array); +expect(path).to.be.a.directory(msg).and.not.include.subDirs(array, msg); + +// #1 +path.should.be.a.directory(msg).with.subDirs(array); +path.should.be.a.directory(msg).with.subDirs(array, msg); +// #2 +path.should.be.a.directory(msg).and.not.have.subDirs(array); +path.should.be.a.directory(msg).and.not.have.subDirs(array, msg); +// #3 +path.should.be.a.directory(msg).with.deep.subDirs(array); +path.should.be.a.directory(msg).with.deep.subDirs(array, msg); +// #4 +path.should.be.a.directory(msg).and.not.have.deep.subDirs(array); +path.should.be.a.directory(msg).and.not.have.deep.subDirs(array, msg); +// #5 +path.should.be.a.directory(msg).and.include.subDirs(array); +path.should.be.a.directory(msg).and.include.subDirs(array, msg); +// #6 +path.should.be.a.directory(msg).and.not.include.subDirs(array); +path.should.be.a.directory(msg).and.not.include.subDirs(array, msg); + +assert.directorySubDirs(path, array, msg); +assert.notDirectorySubDirs(path, array, msg); +assert.directoryDeepSubDirs(path, array, msg); +assert.notDirectoryDeepSubDirs(path, array, msg); +assert.directoryIncludeSubDirs(path, array, msg); +assert.notDirectoryIncludeSubDirs(path, array, msg); + +// directory().and.equal(otherPath) +// #1 +expect(path).to.be.a.directory(msg).and.equal(otherPath); +expect(path).to.be.a.directory(msg).and.equal(otherPath, msg); +// #2 +expect(path).to.be.a.directory(msg).and.not.equal(otherPath); +expect(path).to.be.a.directory(msg).and.not.equal(otherPath, msg); +// #3 +expect(path).to.be.a.directory(msg).and.deep.equal(otherPath); +expect(path).to.be.a.directory(msg).and.deep.equal(otherPath, msg); +// #4 +expect(path).to.be.a.directory(msg).and.not.deep.equal(otherPath); +expect(path).to.be.a.directory(msg).and.not.deep.equal(otherPath, msg); + +// #1 +path.should.be.a.directory(msg).and.equal(otherPath); +path.should.be.a.directory(msg).and.equal(otherPath, msg); +// #2 +path.should.be.a.directory(msg).and.not.equal(otherPath); +path.should.be.a.directory(msg).and.not.equal(otherPath, msg); +// #3 +path.should.be.a.directory(msg).and.deep.equal(otherPath); +path.should.be.a.directory(msg).and.deep.equal(otherPath, msg); +// #4 +path.should.be.a.directory(msg).and.not.deep.equal(otherPath); +path.should.be.a.directory(msg).and.not.deep.equal(otherPath, msg); + +assert.directoryEqual(path, otherPath, msg); +assert.notDirectoryEqual(path, otherPath, msg); +assert.directoryDeepEqual(path, otherPath, msg); +assert.notDirectoryDeepEqual(path, otherPath, msg); + +// file() +expect(path).to.be.a.file(); +expect(path).to.be.a.file(msg); +expect(path).to.not.be.a.file(); +expect(path).to.not.be.a.file(msg); + +path.should.be.a.file(); +path.should.be.a.file(msg); +path.should.not.be.a.file(); +path.should.not.be.a.file(msg); + +assert.isFile(path); +assert.isFile(path, msg); +assert.notIsFile(path); +assert.notIsFile(path, msg); + +// file().and.empty +expect(path).to.be.a.file(msg).and.empty; +expect(path).to.be.a.file(msg).and.not.empty; + +path.should.be.a.file(msg).and.empty; +path.should.be.a.file(msg).and.not.empty; + +assert.isEmptyFile(path, msg); +assert.notIsEmptyFile(path, msg); + +// file().with.content(str) +expect(path).to.be.a.file(msg).with.content(data); +expect(path).to.be.a.file(msg).with.content(data, msg); +expect(path).to.be.a.file(msg).and.not.have.content(data); +expect(path).to.be.a.file(msg).and.not.have.content(data, msg); + +path.should.be.a.file(msg).with.content(data); +path.should.be.a.file(msg).with.content(data, msg); +path.should.be.a.file(msg).and.not.have.content(data); +path.should.be.a.file(msg).and.not.have.content(data, msg); + +assert.fileContent(path, data); +assert.fileContent(path, data, msg); +assert.notFileContent(path, data); +assert.notFileContent(path, data, msg); + +// file().with.contents.that.match(/xyz/) +// expect(path).to.be.a.file(msg).with.contents.that.match(/xyz/, msg); +// expect(path).to.be.a.file(msg).and.not.have.contents.that.match(/xyz/, msg); + +// path.should.be.a.file(msg).with.contents.that.match(/xyz/, msg); +// path.should.be.a.file(msg).and.not.have.contents.that.match(/xyz/, msg); + +assert.fileContentMatch(path, /xyz/); +assert.fileContentMatch(path, /xyz/, msg); +assert.notFileContentMatch(path, /xyz/); +assert.notFileContentMatch(path, /xyz/, msg); + +// file().and.equal(otherPath) +expect(path).to.be.a.file(msg).and.equal(otherPath); +expect(path).to.be.a.file(msg).and.equal(otherPath, msg); +expect(path).to.be.a.file(msg).and.not.equal(otherPath); +expect(path).to.be.a.file(msg).and.not.equal(otherPath, msg); + +path.should.be.a.file(msg).and.equal(otherPath); +path.should.be.a.file(msg).and.equal(otherPath, msg); +path.should.be.a.file(msg).and.not.equal(otherPath); +path.should.be.a.file(msg).and.not.equal(otherPath, msg); + +assert.fileEqual(path, otherPath, msg); +assert.notFileEqual(path, otherPath, msg); + +// file().with.json +expect(path).to.be.a.file(msg).with.json; +expect(path).to.be.a.file(msg).with.not.json; + +path.should.be.a.file(msg).with.json; +path.should.be.a.file(msg).with.not.json; + +assert.jsonFile(path); +assert.jsonFile(path, msg); +assert.notJsonFile(path); +assert.notJsonFile(path, msg); + +// file().using.json.schema(obj) +expect(path).to.be.a.file(msg).with.json.using.schema(obj); +expect(path).to.be.a.file(msg).with.json.not.using.schema(obj); + +path.should.be.a.file(msg).with.json.using.schema(obj); +path.should.be.a.file(msg).with.json.not.using.schema(obj); + +assert.jsonSchemaFile(path, schema); +assert.jsonSchemaFile(path, schema, msg); +assert.notJsonSchemaFile(path, schema); +assert.notJsonSchemaFile(path, schema, msg); diff --git a/types/chai-fs/index.d.ts b/types/chai-fs/index.d.ts new file mode 100644 index 0000000000..3b82eee078 --- /dev/null +++ b/types/chai-fs/index.d.ts @@ -0,0 +1,222 @@ +// Type definitions for chai-fs 2.0 +// Project: https://github.com/chaijs/chai-fs +// Definitions by: Dimitar Danailov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/// +/// + +declare global { + namespace Chai { + interface TypeComparison { + path(msg?: string): Assertion; + directory(msg?: string): Assertion; + file(msg?: string): Assertion; + } + + interface Deep { + contents(array: any[], msg?: string): Assertion; + files(array: any[], msg?: string): Assertion; + subDirs(array: any[], msg?: string): Assertion; + } + + interface Include { + contents(array: any[], msg?: string): Assertion; + files(array: any[], msg?: string): Assertion; + subDirs(array: any[], msg?: string): Assertion; + } + + interface LanguageChains { + json: Assertion; + using: Assertion; + } + + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + // Basename + basename(path?: string, name?: string, msg?: string): Assertion; + notBasename(path: string, name: string, msg?: string): Assertion; + + // Dirname + dirname(name: string, msg?: string): Assertion; + notDirname(path: string, name: string, msg?: string): Assertion; + + // Еxtname + extname(path: string, name?: string, msg?: string): Assertion; + notExtname(path: string, name: string, msg?: string): Assertion; + + // Path + pathExists(path: string, msg?: string): Assertion; + notPathExists(path: string, msg?: string): Assertion; + + // Directory + isDirectory(path: string, msg?: string): Assertion; + notIsDirectory(path: string, msg?: string): Assertion; + + // directory().and.empty + isEmptyDirectory(path: string, msg?: string): Assertion; + notIsEmptyDirectory(path: string, msg?: string): Assertion; + + // directory().with.contents([...]) + contents(array: any[], msg?: string): Assertion; + directoryContent(path: string, array: any[], msg?: string): Assertion; + notDirectoryContent(path: string, array: any[], msg?: string): Assertion; + directoryDeepContent(path: string, array: any[], msg?: string): Assertion; + notDirectoryDeepContent(path: string, array: any[], msg?: string): Assertion; + directoryInclude(path: string, array: any[], msg?: string): Assertion; + notDirectoryInclude(path: string, array: any[], msg?: string): Assertion; + + // directory().with.files([...]) + files(array: any[], msg?: string): Assertion; + directoryFiles(path: string, array: any[], msg?: string): Assertion; + notDirectoryFiles(path: string, array: any[], msg?: string): Assertion; + directoryDeepFiles(path: string, array: any[], msg?: string): Assertion; + notDirectoryDeepFiles(path: string, array: any[], msg?: string): Assertion; + directoryIncludeFiles(path: string, array: any[], msg?: string): Assertion; + notDirectoryIncludeFiles(path: string, array: any[], msg?: string): Assertion; + + // directory().with.subDirs([...]) + subDirs(array: any[], msg?: string): Assertion; + directorySubDirs(path: string, array: any[], msg?: string): Assertion; + notDirectorySubDirs(path: string, array: any[], msg?: string): Assertion; + directoryDeepSubDirs(path: string, array: any[], msg?: string): Assertion; + notDirectoryDeepSubDirs(path: string, array: any[], msg?: string): Assertion; + directoryIncludeSubDirs(path: string, array: any[], msg?: string): Assertion; + notDirectoryIncludeSubDirs(path: string, array: any[], msg?: string): Assertion; + + // directory().and.equal(otherPath) + directoryEqual(path: string, otherPath: string, msg?: string): Assertion; + notDirectoryEqual(path: string, otherPath: string, msg?: string): Assertion; + directoryDeepEqual(path: string, otherPath: string, msg?: string): Assertion; + notDirectoryDeepEqual(path: string, otherPath: string, msg?: string): Assertion; + + // file + isFile(path: string, msg?: string): Assertion; + notIsFile(path: string, msg?: string): Assertion; + + // file().and.empty + isEmptyFile(path: string, msg?: string): Assertion; + notIsEmptyFile(path: string, msg?: string): Assertion; + + // file().with.content(str) + content(data: any, msg?: string): Assertion; + fileContent(path: string, data: any, msg?: string): Assertion; + notFileContent(path: string, data: any, msg?: string): Assertion; + + // file().with.contents.that.match(/xyz/) + fileContentMatch(path: string, regExp: RegExp, msg?: string): Assertion; + notFileContentMatch(path: string, regExp: RegExp, msg?: string): Assertion; + + // file().and.equal(otherPath) + fileEqual(path: string, otherPath: string, msg?: string): Assertion; + notFileEqual(path: string, otherPath: string, msg?: string): Assertion; + + // file().with.json + jsonFile(path: string, msg?: string): Assertion; + notJsonFile(path: string, msg?: string): Assertion; + + // file().using.json.schema(obj) + jsonSchemaFile(path: string, schema: any, msg?: string): Assertion; + notJsonSchemaFile(path: string, schema: any, msg?: string): Assertion; + schema(obj: object): Assertion; + } + + interface Assert { + // Basename + basename(path: string, name: string, msg?: string): void; + notBasename(path: string, name: string, msg?: string): void; + + // Dirname + dirname(path: string, name?: string, msg?: string): void; + notDirname(path: string, name: string, msg?: string): void; + + // Еxtname + extname(path: string, name: string, msg?: string): void; + notExtname(path: string, name: string, msg?: string): void; + + // Path + path(msg?: string): void; + pathExists(path: string, msg?: string): void; + notPathExists(path: string, msg?: string): void; + + // Directory + directory(msg?: string): void; + isDirectory(path: string, msg?: string): void; + notIsDirectory(path: string, msg?: string): void; + + // directory().and.empty + isEmptyDirectory(path: string, msg?: string): void; + notIsEmptyDirectory(path: string, msg?: string): void; + + // directory().with.contents([...]) + contents(array: any[], msg?: string): void; + directoryContent(path: string, array: any[], msg?: string): void; + notDirectoryContent(path: string, array: any[], msg?: string): void; + directoryDeepContent(path: string, array: any[], msg?: string): void; + notDirectoryDeepContent(path: string, array: any[], msg?: string): void; + directoryInclude(path: string, array: any[], msg?: string): void; + notDirectoryInclude(path: string, array: any[], msg?: string): void; + + // directory().with.files([...]) + files(array: any[], msg?: string): void; + directoryFiles(path: string, array: any[], msg?: string): void; + notDirectoryFiles(path: string, array: any[], msg?: string): void; + directoryDeepFiles(path: string, array: any[], msg?: string): void; + notDirectoryDeepFiles(path: string, array: any[], msg?: string): void; + directoryIncludeFiles(path: string, array: any[], msg?: string): void; + notDirectoryIncludeFiles(path: string, array: any[], msg?: string): void; + + // directory().with.subDirs([...]) + subDirs(array: any[], msg?: string): void; + directorySubDirs(path: string, array: any[], msg?: string): void; + notDirectorySubDirs(path: string, array: any[], msg?: string): void; + directoryDeepSubDirs(path: string, array: any[], msg?: string): void; + notDirectoryDeepSubDirs(path: string, array: any[], msg?: string): void; + directoryIncludeSubDirs(path: string, array: any[], msg?: string): void; + notDirectoryIncludeSubDirs(path: string, array: any[], msg?: string): void; + + // directory().and.equal(otherPath) + directoryEqual(path: string, otherPath: string, msg?: string): void; + notDirectoryEqual(path: string, otherPath: string, msg?: string): void; + directoryDeepEqual(path: string, otherPath: string, msg?: string): void; + notDirectoryDeepEqual(path: string, otherPath: string, msg?: string): void; + + // file + file(msg?: string): void; + isFile(path: string, msg?: string): void; + notIsFile(path: string, msg?: string): void; + + // file().and.empty + isEmptyFile(path: string, msg?: string): void; + notIsEmptyFile(path: string, msg?: string): void; + + // file().with.content(str) + fileContent(path: string, data: any, msg?: string): void; + notFileContent(path: string, data: any, msg?: string): void; + + // file().with.contents.that.match(/xyz/) + fileContentMatch(path: string, regExp: RegExp, msg?: string): void; + notFileContentMatch(path: string, regExp: RegExp, msg?: string): void; + + // file().and.equal(otherPath) + fileEqual(path: string, otherPath: string, msg?: string): void; + notFileEqual(path: string, otherPath: string, msg?: string): void; + + // file().with.json + jsonFile(path: string, msg?: string): void; + notJsonFile(path: string, msg?: string): void; + + // file().using.json.schema(obj) + jsonSchemaFile(path: string, schema: any, msg?: string): void; + notJsonSchemaFile(path: string, schema: any, msg?: string): void; + schema(obj: object): void; + } + } +} + +declare function chaiFs(chai: any, utils: any): void; +export = chaiFs; + +interface Object { + should: Chai.Assertion; +} diff --git a/types/chai-fs/tsconfig.json b/types/chai-fs/tsconfig.json new file mode 100644 index 0000000000..8ca5abeb7d --- /dev/null +++ b/types/chai-fs/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", + "chai-fs-tests.ts" + ] +} diff --git a/types/chai-fs/tslint.json b/types/chai-fs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chai-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chai-http/tsconfig.json b/types/chai-http/tsconfig.json index 3554b4ab09..45d92cf188 100644 --- a/types/chai-http/tsconfig.json +++ b/types/chai-http/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/chai-jest-snapshot/tslint.json b/types/chai-jest-snapshot/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/chai-jest-snapshot/tslint.json +++ b/types/chai-jest-snapshot/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/chai-jquery/chai-jquery-tests.ts b/types/chai-jquery/chai-jquery-tests.ts index 894acf9ca5..bd798be847 100644 --- a/types/chai-jquery/chai-jquery-tests.ts +++ b/types/chai-jquery/chai-jquery-tests.ts @@ -67,6 +67,10 @@ function test_disabled() { expect($('#foo')).to.be.disabled; } +function test_enabled() { + expect($('#foo')).to.be.enabled; +} + function test_empty() { $('.empty').should.be.empty; expect($('body')).not.to.be.empty; diff --git a/types/chai-jquery/index.d.ts b/types/chai-jquery/index.d.ts index bd6826ca08..c2827d2e05 100644 --- a/types/chai-jquery/index.d.ts +++ b/types/chai-jquery/index.d.ts @@ -25,6 +25,7 @@ declare namespace Chai { selected(): Assertion; checked(): Assertion; disabled(): Assertion; + enabled(): Assertion; (selector: string): Assertion; } diff --git a/types/chai/chai-tests.ts b/types/chai/chai-tests.ts index ae8a71766e..36002d9bfa 100644 --- a/types/chai/chai-tests.ts +++ b/types/chai/chai-tests.ts @@ -808,6 +808,24 @@ function frozen() { expect(Object.freeze({})).to.be.frozen; ({}).should.be.not.frozen; Object.freeze({}).should.be.frozen; + + expect([1, 2, 3]).to.have.all.members([1, 2, 3]); + expect([1, 2, 3]).to.have.all.members(Object.freeze([1, 2, 3])); + + expect({1: "", 2: "", 3: ""}).to.have.all.keys([1, 2, 3]); + expect({1: "", 2: "", 3: ""}).to.have.all.keys(Object.freeze([1, 2, 3])); + + assert.notDeepInclude([1, 2, 3], 1); + assert.notDeepInclude(Object.freeze([1, 2, 3]), 1); + + assert.include([1, 2, 3], 1); + assert.include(Object.freeze([1, 2, 3]), 1); + + assert.notInclude([1, 2, 3], 1); + assert.notInclude(Object.freeze([1, 2, 3]), 1); + + expect([1, 2, 3]).to.have.oneOf([1, 2, 3]); + expect([1, 2, 3]).to.have.oneOf(Object.freeze([1, 2, 3])); } class PoorlyConstructedError { diff --git a/types/chai/index.d.ts b/types/chai/index.d.ts index 72ebc0191d..5f73803757 100644 --- a/types/chai/index.d.ts +++ b/types/chai/index.d.ts @@ -118,7 +118,7 @@ declare namespace Chai { extensible: Assertion; sealed: Assertion; frozen: Assertion; - oneOf(list: any[], message?: string): Assertion; + oneOf(list: ReadonlyArray, message?: string): Assertion; } interface LanguageChains { @@ -235,7 +235,7 @@ declare namespace Chai { interface Keys { (...keys: string[]): Assertion; - (keys: any[]|Object): Assertion; + (keys: ReadonlyArray|Object): Assertion; } interface Throw { @@ -252,7 +252,7 @@ declare namespace Chai { } interface Members { - (set: any[], message?: string): Assertion; + (set: ReadonlyArray, message?: string): Assertion; } interface PropertyChange { @@ -696,7 +696,7 @@ declare namespace Chai { * @param needle Potential value contained in haystack. * @param message Message to display on error. */ - include(haystack: T[], needle: T, message?: string): void; + include(haystack: ReadonlyArray, needle: T, message?: string): void; /** * Asserts that haystack does not include needle. @@ -705,7 +705,7 @@ declare namespace Chai { * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notInclude(haystack: string | any[], needle: any, message?: string): void; + notInclude(haystack: string | ReadonlyArray, needle: any, message?: string): void; /** * Asserts that haystack includes needle. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used. @@ -732,7 +732,7 @@ declare namespace Chai { * @param needle Potential expected substring of haystack. * @param message Message to display on error. */ - notDeepInclude(haystack: string | any[], needle: any, message?: string): void; + notDeepInclude(haystack: string | ReadonlyArray, needle: any, message?: string): void; /** * Asserts that ‘haystack’ includes ‘needle’. Can be used to assert the inclusion of a subset of properties in an object. diff --git a/types/chart.js/chart.js-tests.ts b/types/chart.js/chart.js-tests.ts index 41ab453e0f..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,9 +19,11 @@ 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] + data: [1, null, 3] } ] }, @@ -36,6 +40,7 @@ const chart: Chart = new Chart(new CanvasRenderingContext2D(), { tooltips: { filter: data => Number(data.yLabel) > 0, intersect: true, + mode: 'index', itemSort: (a, b) => Math.random() - 0.5, position: "average", caretPadding: 2, @@ -125,6 +130,7 @@ const chartConfig: Chart.ChartConfiguration = { backgroundColor: '#37738353', borderColor: '#37738353', borderWidth: 3, + borderCapStyle: 'round', fill: true }] }, diff --git a/types/chart.js/index.d.ts b/types/chart.js/index.d.ts index 37f4757460..2803def896 100644 --- a/types/chart.js/index.d.ts +++ b/types/chart.js/index.d.ts @@ -10,7 +10,6 @@ // Guillaume Rodriguez // Simon Archer // Ken Elkabany -// Slavik Nychkalo // Francesco Benedetto // Alexandros Dorodoulis // Manuel Heidrich @@ -174,6 +173,8 @@ declare namespace Chart { type PositionType = 'left' | 'right' | 'top' | 'bottom'; + type InteractionMode = 'point' | 'nearest' | 'single' | 'label' | 'index' | 'x-axis' | 'dataset' | 'x' | 'y'; + interface ChartArea { top: number; right: number; @@ -185,10 +186,10 @@ declare namespace Chart { text?: string; fillStyle?: string; hidden?: boolean; - lineCap?: string; + lineCap?: 'butt' | 'round' | 'square'; lineDash?: number[]; lineDashOffset?: number; - lineJoin?: string; + lineJoin?: 'bevel' | 'round' | 'miter'; lineWidth?: number; strokeStyle?: string; pointStyle?: PointStyle; @@ -331,7 +332,7 @@ declare namespace Chart { interface ChartTooltipOptions { enabled?: boolean; custom?(a: any): void; - mode?: string; + mode?: InteractionMode; intersect?: boolean; backgroundColor?: ChartColor; titleFontFamily?: string; @@ -373,7 +374,7 @@ declare namespace Chart { type ChartTooltipPositioner = (elements: any[], eventPosition: Point) => Point; interface ChartHoverOptions { - mode?: string; + mode?: InteractionMode; animationDuration?: number; intersect?: boolean; onHover?(this: Chart, event: MouseEvent, activeElements: Array<{}>): any; @@ -479,7 +480,12 @@ declare namespace Chart { fontStyle?: string; } - interface TickOptions { + interface TickOptions extends NestedTickOptions { + minor?: NestedTickOptions | false; + major?: NestedTickOptions | false; + } + + interface NestedTickOptions { autoSkip?: boolean; autoSkipPadding?: number; backdropColor?: ChartColor; @@ -504,6 +510,7 @@ declare namespace Chart { reverse?: boolean; showLabelBackdrop?: boolean; source?: 'auto' | 'data' | 'labels'; + stepSize?: number; suggestedMax?: number; suggestedMin?: number; } @@ -540,15 +547,15 @@ declare namespace Chart { backgroundColor?: ChartColor | ChartColor[]; borderWidth?: number | number[]; borderColor?: ChartColor | ChartColor[]; - borderCapStyle?: string; + borderCapStyle?: 'butt' | 'round' | 'square'; borderDash?: number[]; borderDashOffset?: number; - borderJoinStyle?: string; + borderJoinStyle?: 'bevel' | 'round' | 'miter'; borderSkipped?: PositionType; - data?: number[] | ChartPoint[]; + 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; @@ -565,7 +572,7 @@ declare namespace Chart { pointStyle?: PointStyle | HTMLImageElement | HTMLCanvasElement | Array; xAxisID?: string; yAxisID?: string; - type?: string; + type?: ChartType | string; hidden?: boolean; hideInLegendAndTooltip?: boolean; showLine?: boolean; diff --git a/types/chartist/chartist-tests.ts b/types/chartist/chartist-tests.ts index bd7006723e..cb7f884264 100644 --- a/types/chartist/chartist-tests.ts +++ b/types/chartist/chartist-tests.ts @@ -197,6 +197,7 @@ new Chartist.Bar('.ct-chart', { }, { // Default mobile configuration stackBars: true, + stackMode: 'accumulate', axisX: { labelInterpolationFnc: (value: string) => { return value.split(/\s+/).map((word: string) => { diff --git a/types/chartist/index.d.ts b/types/chartist/index.d.ts index 3d72210c73..9b096839cc 100644 --- a/types/chartist/index.d.ts +++ b/types/chartist/index.d.ts @@ -283,6 +283,7 @@ declare namespace Chartist { * If set to true this property will cause the series bars to be stacked and form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect. */ stackBars?: boolean; + stackMode?: 'overlap' | 'accumulate'; horizontalBars?: boolean; distributeSeries?: boolean; diff --git a/types/chartmogul-node/common.d.ts b/types/chartmogul-node/common.d.ts index ced10f98d7..d12587f090 100644 --- a/types/chartmogul-node/common.d.ts +++ b/types/chartmogul-node/common.d.ts @@ -1,5 +1,5 @@ export interface Map { - [key: string]: any + [key: string]: any; } export interface CursorParams { page?: number; @@ -15,9 +15,9 @@ export interface Cursor { total_pages?: number; } export interface Entries extends Cursor { - entries: T[] + entries: T[]; } -interface Summary { +export interface Summary { current: number; previous: number; ['percentage-change']: number; @@ -25,4 +25,4 @@ interface Summary { export interface EntriesSummary { entries: T[]; summary: Summary; -} \ No newline at end of file +} diff --git a/types/cheerio/index.d.ts b/types/cheerio/index.d.ts index cb8031705e..6c893021a3 100644 --- a/types/cheerio/index.d.ts +++ b/types/cheerio/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for Cheerio v0.22.0 // Project: https://github.com/cheeriojs/cheerio -// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani , LiJinyao , Chennakrishna +// Definitions by: Bret Little , VILIC VANE , Wayne Maurer , Umar Nizamani , LiJinyao , Chennakrishna , AzSiAz // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface Cheerio { @@ -111,9 +111,8 @@ interface Cheerio { eq(index: number): Cheerio; - get(): string[]; - get(): CheerioElement[]; - get(index: number): CheerioElement; + get(): any[]; + get(index: number): any; index(): number; index(selector: string): number; diff --git a/types/chordsheetjs/chordsheetjs-tests.ts b/types/chordsheetjs/chordsheetjs-tests.ts new file mode 100644 index 0000000000..7f01828e7f --- /dev/null +++ b/types/chordsheetjs/chordsheetjs-tests.ts @@ -0,0 +1,5 @@ +import { Song, HtmlTableFormatter } from 'chordsheetjs'; + +const song = new Song({ key: 'value' }); +const formatter = new HtmlTableFormatter(); +formatter.format(song); diff --git a/types/chordsheetjs/index.d.ts b/types/chordsheetjs/index.d.ts new file mode 100644 index 0000000000..ee2e69593f --- /dev/null +++ b/types/chordsheetjs/index.d.ts @@ -0,0 +1,372 @@ +// Type definitions for chordsheetjs 2.8 +// Project: https://github.com/martijnversluis/ChordSheetJS +// Definitions by: Adam Bloom +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +/** + * Represents a chord with the corresponding (partial) lyrics + */ +export class ChordLyricsPair { + /** + * Initialises a ChordLyricsPair + * @param chords The chords + * @param lyrics The lyrics + */ + constructor(chords: string, lyrics: string); + + chords: string; + lyrics: string; + + /** + * Indicates whether a ChordLyricsPair should be visible in a formatted chord sheet (except for ChordPro sheets) + */ + isRenderable: () => boolean; + + /** + * Returns a deep copy of the ChordLyricsPair, useful when programmatically transforming a song + */ + clone: () => ChordLyricsPair; + + toString: () => string; +} + +/** + * Represents a tag/directive. See https://www.chordpro.org/chordpro/ChordPro-Directives.html + */ +export class Tag { + constructor(name: string, value: string | null); + + /** + * The tag full name. When the original tag used the short name, `name` will return the full name. + */ + name: string; + + /** + * The tag value + */ + value: string | null; + + static parse(tag: string): Tag | null; + static parseWithRegex(tag: string, regex: string): Tag | null; + + /** + * The original tag name that was used to construct the tag. + */ + originalName: string; + + /** + * Checks whether the tag value is a non-empty string. + */ + hasValue(): boolean; + + /** + * Checks whether the tag is usually rendered inline. It currently only applies to comment tags. + */ + isRenderable(): boolean; + + /** + * Checks whether the tag is either a standard meta tag or a custom meta directive (`{x_some_name}`) + */ + isMetaTag(): boolean; + + /** + * Returns a clone of the tag. + */ + clone(): Tag; + + toString(): string; +} + +/** + * Represents a line in a chord sheet, consisting of items of type ChordLyricsPair or Tag + */ +export class Line { + constructor(); + + /** + * The items (ChordLyricsPair or Tag) of which the line consists + */ + items: Array; + + /** + * The line type, This is set by the ChordProParser when it read tags like {start_of_chorus} or {start_of_verse} + * Values can be 'verse', 'chorus' or 'none' + */ + type: 'verse' | 'chorus' | 'none'; + + /** + * Indicates whether the line contains any items + */ + isEmpty(): boolean; + + /** + * Adds an item to the line + * @param item The item to be added + */ + addItem(item: ChordLyricsPair | Tag): void; + + /** + * Indicates whether the line contains items that are renderable + */ + hasRenderableItems(): boolean; + + /** + * Returns a deep copy of the line and all of its items + */ + clone(): Line; + + /** + * Indicates whether the line type is 'verse' + */ + isVerse(): boolean; + + /** + * Indicates whether the line type is 'chorus' + */ + isChorus(): boolean; + + /** + * Indicates whether the line contains items that are renderable. Please use hasRenderableItems + * @deprecated + */ + hasContent(): boolean; + + addChordLyricsPair( + chords: ChordLyricsPair | string, + lyrics: string + ): ChordLyricsPair; + ensureChordLyricsPair(): void; + chords(chr: string): void; + lyrics(chr: string): void; + addTag(name: Tag | string, value: string | null): Tag; +} + +/** + * Represents a paragraph of lines in a chord sheet + */ +export class Paragraph { + constructor(); + + /** + * The Line items of which the paragraph consists + */ + lines: Line[]; + + addLine(line: Line): void; + + /** + * Tries to determine the common type for all lines. If the types for all lines are equal, it returns that type. + * If not, it returns 'indeterminate'. + */ + type: string; +} + +/** + * Represents a song in a chord sheet. Currently a chord sheet can only have one song. + */ +export class Song { + constructor(metadata: object); + + /** + * The Line items of which the song consists + */ + lines: Line[]; + + /** + * The Paragraph items of which the song consists + */ + paragraphs: Paragraph[]; + + currentLine: Line; + currentParagraph: Paragraph; + assignMetaData(metadata: object): void; + + /** + * Returns the song lines, skipping the leading empty lines (empty as in not rendering any content). This is useful + * if you want to skip the "header lines": the lines that only contain meta data. + */ + bodyLines: Line[]; + + chords(chr: string): void; + lyrics(chr: string): void; + addLine(): Line; + setCurrentLineType(type: string): void; + flushLine(): void; + finish(): void; + addChordLyricsPair(): ChordLyricsPair; + ensureLine(): void; + addParagraph(): Paragraph; + ensureParagraph(): void; + addTag(tagContents: string): Tag; + + /** + * Returns a deep clone of the song + */ + clone(): Song; + + setMetaData(name: string, value: string): void; + metaData: object; + optimizedMetaData: object; + getOptimizedMetaData(): object; + optimizeMetaDataValue( + valueSet: string[] | undefined + ): string | string[] | null; + getMetaData(name: string): string | null; +} + +/** + * Represents a parser warning, currently only used by ChordProParser. + */ +export class ParserWarning { + /** + * The warning message + */ + message: string; + + /** + * The line number on which the warning occurred + */ + lineNumber: string; + + toString(): string; +} + +/** + * Parses a ChordPro chord sheet + */ +export class ChordProParser { + /** + * Parses a ChordPro chord sheet into a song + * @param chordProChordSheet The ChordPro chord sheet + */ + parse(chordProChordSheet: string): Song; + + song: Song; + lineNumber: number; + sectionType: string; + warnings: ParserWarning[]; + + parseDocument(document: string): void; + readLyrics(chr: string): void; + readChords(chr: string): void; + readTag(chr: string): void; + readComment(chr: string): void; + finishTag(): void; + resetTag(): void; + applyTag(tag: Tag): void; + startSection(sectionType: string, tag: Tag): void; + endSection(sectionType: string, tag: Tag): void; + checkCurrentSectionType(sectionType: string, tag: Tag): void; + addWarning(message: string): void; +} + +export interface ChordSheetParserProps { + preserveWhitespace: boolean; +} + +/** + * Formats a song into a plain text chord sheet + */ +export class ChordSheetParser { + constructor(props: ChordSheetParserProps); + + song: Song; + lines: Line[]; + songLine: Line; + chordLyricsPair: ChordLyricsPair; + currentLine: number; + lineCount: number; + processingText: string; + preserveWhitespace: boolean; + + /** + * Parses a chord sheet into a song + * @param chordSheet The ChordPro chord sheet + */ + parse(chordSheet: string): Song; + + parseLine(line: string): void; + parseNonEmptyLine(line: string): void; + initialize(document: string): void; + readLine(): Line; + hasNextLine(): boolean; + parseLyricsWithChords(chordsLine: string, lyricsLine: string): void; + processCharacters(chordsLine: string, lyricsLine: string): void; + addCharacter(chr: string, nextChar: string): void; + shouldAddCharacterToChords(nextChar: string): boolean; + ensureChordLyricsPairInitialized(): void; +} + +export interface SongHeader { + title: string; + subtitle: string; +} + +export class TextFormatter { + constructor(); + /** + * Formats a song into a plain text chord sheet + * @param song The song to be formatted + */ + format(song: Song): string; + formatHeader(header: SongHeader): string; + formatParagraphs(song: Song): string; + formatParagraph(paragraph: Paragraph): string; + formatLine(line: Line): string; + formatTitle(title: string): string; + formatSubtitle(subtitle: string): string; + formatTopLine(line: Line): string | null; + chordLyricsPairLength(chordLyricsPair: ChordLyricsPair): number; + formatItemTop(item: Tag | ChordLyricsPair | Line): string; + formatLineBottom(line: Line): string; + formatLineWithFormatter( + line: Line, + formatter: (x: string) => string + ): string; + formatItemBottom(item: Tag | ChordLyricsPair | Line): string; +} + +/** + * Formats a song into HTML. It uses TABLEs to align lyrics with chords, which makes the HTML for things like + * PDF conversion. + */ +export class HtmlTableFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into HTML. It uses DIVs to align lyrics with chords, which makes it useful for responsive web pages. + */ +export class HtmlDivFormatter { + constructor(); + /** + * Formats a song into HTML. + * @param song The song to be formatted + */ + format(song: Song): string; +} + +/** + * Formats a song into a ChordPro chord sheet + */ +export class ChordProFormatter { + constructor(); + /** + * Formats a song into a ChordPro chord sheet. + * @param song The song to be formatted + */ + format(song: Song): string; + + formatLine(line: Line): string; + formatItem(item: Tag | ChordLyricsPair | Line): string; + formatTag(tag: Tag): string; + formatChordLyricsPair(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairChords(chordLyricsPair: ChordLyricsPair): string; + formatChordLyricsPairLyrics(chordLyricsPair: ChordLyricsPair): string; +} diff --git a/types/chordsheetjs/tsconfig.json b/types/chordsheetjs/tsconfig.json new file mode 100644 index 0000000000..0b2e8140ca --- /dev/null +++ b/types/chordsheetjs/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", "chordsheetjs-tests.ts"] +} diff --git a/types/chordsheetjs/tslint.json b/types/chordsheetjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/chordsheetjs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/chrome-apps/index.d.ts b/types/chrome-apps/index.d.ts index 33b760ce82..8873e80da2 100644 --- a/types/chrome-apps/index.d.ts +++ b/types/chrome-apps/index.d.ts @@ -612,7 +612,10 @@ declare namespace chrome { * @deprecated Deprecated since Chrome 36. Use innerBounds or outerBounds. */ maxHeight?: integer; - /** Type of window to create */ + /** + * @deprecated Deprecated since Chrome 69. All app windows use the 'shell' window type. + * @description Type of window to create + **/ type?: 'shell'; /** * If true, the window will have its own shelf icon. @@ -919,7 +922,8 @@ declare namespace chrome { level?: integer; } /** - * Device properties by which to filter the list of returned audio devices. If the filter is not set or set to {}, returned device list will contain all available audio devices. + * Device properties by which to filter the list of returned audio devices. + * If the filter is not set or set to {}, returned device list will contain all available audio devices. */ interface Filter { /** @@ -1083,8 +1087,9 @@ declare namespace chrome { function getDevices(callback: (devices: Device[]) => void): void; /** - * Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. - * @param filter Since Chrome 67. Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. + * @since Chrome 67. + * @description Get a list of Bluetooth devices known to the system, including paired and recently discovered devices. + * @param filter Some criteria to filter the list of returned bluetooth devices. If the filter is not set or set to {}, returned device list will contain all bluetooth devices. Right now this is only supported in ChromeOS, for other platforms, a full list is returned. * @param callback Called when the search is completed. */ function getDevices(filter: DeviceFilter, callback: (devices: Device[]) => void): void; @@ -2082,12 +2087,12 @@ declare namespace chrome { /** * **Dev channel only.** * Sets image data to clipboard - * @param imageData The encoded image data. *Since Chrome 70. Warning: this is the current Beta channel.* - * @param type The type of image being passed. *Since Chrome 70. Warning: this is the current Beta channel.* + * @param imageData The encoded image data. *Since Chrome 71. Warning: this is the current Dev channel.* + * @param type The type of image being passed. *Since Chrome 71. Warning: this is the current Dev channel.* * @param [additionalItems] Additional data items for describing image data. * The callback is called with chrome.runtime.lastError set to error code if there is an error. * Requires clipboard and clipboardWrite permissions. - * *Since Chrome 70. Warning: this is the current Beta channel.* + * *Since Chrome 71. Warning: this is the current Dev channel.* * @param [callback] */ function setImageData(imageData: ArrayBuffer, type: ImageType, additionalItems?: AdditionalItems, callback?: () => void): void; @@ -3078,7 +3083,8 @@ declare namespace chrome { 'document_end' | 'document_idle'; /** - * The origin of injected CSS. + * @since Chrome 66. + * @description The origin of injected CSS. **/ type CSSOrigin = 'author' | @@ -3363,7 +3369,7 @@ declare namespace chrome { function chooseEntry(options: ChooseEntryOptionsBase, callback: FileEntryCallback): void; function chooseEntry(options: ChooseFileEntryOptions, callback: FileEntryCallback): void; function chooseEntry(options: ChooseSaveFileEntryOptions, callback: FileEntryCallback): void; - function chooseEntry(options: ChooseMultipleFilesEntryOptions, callback: FileEntryCallback): void; + function chooseEntry(options: ChooseMultipleFilesEntryOptions, callback: FileEntryCallback): void; function chooseEntry(options: ChooseDirectoryEntryOptions, callback: FileEntryCallback): void; /** Returns the file entry with the given id if it can be restored. This call will fail with a runtime error otherwise. */ function restoreEntry(id: string, callback: (entry: FileEntry) => void): void; @@ -5968,6 +5974,11 @@ declare namespace chrome { SSID?: S; /** The network signal strength. */ SignalStrength?: integer; + /** + * @since Chrome 70 + * @description The tethering state associated with the connection. + */ + TetheringState?: string; } interface WiFiProperties void>; /** - * The user clicked on a link for the app's notification settings. - * @since Chrome 32. + * @deprecated Deprecated since Chrome 65. Custom notification settings button is no longer supported. + * @description The user clicked on a link for the app's notification settings. + * As of Chrome 47, only ChromeOS has UI that dispatches this event. + * As of Chrome 65, that UI has been removed from ChromeOS, too. */ const onShowSettings: chrome.events.Event<() => void>; @@ -9319,7 +9339,10 @@ declare namespace chrome { /** The display mode height in native pixels. */ heightInNativePixels: integer; - /** The display mode UI scale factor. */ + /** + * @deprecated Deprecated since Chrome 70. Use `displayZoomFactor` + * @description The display mode UI scale factor. + **/ uiScale: integer; /** The display mode device scale factor. */ @@ -9380,15 +9403,16 @@ declare namespace chrome { * If set to true, changes the display mode to unified desktop. * If set to false, unified desktop mode will be disabled. * This is only valid for the primary display. - * If provided, mirroringSourceId must not be provided and other properties may not apply. This is has no effect if not provided. - * @see(See enableUnifiedDesktop for details). + * If provided, mirroringSourceId must not be provided and other properties may not apply. + * This is has no effect if not provided. + * @see(See `enableUnifiedDesktop` for details). * @since Chrome 59 * */ isUnified?: boolean; /** * @requires(CrOS) Chrome OS only. - * @deprecated Deprecated since Chrome 68. Use *setMirrorMode* + * @deprecated Deprecated since Chrome 68. Use ´setMirrorMode´ * @see setMirrorMode * @description * If set and not empty, enables mirroring for this display. @@ -9416,7 +9440,7 @@ declare namespace chrome { * If set, updates the display's rotation. * Legal values are [0, 90, 180, 270]. * The rotation is set clockwise, relative to the display's vertical position. - * It's applied after overscan paramter. + * It's applied after overscan parameter. */ rotation?: 0 | 90 | 180 | 270; @@ -9912,10 +9936,10 @@ declare namespace chrome { /** The language that this voice supports, in the form language-region. Examples: 'en', 'en-US', 'en-GB', 'zh-CN'. */ lang?: string; /** - * This voice's gender. - * One of: 'male', or 'female' + * @deprecated Deprecated since Chrome 70. Gender is deprecated and will be ignored. + * @description This voice's gender. */ - gender?: string; + gender?: 'male' | 'female'; /** The name of the voice. */ voiceName?: string; /** The ID of the extension providing this voice. */ @@ -9959,10 +9983,10 @@ declare namespace chrome { /** The extension ID of the speech engine to use, if known. */ extensionId?: string; /** - * Gender of voice for synthesized speech. - * One of: 'male', or 'female' + * @deprecated Deprecated since Chrome 70. Gender is deprecated and will be ignored. + * @description Gender of voice for synthesized speech. */ - gender?: string; + gender?: 'male' | 'female'; /** The TTS event types the voice must support. */ requiredEventTypes?: string[]; /** The TTS event types that you are interested in listening to. If missing, all event types may be sent. */ @@ -10983,7 +11007,7 @@ declare namespace chrome { */ class RequestMatcher { protected readonly typeGuard: 'RequestMatcher'; - constructor (parameters?: RequestMatcherFields); + constructor(parameters?: RequestMatcherFields); public readonly instanceType: string; } @@ -11001,7 +11025,7 @@ declare namespace chrome { /** Declarative event action that redirects a network request. */ class RedirectRequest { protected readonly typeGuard: 'RedirectRequest'; - constructor (parameters: RedirectRequestParams); + constructor(parameters: RedirectRequestParams); public readonly instanceType: string; } @@ -11036,7 +11060,7 @@ declare namespace chrome { */ class RedirectByRegEx { protected readonly typeGuard: 'RedirectByRegEx'; - constructor (parameters: RedirectByRegExParams); + constructor(parameters: RedirectByRegExParams); public readonly instanceType: string; } @@ -11055,7 +11079,7 @@ declare namespace chrome { */ class SetRequestHeader { protected readonly typeGuard: 'SetRequestHeader'; - constructor (parameters: SetRequestHeaderParams); + constructor(parameters: SetRequestHeaderParams); public readonly instanceType: string; } @@ -11072,7 +11096,7 @@ declare namespace chrome { */ class RemoveRequestHeader { protected readonly typeGuard: 'RemoveRequestHeader'; - constructor (parameters: RemoveRequestHeaderParams); + constructor(parameters: RemoveRequestHeaderParams); public readonly instanceType: string; } @@ -11091,7 +11115,7 @@ declare namespace chrome { */ class AddResponseHeader { protected readonly typeGuard: 'AddResponseHeader'; - constructor (parameters: AddResponseHeaderParams); + constructor(parameters: AddResponseHeaderParams); public readonly instanceType: string; } @@ -11107,7 +11131,7 @@ declare namespace chrome { */ class RemoveResponseHeader { protected readonly typeGuard: 'RemoveResponseHeader'; - constructor (parameters: RemoveResponseHeaderParams); + constructor(parameters: RemoveResponseHeaderParams); public readonly instanceType: string; } @@ -11133,7 +11157,7 @@ declare namespace chrome { */ class IgnoreRules { protected readonly typeGuard: 'IgnoreRules'; - constructor (parameters: IgnoreRulesParams); + constructor(parameters: IgnoreRulesParams); public readonly instanceType: string; } @@ -11150,7 +11174,7 @@ declare namespace chrome { */ class SendMessageToExtension { protected readonly typeGuard: 'SendMessageToExtension'; - constructor (parameters: SendMessageParams); + constructor(parameters: SendMessageParams); public readonly instanceType: string; } @@ -11248,7 +11272,7 @@ declare namespace chrome { */ class AddRequestCookie { protected readonly typeGuard: 'AddRequestCookie'; - constructor (parameters: AddCookie); + constructor(parameters: AddCookie); public readonly instanceType: string; } @@ -11259,7 +11283,7 @@ declare namespace chrome { */ class AddResponseCookie { protected readonly typeGuard: 'AddResponseCookie'; - constructor (parameters: AddCookie); + constructor(parameters: AddCookie); public readonly instanceType: string; } @@ -11292,7 +11316,7 @@ declare namespace chrome { * @param modification Attributes that shall be overridden in cookies that machted the filter. * Attributes that are set to an empty string are removed. */ - constructor (parameters: EditCookieParams); + constructor(parameters: EditCookieParams); public readonly instanceType: string; } @@ -11306,7 +11330,7 @@ declare namespace chrome { * @param filter Filter for cookies that will be modified.All empty entries are ignored. * @param modification */ - constructor (parameter: EditCookieParams); + constructor(parameter: EditCookieParams); public readonly instanceType: string; } @@ -11316,7 +11340,7 @@ declare namespace chrome { */ class RemoveRequestCookie { protected readonly typeGuard: 'RemoveRequestCookie'; - constructor (parameters: RemoveCookieParams); + constructor(parameters: RemoveCookieParams); public readonly instanceType: string; } @@ -11340,7 +11364,7 @@ declare namespace chrome { */ class RemoveResponseCookie { protected readonly typeGuard: 'RemoveResponseCookie'; - constructor (parameters: RemoveCookieParams); + constructor(parameters: RemoveCookieParams); public readonly instanceType: string; } @@ -11518,7 +11542,7 @@ declare namespace chrome { */ declare class HTMLAppViewElement extends HTMLElement { /** Create a new AppView tag */ - constructor (); + constructor(); /** * Requests another app to be embedded. * @param app The extension id of the app to be embedded. @@ -11626,7 +11650,7 @@ declare class HTMLWebViewElement extends HTMLElement { src: string; /** Create a new element */ - constructor (); + constructor(); /** * Queries audio state. @@ -11908,6 +11932,21 @@ declare class HTMLWebViewElement extends HTMLElement { */ loadDataWithBaseUrl(dataUrl: string, baseUrl: string, virtualUrl?: string): void; + /** + * @since Chrome 71 + * @description Sets spatial navigation state of the webview. + * @param enabled Spatial navigation state value. + */ + setSpatialNavigationEnabled(enabled: boolean): void; + + /** + * @since Chrome 71 + * @description Queries whether spatial navigation is enabled for the webview. + * @param callback Callback that will provide the value of the spatial navigation state. + */ + isSpatialNavigationEnabled(callback: (enabled: boolean) => void): void; + + /** * Forcibly kills the guest web page's renderer process. * This may affect multiple webview tags in the current app if they share the same process, diff --git a/types/chrome-apps/test/index.ts b/types/chrome-apps/test/index.ts index 93864d107b..499a34bab1 100644 --- a/types/chrome-apps/test/index.ts +++ b/types/chrome-apps/test/index.ts @@ -1114,6 +1114,7 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { if (networkObj.WiFi) { // WiFi active :) console.log('Wifi BSID: ' + networkObj.WiFi.BSSID); + const state = networkObj.WiFi.TetheringState; } chrome.networking.onc.setProperties(networkObj.GUID || '', { WiFi: { @@ -1124,6 +1125,19 @@ chrome.networking.onc.getNetworks({ 'networkType': 'All' }, (networkList) => { chrome.networking.onc.getProperties(networkObj.GUID || '', (props) => { const WiFiResult = props.WiFi; }); + chrome.networking.onc.getState(networkObj.GUID || '', (state) => { + const wifiState = state.WiFi || {}; + return wifiState.TetheringState; + }); + chrome.networking.onc.getManagedProperties(networkObj.GUID || '', (result) => { + const wifiResult = result.WiFi; + if (wifiResult !== undefined) { + const managed = wifiResult.HexSSID; + if (managed !== undefined) { + return managed.UserPolicy; + } + } + }); } }); diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index 49f079e159..ba074550f8 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -4525,12 +4525,12 @@ declare namespace chrome.pageAction { * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. */ - export function hide(tabId: number): void; + export function hide(tabId: number, callback?: () => void): void; /** * Shows the page action. The page action is shown whenever the tab is selected. * @param tabId The id of the tab for which you want to modify the page action. */ - export function show(tabId: number): void; + export function show(tabId: number, callback?: () => void): void; /** Sets the title of the page action. This is displayed in a tooltip over the page action. */ export function setTitle(details: TitleDetails): void; /** Sets the html document to be opened as a popup when the user clicks on the page action's icon. */ diff --git a/types/chrome/tslint.json b/types/chrome/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/chrome/tslint.json +++ b/types/chrome/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, 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 a6f9c9cf5c..6a0b50a4d8 100644 --- a/types/ckeditor/ckeditor-tests.ts +++ b/types/ckeditor/ckeditor-tests.ts @@ -914,6 +914,9 @@ function test_skin() { CKEDITOR.skin.loadPart('part', () => console.log('load')); var path2: string = CKEDITOR.skin.path(); + + CKEDITOR.skin.ua_dialog = 'ie,iequirks,ie8,gecko'; + CKEDITOR.skin.ua_editor = 'ie,gecko'; } function test_style() { diff --git a/types/ckeditor/index.d.ts b/types/ckeditor/index.d.ts index 6815d3aa98..69c23d6a99 100644 --- a/types/ckeditor/index.d.ts +++ b/types/ckeditor/index.d.ts @@ -2,6 +2,7 @@ // Project: https://ckeditor.com/ckeditor-4/ // Definitions by: Thomas Wittwer // Stuart Long +// Viktor Pegy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // WORK-IN-PROGRESS: Any contribution support welcomed. @@ -2168,6 +2169,8 @@ declare namespace CKEDITOR { // tslint:disable-next-line:no-duplicate-variable var name: string; var ua: { [name: string]: any }; + var ua_dialog: string; + var ua_editor: string; function addIcon(name: string, path: string, offset?: number, bgsize?: string): void; function chameleon(editor: string, part: string): void; diff --git a/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts new file mode 100644 index 0000000000..82c272a6ec --- /dev/null +++ b/types/ckeditor__ckeditor5-utils/ckeditor__ckeditor5-utils-tests.ts @@ -0,0 +1,594 @@ +import * as utils from "ckeditor__ckeditor5-utils"; + +declare const document: Document; +declare const locale: utils.Locale; +declare let bool: boolean; +declare let changes: utils.Change[]; +declare let emitter: utils.Emitter; +declare let htmlElement: HTMLElement; +declare let map: Map; +declare let num: number; +declare let rect: utils.Rect; +declare let rectOrNull: utils.Rect | null; +declare let str: string; + +// utils/dom + +utils.createElement(document, "p"); +utils.createElement(document, "p", {class: "foo"}); +utils.createElement(document, "p", null, "foo"); +utils.createElement(document, "p", null, ["foo", utils.createElement(document, "img")]); + +// TODO? utils/dom/emittermixin + +utils.getAncestors(htmlElement); + +utils.getBorderWidths(htmlElement); + +utils.getCommonAncestor(htmlElement, htmlElement); + +str = utils.getDataFromElement(htmlElement); + +let strNull: HTMLElement | null = utils.getPositionedAncestor(); +strNull = utils.getPositionedAncestor(htmlElement); + +num = utils.indexOf(htmlElement); + +utils.insertAt(htmlElement, 2, htmlElement); + +bool = utils.isNode(htmlElement); +bool = utils.isNode(new Date()); + +bool = utils.isRange(new Range()); +bool = utils.isRange(new Date()); + +bool = utils.isText(new Text("foo")); +bool = utils.isText(new Date()); + +bool = utils.isWindow(window); +bool = utils.isWindow(new Date()); + +let position: utils.Position; + +position = utils.getOptimalPosition({ + element: htmlElement, + target: () => htmlElement, + positions: [(targetRect, elementRect) => ({ + top: targetRect.top, + left: targetRect.left + elementRect.width, + name: "right" + })] +}); + +position = utils.getOptimalPosition({ + element: htmlElement, + target: htmlElement, + positions: [ + (targetRect) => ({ + top: targetRect.bottom, + left: targetRect.left, + name: "mySouthEastPosition" + }), + (targetRect, elementRect) => ({ + top: targetRect.top - elementRect.height, + left: targetRect.left, + name: "myNorthEastPosition" + }) + ], + limiter: document.body, + fitInViewport: true, +}); + +rect = new utils.Rect(document.body); +rect = new utils.Rect(document.getSelection()!.getRangeAt(0)); +rect = new utils.Rect(window); +rect = new utils.Rect({top: 0, right: 10, bottom: 10, left: 0, width: 10, height: 10}); +rect = new utils.Rect(rect); +rect = new utils.Rect(document.body.getClientRects().item(0)!); + +rect = rect.clone(); +bool = rect.contains(rect); +rect = rect.excludeScrollbarsAndBorders(); +num = rect.getArea(); +rect = rect.getIntersection(rect); +num = rect.getIntersectionArea(rect); +rectOrNull = rect.getVisible(); +bool = rect.isEqual(rect); +rect = rect.moveBy(1, 1); +rect = rect.moveTo(1, 1); + +utils.remove(htmlElement); + +utils.scrollAncestorsToShowTarget(new Range()); +utils.scrollAncestorsToShowTarget(htmlElement); + +utils.scrollViewportToShowTarget({target: new Range()}); +utils.scrollViewportToShowTarget({target: htmlElement}); +utils.scrollViewportToShowTarget({target: new Range(), viewportOffset: 30}); +utils.scrollViewportToShowTarget({target: htmlElement, viewportOffset: 30}); + +utils.setDataInElement(htmlElement, "foo"); + +str = utils.toUnit("rem")(10); + +// utils/ckeditorerror ======================================================== + +const regularError = new Error("foo"); +let ckeditorError: utils.CKEditorError; + +const data = {bar: 1}; +ckeditorError = new utils.CKEditorError("foo"); +ckeditorError = new utils.CKEditorError("foo", data); + +utils.CKEditorError.isCKEditorError(ckeditorError); +utils.CKEditorError.isCKEditorError(regularError); + +// utils/collection =========================================================== + +interface Foo { + foo: number; +} + +interface Props { + id: string; +} + +interface PropsStr { + id: string; + name: string; +} + +declare let foo: Foo; +let items: PropsStr[]; +let itemOrNull: Props | null; +let itemOrUndef: Props | undefined; + +const item1 = {id: "id1"}; +const item2 = {id: "id2"}; +const itemStr1 = {id: "foo", name: "yy"}; +const itemStr2 = {id: "foo", name: "xx"}; + +const coll = new utils.Collection(); +const collStr = new utils.Collection({idProperty: "name"}); + +coll.add(item1); +coll.add(item2); +collStr.add(itemStr1); +collStr.add(itemStr2); + +coll.add(item1, 0); +coll.add(item1).add(item2); + +coll.clear(); + +items = collStr.filter((item) => item.name === "yy"); +items = collStr.filter((_, idx) => idx > 0); +items = collStr.filter(function(this: Foo, _, idx) {return this.foo > 0 && idx === 0; }, foo); + +itemOrUndef = collStr.find((item) => item.name === "yy"); +itemOrUndef = collStr.find((_, idx) => idx === 3); +itemOrUndef = collStr.find(function(this: Foo, _, idx) {return this.foo > 0 && idx === 0; }, foo); + +itemOrNull = coll.get(0); +itemOrNull = coll.get("id1"); + +num = coll.getIndex("id1"); +num = coll.getIndex(item1); + +coll.remove(0); +coll.remove("id1"); +coll.remove(item1); + +const strings: string[] = collStr.map((item) => item.name); +const nums: number[] = collStr.map((_, idx) => idx); +const bools: boolean[] = collStr.map(function(this: Foo, _, idx) {return this.foo === idx; }, foo); + +// collection#bindTo + +interface LabelObj { + label: string; +} + +interface LabelValueObj { + label: {value: string}; +} + +interface HiddenObj { + hidden: boolean; +} + +class FactoryClass { + factoryLabel: string; + constructor(data: LabelObj) { + this.factoryLabel = data.label; + } +} + +const source1 = new utils.Collection({idProperty: "label"}); +const target1 = new utils.Collection(); + +target1.bindTo(source1).as(FactoryClass); + +source1.add({label: "foo"}); +source1.add({label: "bar"}); + +source1.remove(0); +console.log(target1.length); +console.log(target1.get(0)!.factoryLabel); + +class FooClass { + fooLabel: string; + constructor(data: LabelObj) { + this.fooLabel = data.label; + } +} + +class BarClass { + barLabel: string; + constructor(data: LabelObj) { + this.barLabel = data.label; + } +} + +const source2 = new utils.Collection({idProperty: "label"}); +const target2 = new utils.Collection(); + +target2.bindTo(source2).using((item) => { + if (item.label === "foo") { + return new FooClass(item); + } else { + return new BarClass(item); + } +}); + +source2.add({label: "foo"}); +source2.add({label: "bar"}); + +console.log(target2.length); +console.log(target2.get(0)! instanceof FooClass); +console.log(target2.get(1)! instanceof BarClass); + +const source3 = new utils.Collection({idProperty: "label"}); +const target3 = new utils.Collection(); + +target3.bindTo(source2).using("label"); + +source3.add({label: {value: "foo"}}); +source3.add({label: {value: "bar"}}); + +console.log(target3.length); +console.log(target3.get(0)!.value); +console.log(target3.get(1)!.value); + +const source4 = new utils.Collection(); +const target4 = new utils.Collection(); + +target4.bindTo(source4).using(item => { + if (item.hidden) { + return null; + } + + return item; +}); + +source4.add({hidden: true}); +source4.add({hidden: false}); + +// utils/comparearrays ======================================================== + +utils.compareArrays([0, 2], [0, 2, 1]); +utils.compareArrays(["abc", 0 ], ["abc", 0, 3]); + +// utils/config =============================================================== + +let strOrUndef: string | undefined; +let config: utils.Config; +const defaultConfig = { + foo: 1, bar: 2, +}; + +config = new utils.Config(); +config = new utils.Config({foo: 10}); +config = new utils.Config({}, defaultConfig); +config = new utils.Config({foo: 10}, defaultConfig); + +config.define({ + resize: { + minHeight: 400, + hidden: true + } +}); + +config.define("resize", {minHeight: 400, hidden: true}); +config.define("language", "en"); +config.define("resize.minHeight", 400); + +str = config.get("language"); +num = config.get("resize.minHeight"); + +config.define("language", undefined); +strOrUndef = config.get("language"); + +// utils/count ================================================================ + +num = utils.count([1, 2, 3, 4, 5]); + +// utils/diff ================================================================= + +changes = utils.diff("aba", "acca"); +changes = utils.diff(Array.from("aba"), Array.from("acca")); + +// utils/difftochanges ======================================================== + +const input = Array.from("abc"); +const output = Array.from("xaby"); +const allChanges = utils.diffToChanges(utils.diff(input, output), output); +allChanges.forEach(change => { + if (change.type === "insert") { + input.splice(change.index, 0, ...change.values); + } else if (change.type === "delete") { + input.splice(change.index, change.howMany); + } +}); + +// utils/elementreplacer ====================================================== + +const replacer = new utils.ElementReplacer(); + +replacer.replace(htmlElement, htmlElement); +replacer.replace(htmlElement); + +replacer.restore(); + +// utils/emittermixin + +emitter = utils.EmitterMixin; +emitter = Object.create(utils.EmitterMixin); + +emitter.delegate("foo") ; +emitter.delegate("foo", "bar"); +emitter.delegate("foo").to(emitter); +emitter.delegate("foo").to(emitter, "bar"); +emitter.delegate("foo").to(emitter, name => name + "-delegated"); + +emitter.fire("foo"); +emitter.fire("foo", 1, "b", true); +emitter.fire("getSelectedContent", (evt: utils.EventInfo) => { + evt.return = new DocumentFragment(); + evt.stop(); +}); + +emitter.listenTo(emitter, "foo", () => {}); +emitter.listenTo(emitter, "foo", () => {}, {priority: 10}); +emitter.listenTo(emitter, "foo", () => {}, {priority: "highest"}); + +emitter.off("foo"); +emitter.off("foo", () => {}); + +emitter.on("foo", () => {}); +emitter.on("foo", () => {}, {priority: 10}); +emitter.on("foo", () => {}, {priority: "normal"}); + +emitter.once("foo", () => {}); +emitter.once("foo", () => {}, {priority: 10}); +emitter.once("foo", () => {}, {priority: "lowest"}); + +emitter.stopDelegating(); +emitter.stopDelegating("foo"); +emitter.stopDelegating("foo", emitter); + +emitter.stopListening(); +emitter.stopListening(emitter); +emitter.stopListening(emitter, "foo"); +emitter.stopListening(emitter, "foo", () => {}); + +// utils/env ================================================================== + +bool = utils.env.isEdge; +bool = utils.env.isMac; + +// utils/eventinfo ============================================================ + +const event = new utils.EventInfo({a: 1}, "test"); +num = event.source.a; +str = event.name; + +event.path[0]; + +event.stop(); +event.off(); + +bool = event.stop.called; +bool = event.off.called; + +// utils/fastdiff ============================================================= + +utils.fastDiff(str, "2ab").forEach(change => { + if (change.type === "insert") { + str = str.substring(0, change.index) + change.values.join("") + str.substring(change.index); + } else if (change.type === "delete") { + str = str.substring(0, change.index) + str.substring(change.index + change.howMany); + } +}); + +// utils/first ================================================================ + +const collection = [ 11, 22 ]; +const iterator = collection[Symbol.iterator](); + +utils.first(iterator); + +// utils/focustracker ========================================================= + +const focusTracker = new utils.FocusTracker(); +htmlElement = focusTracker.focusedElement; +bool = focusTracker.isFocused; +focusTracker.add(htmlElement); +focusTracker.remove(htmlElement); + +// utils/isiterable =========================================================== + +bool = utils.isIterable(str); +bool = utils.isIterable([1, 2, 3]); + +// utils/keyboard ============================================================= + +num = utils.keyCodes.a; +num = utils.keyCodes["a"]; + +num = utils.getCode("0"); +num = utils.getCode({keyCode: 48}) ; +num = utils.getCode({keyCode: 48, altKey: true, ctrlKey: true, shiftKey: true}); + +str = utils.getEnvKeystrokeText("alt+A"); + +num = utils.parseKeystroke("Ctrl+A"); +num = utils.parseKeystroke(["ctrl", "a"]); +num = utils.parseKeystroke(["shift", 33]); + +// utils/keystrokehandler ===================================================== + +declare const keystroke: utils.KeystrokeInfo; +const keystrokes = new utils.KeystrokeHandler(); + +const spy = utils.spy(); +keystrokes.set("Ctrl+A", spy); +keystrokes.set(["Ctrl", "A"], spy); +keystrokes.set(["Ctrl", "A"], spy, {priority: "high"}); +keystrokes.set(["Ctrl", 33], spy, {priority: 10}); + +const emitterMixxin = Object.create(utils.EmitterMixin) as utils.Emitter; +keystrokes.listenTo(emitterMixxin); + +bool = keystrokes.press(keystroke); + +keystrokes.destroy(); + +// utils/locale =============================================================== + +locale.t("Label"); +locale.t('Created file "%0" in %1ms.', ["fileName", "100"]); + +// utils/log ================================================================== + +utils.log.warn("message"); +utils.log.warn('plugin-load: It was not possible to load the "{$pluginName}" plugin in module "{$moduleName}', { + pluginName: "foo", + moduleName: "bar" +}); + +utils.log.error("message"); +utils.log.error('plugin-load: It was not possible to load the "{$pluginName}" plugin in module "{$moduleName}', { + pluginName: "foo", + moduleName: "bar" +}); + +// utils/mapsequal ============================================================ + +utils.mapsEqual(map, map); + +// utils/mix ================================================================== + +class Editor { + b: () => number; +} + +interface SomeMixin { + a: () => string; +} + +const SomeMixin = { + a() { + return "a"; + } +}; + +utils.mix(Editor, SomeMixin); +const mixEditor = new Editor() as Editor & SomeMixin; +mixEditor.a(); +mixEditor.b(); + +// utils/nth ================================================================== + +function* getGenerator() { + yield 11; + yield 22; + yield 33; +} + +utils.nth(2, getGenerator()); + +// utils/objecttomap ========================================================== + +const objMap: Map = utils.objectToMap({foo: 1, bar: 2}); +num = objMap.get("foo")!; + +// utils/observablemixin ====================================================== + +const observable: utils.Observable = utils.ObservableMixin; + +const vehicle = Object.create(utils.ObservableMixin) as utils.Observable; +const car = Object.create(utils.ObservableMixin) as utils.Observable; + +vehicle.bind("color"); +vehicle.bind("color", "year"); +vehicle.bind("color", "year").to(car); +vehicle.bind("color", "year").to(car, "color"); +vehicle.bind("color", "year").to(car, "color", car, "year"); +vehicle.bind("year").to(car, "color", car, "year", (a: string, b: number) => a + b); +vehicle.bind("custom").to(car, "color", car, "year", car, "hue", (...args: Array) => args.join("/")); // TS 3.0: [string, number, string] +vehicle.bind("color").toMany([car, car], "color", () => {}); + +vehicle.decorate("method"); + +car.set("color", "red"); +car.set("seats", undefined); +car.set({ + color: "blue", + wheels: 4, + seats: 5, +}); + +vehicle.unbind(); +vehicle.unbind("color"); +vehicle.unbind("color", "year"); + +// utils/priorities =========================================================== + +num = utils.priorities.get(2); +num = utils.priorities.get("normal"); + +// utils/spy + +const fn1 = utils.spy(); +fn1(); +bool = fn1.called; + +// utils/tomap + +map = utils.toMap({foo: 1, bar: 2}); +map = utils.toMap([["foo", 1], ["bar", 2]]); +map = utils.toMap(map); + +// utils/translation-service ================================================== + +utils.add("pl", { + OK: "OK", + "Cancel [context: reject]": "Anuluj" +}); + +utils.translate("pl", "Cancel [context: reject]"); + +// utils/uid ================================================================== + +str = utils.uid(); + +// utils/unicode ============================================================== + +bool = utils.isCombiningMark("a"); +bool = utils.isHighSurrogateHalf("a"); +bool = utils.isInsideCombinedSymbol(str, 2); +bool = utils.isInsideSurrogatePair(str, 2); +bool = utils.isLowSurrogateHalf(String.fromCharCode(57166)); + +// utils/version ============================================================== diff --git a/types/ckeditor__ckeditor5-utils/index.d.ts b/types/ckeditor__ckeditor5-utils/index.d.ts new file mode 100644 index 0000000000..8d9d50e889 --- /dev/null +++ b/types/ckeditor__ckeditor5-utils/index.d.ts @@ -0,0 +1,471 @@ +// Type definitions for @ckeditor/ckeditor5-utils 10.2 +// Project: https://github.com/ckeditor/ckeditor5-utils +// Definitions by: denisname +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +// Helpers + +export interface DeleteChange { + index: number; + type: "delete"; + howMany: number; +} + +export interface InsertChange { + index: number; + type: "insert"; + values: string[]; +} + +export interface BindChain { + to(observable: Observable, ...bindProperties: Array): void; + toMany(observable: Observable[], ...bindProperties: Array): void; +} + +export interface CollectionBindTo { + as: (Class: {new(item: T): K}) => void; + using: (callbackOrProperty: keyof T | ((item: T) => K)) => void; +} + +// utils/dom + +export function createElement(doc: Document, name: string, attributes?: object | null, children?: Node | string | Array): Element; + +// TODO? utils/dom/emittermixin + +export function getAncestors(node: Node): Array; + +export function getBorderWidths(element: HTMLElement): {top: number, right: number, bottom: number, left: number}; + +export function getCommonAncestor(nodeA: Node, nodeB: Node): Node | DocumentFragment | Document | null; + +export function getDataFromElement(el: HTMLElement): string; + +export function getPositionedAncestor(element?: HTMLElement): HTMLElement | null; + +export function indexOf(node: Node): number; + +export function insertAt(parentElement: Element, index: number, nodeToInsert: Node): void; + +export function isNode(obj: any): obj is Node; + +export function isRange(obj: any): obj is Range; + +export function isText(obj: any): obj is Text; + +export function isWindow(obj: any): obj is Window; + +export interface Options { + element: HTMLElement; + fitInViewport?: boolean; + limiter?: HTMLElement | Range | ClientRect | Rect | (() => HTMLElement | Range | ClientRect | Rect); + positions: Array<(targetRect: Rect, elementRect: Rect) => Position>; + target: HTMLElement | Range | ClientRect | Rect | (() => HTMLElement | Range | ClientRect | Rect); +} + +export interface Position { + left: number; + name: string; + top: number; +} + +export function getOptimalPosition(options: Options): Position; + +export class Rect { + readonly bottom: number; + readonly height: number; + readonly left: number; + readonly right: number; + readonly top: number; + readonly width: number; + + constructor(source: HTMLElement | Range | Window | ClientRect | Rect | object); + clone(): Rect; + contains(anotherRect: Rect): boolean; + excludeScrollbarsAndBorders(): Rect; + getArea(): number; + getIntersection(anotherRect: Rect): Rect; + getIntersectionArea(anotherRect: Rect): number; + getVisible(): Rect | null; + isEqual(rect: Rect): boolean; + moveBy(x: number, y: number): Rect; + moveTo(x: number, y: number): Rect; + + static getDomRangeRects(range: Range): Rect[]; +} + +export function remove(node: Node): void; + +export function scrollAncestorsToShowTarget(target: HTMLElement | Range): void; + +export function scrollViewportToShowTarget(options: {target: HTMLElement | Range, viewportOffset?: number}): void; + +export function setDataInElement(el: HTMLElement, data: string): void; + +export function toUnit(unit: string): (value: number) => string; + +// utils/ckeditorerror + +export const DOCUMENTATION_URL: string; + +export class CKEditorError extends Error { + data: object | undefined; + name: string; + + constructor(message: string, data?: object); + + static isCKEditorError(error: Error): boolean; +} + +export function attachLinkToDocumentation(message: string): string; + +// utils/collection + +export function as(Class: Function): void; +export function using(callbackOrProperty: Function | string): void; + +export class Collection implements Iterable, Emitter { + first: T | null; + last: T | null; + length: number; + + constructor(options?: {idProperty?: keyof T}); + add(item: T, index?: number): this; + bindTo(externalCollection: Collection): CollectionBindTo; + clear(): void; + filter(callbackfn: (item: T, index: number) => boolean, thisArg?: any): T[]; + find(predicate: (item: T, index: number) => boolean, thisArg?: any): T | undefined; + get(idOrIndex: string | number): T | null; + getIndex(idOrItem: string | T): number; + map(callbackfn: (item: T, index: number) => U, thisArg?: any): U[]; + remove(subject: T | number | string): T; + + // Iterable + [Symbol.iterator](): Iterator; + + // Emitter + delegate(...events: string[]): EmitterMixinDelegateChain; + fire(eventOrInfo: string | EventInfo, ...args: any[]): any; + listenTo(emitter: Emitter, event: string, callback: Function, options?: {priority?: PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + stopDelegating(event?: string, emitter?: Emitter): void; + stopListening(emitter?: Emitter, event?: string, callback?: Function): void; +} + +// utils/comparearrays + +export type ArrayRelation = "extension" | "same" | "prefix"; + +export function compareArrays(a: ReadonlyArray, b: ReadonlyArray): number | ArrayRelation; + +// utils/config + +export class Config { + constructor(configurations?: object, defaultConfigurations?: object); + define(name: object): void; + define(name: string, value: any): void; + get(name: string): any /*| undefined*/; + set(name: string, value: any /*| undefined*/): void; +} + +// utils/count + +export function count(iterator: Iterable): number; + +// utils/diff + +export type Change = "equal" | "insert" | "delete"; + +export function diff(a: string, b: string, cmp?: (a: string, b: string) => boolean): Change[]; +export function diff(a: ReadonlyArray, b: ReadonlyArray, cmp?: (a: string, b: string) => boolean): Change[]; + +// utils/difftochanges + +export function diffToChanges(diff: Change[], output: string | string[]): Array; + +// utils/elementreplacer + +export class ElementReplacer { + replace(element: HTMLElement, newElement?: HTMLElement): void; + restore(): void; +} + +// utils/emittermixin + +export const EmitterMixin: Emitter; + +export interface Emitter { + delegate(...events: string[]): EmitterMixinDelegateChain; + fire(eventOrInfo: string | EventInfo, ...args: any[]): any; + listenTo(emitter: Emitter, event: string, callback: Function, options?: {priority?: PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + stopDelegating(event?: string, emitter?: Emitter): void; + stopListening(emitter?: Emitter, event?: string, callback?: Function): void; +} + +export interface EmitterMixinDelegateChain { + to(emitter: Emitter, nameOrFunction?: string | ((name: string) => string)): void; +} + +// utils/env + +export namespace env { + const isEdge: boolean; + const isMac: boolean; +} + +// utils/eventinfo + +export class EventInfo { + readonly name: string; + readonly path: object[]; + return: any /*| undefined*/; + readonly source: T; + + constructor(source: T, name: string); + off: { + (): void; + called: boolean; + }; + stop: { + (): void; + called: boolean; + }; +} + +// utils/fastdiff + +export function fastDiff(oldText: string, newText: string): Array; + +// utils/first + +export function first(iterable: Iterable): T; + +// utils/focustracker + +export class FocusTracker implements Observable { + readonly focusedElement: HTMLElement; + readonly isFocused: boolean; + + add(element: HTMLElement): void; + remove(element: HTMLElement): void; + + // Observable + bind(...bindProperties: string[]): BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + + // Observable (Emitter) + delegate(...events: string[]): EmitterMixinDelegateChain; + fire(eventOrInfo: string | EventInfo, ...args: any[]): any; + listenTo(emitter: Emitter, event: string, callback: Function, options?: {priority?: PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + stopDelegating(event?: string, emitter?: Emitter): void; + stopListening(emitter?: Emitter, event?: string, callback?: Function): void; +} + +// utils/isiterable + +export function isIterable(value: any): value is Iterable; + +// utils/keyboard + +export const keyCodes: { + a: 65, + b: 66, + c: 67; + d: 68; + e: 69; + f: 70; + g: 71; + h: 72; + i: 73; + j: 74; + k: 75; + l: 76; + m: 77; + n: 78; + o: 79; + p: 80; + q: 81; + r: 82; + s: 83; + t: 84; + u: 85; + v: 86; + w: 87; + x: 88; + y: 89; + z: 90; + + 0: 48; + 1: 49; + 2: 50; + 3: 51; + 4: 52; + 5: 53; + 6: 54; + 7: 55; + 8: 56; + 9: 57; + + f1: 112; + f2: 113; + f3: 114; + f4: 115; + f5: 116; + f6: 117; + f7: 118; + f8: 118; + f9: 120; + f10: 121; + f11: 122; + f12: 123; + + arrowleft: 37, + arrowup: 38, + arrowright: 39, + arrowdown: 40, + backspace: 8, + "delete": 46, + enter: 13, + space: 32, + esc: 27, + tab: 9, + ctrl: 0x110000, + cmd: 0x110000, + shift: 0x220000, + alt: 0x440000 +}; + +export interface KeystrokeInfo { + altKey?: boolean; + ctrlKey?: boolean; + keyCode: number; + shiftKey?: boolean; +} + +export function getCode(key: string | KeystrokeInfo): number; + +export function getEnvKeystrokeText(keystroke: string): string; + +export function parseKeystroke(keystroke: string | Array): number; + +// utils/keystrokehandler + +export class KeystrokeHandler { + constructor(); + destroy(): void; + listenTo(emitter: Emitter): void; + press(keyEvtData: KeystrokeInfo): boolean; + set(keystroke: string | Array, callback: Function, options?: {priority?: PriorityString | number}): void; +} + +// utils/locale + +export class Locale { + readonly language: string; + + constructor(language?: string); + t(str: string, values?: string[]): string; +} + +// utils/log + +export namespace log { + function error(message: string, data?: object): void; + function warn(message: string, data?: object): void; +} + +// utils/mapsequal + +export function mapsEqual(mapsA: Map, mapsB: Map): boolean; + +// utils/mix + +export function mix(baseClass: {new(): any}, ...mixins: any[]): void; + +// utils/nth + +export function nth(index: number, iterable: Iterable): T; + +// utils/objecttomap + +export function objectToMap(obj: T): Map; + +// utils/observablemixin + +export const ObservableMixin: Observable; + +export interface Observable extends Emitter { + bind(...bindProperties: string[]): BindChain; + decorate(methodName: string): void; + set(name: object): void; + set(name: string, value: any): void; + unbind(...unbindProperties: string[]): void; + + // Emitter + delegate(...events: string[]): EmitterMixinDelegateChain; + fire(eventOrInfo: string | EventInfo, ...args: any[]): any; + listenTo(emitter: Emitter, event: string, callback: Function, options?: {priority?: PriorityString | number }): void; + off(event: string, callback?: Function): void; + on(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + once(event: string, callback: Function, options?: {priority: PriorityString | number}): void; + stopDelegating(event?: string, emitter?: Emitter): void; + stopListening(emitter?: Emitter, event?: string, callback?: Function): void; +} + +// utils/priorities + +export namespace priorities { + function get(priority: PriorityString | number): number; +} + +export type PriorityString = "highest" | "high" | "normal" | "low" | "lowest"; + +// utils/spy + +export function spy(): {(): void; called: boolean}; + +// utils/tomap + +export function toMap(data: Map): Map; +export function toMap(data: ReadonlyArray<[K, V]>): Map; +export function toMap(data: T): Map; + +// utils/translation-service + +export function add(language: string, translations: {[key: string]: string}): void; + +export function translate(language: string, translationKey: string): string; + +// TODO: CKEDITOR_TRANSLATIONS + +// utils/uid + +export function uid(): string; + +// utils/unicode + +export function isCombiningMark(character: string): boolean; + +export function isHighSurrogateHalf(character: string): boolean; + +export function isInsideCombinedSymbol(string: string, offset: number): boolean; + +export function isInsideSurrogatePair(string: string, offset: number): boolean; + +export function isLowSurrogateHalf(character: string): boolean; + +// utils/version + +// TODO: CKEDITOR_VERSION; diff --git a/types/ckeditor__ckeditor5-utils/tsconfig.json b/types/ckeditor__ckeditor5-utils/tsconfig.json new file mode 100644 index 0000000000..1fbda2fd6b --- /dev/null +++ b/types/ckeditor__ckeditor5-utils/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-utils-tests.ts" + ] +} diff --git a/types/ckeditor__ckeditor5-utils/tslint.json b/types/ckeditor__ckeditor5-utils/tslint.json new file mode 100644 index 0000000000..332951717c --- /dev/null +++ b/types/ckeditor__ckeditor5-utils/tslint.json @@ -0,0 +1,20 @@ +{ + "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`?"] + ] + }, + "quotemark": [ + true, + "double", + "avoid-escape", + "avoid-template" + ] + } +} 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/cli-table2/cli-table2-tests.ts b/types/cli-table2/cli-table2-tests.ts index dfaed4ec33..97d8c82dbe 100644 --- a/types/cli-table2/cli-table2-tests.ts +++ b/types/cli-table2/cli-table2-tests.ts @@ -230,3 +230,24 @@ table26.push( // feel free to use colors in your content strings, column widths will be calculated correctly const table27 = new Table({ colWidths: [5], style: { head: [], border: [] } }) as Table.HorizontalTable; table27.push([/*colors.red(*/'hello'/*)*/]); + +// Header as text +const table28 = new Table({ head: ["Top Header 1", "Top Header 2"] }) as Table.HorizontalTable; +table28.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// Header as Cells +const table29 = new Table({ head: [{content: "Top Header 1"}, {content: "Top Header 2"}] }) as Table.HorizontalTable; +table29.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2'] +); + +// ColSpan in header +const table30 = new Table({ head: [{content: "Top Header 1", colSpan: 2}, {content: "Top Header 3"}] }) as Table.HorizontalTable; +table30.push( + ['Value Row 1 Col 1', 'Value Row 1 Col 2', 'Value Row 1 Col 3'], + ['Value Row 2 Col 1', 'Value Row 2 Col 2', 'Value Row 2 Col 3'] +); diff --git a/types/cli-table2/index.d.ts b/types/cli-table2/index.d.ts index b216b23832..865439f000 100644 --- a/types/cli-table2/index.d.ts +++ b/types/cli-table2/index.d.ts @@ -31,7 +31,7 @@ declare namespace CliTable2 { rowHeights: Array; colAligns: HorizontalAlignment[]; rowAligns: VerticalAlignment[]; - head: string[]; + head: Cell[]; wordWrap: boolean; } diff --git a/types/code/code-tests.ts b/types/code/code-tests.ts index 9e5f12645f..f9b55ca72e 100644 --- a/types/code/code-tests.ts +++ b/types/code/code-tests.ts @@ -103,6 +103,7 @@ expect("abcd").to.have.length(4); expect(5).to.equal(5); expect({ a: 1 }).to.equal({ a: 1 }); +expect([1, 2, 3]).to.equal([1, 2, 3]); expect(Object.create(null)).to.equal({}, { prototype: false }); diff --git a/types/code/index.d.ts b/types/code/index.d.ts index 3bdca4be9a..7047fc0702 100644 --- a/types/code/index.d.ts +++ b/types/code/index.d.ts @@ -125,9 +125,9 @@ export interface Values { /** Asserts that the reference value has a length property matching the provided size or an object with the specified number of keys. */ length(size: number): AssertionChain; /** Asserts that the reference value equals the provided value. */ - equal(value: T, options?: any): AssertionChain; + equal(value: T | T[], options?: any): AssertionChain; /** Asserts that the reference value equals the provided value. */ - equals(value: T, options?: any): AssertionChain; + equals(value: T | T[], options?: any): AssertionChain; /** Asserts that the reference value is greater than (>) the provided value. */ above(value: T): AssertionChain; /** Asserts that the reference value is greater than (>) the provided value. */ diff --git a/types/codemirror/codemirror-comment.d.ts b/types/codemirror/codemirror-comment.d.ts new file mode 100644 index 0000000000..706e42e807 --- /dev/null +++ b/types/codemirror/codemirror-comment.d.ts @@ -0,0 +1,43 @@ +// Type definitions for CodeMirror +// Project: https://github.com/marijnh/CodeMirror +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// See docs https://codemirror.net/doc/manual.html#addon_comment + +// Todo: add 'toggleComment' command, once command type definitions exist in main definitions + +import * as CodeMirror from "codemirror"; + +declare module "codemirror" { + + interface Editor { + /** Tries to uncomment the current selection, and if that fails, line-comments it. */ + toggleComment(options?: CommentOptions): void; + /** Set the lines in the given range to be line comments. Will fall back to `blockComment` when no line comment style is defined for the mode. */ + lineComment(from: Position, to: Position, options?: CommentOptions): void; + /** Wrap the code in the given range in a block comment. Will fall back to `lineComment` when no block comment style is defined for the mode. */ + blockComment(from: Position, to: Position, options?: CommentOptions): void; + /** Try to uncomment the given range. Returns `true` if a comment range was found and removed, `false` otherwise. */ + uncomment(from: Position, to: Position, options?: CommentOptions): boolean; + } + + interface CommentOptions { + /** Override the [comment string properties](https://codemirror.net/doc/manual.html#mode_comment) of the mode with custom comment strings. */ + blockCommentStart?: string; + /** Override the [comment string properties](https://codemirror.net/doc/manual.html#mode_comment) of the mode with custom comment strings. */ + blockCommentEnd?: string; + /** Override the [comment string properties](https://codemirror.net/doc/manual.html#mode_comment) of the mode with custom comment strings. */ + blockCommentLead?: string; + /** Override the [comment string properties](https://codemirror.net/doc/manual.html#mode_comment) of the mode with custom comment strings. */ + lineComment?: string; + /** A string that will be inserted after opening and leading markers, and before closing comment markers. Defaults to a single space. */ + padding?: string; + /** Whether, when adding line comments, to also comment lines that contain only whitespace. */ + commentBlankLines?: boolean; + /** When adding line comments and this is turned on, it will align the comment block to the current indentation of the first line of the block. */ + indent?: boolean; + /** When block commenting, this controls whether the whole lines are indented, or only the precise range that is given. Defaults to `true`. */ + fullLines?: boolean; + } +} diff --git a/types/codemirror/codemirror-panel.d.ts b/types/codemirror/codemirror-panel.d.ts new file mode 100644 index 0000000000..a361992641 --- /dev/null +++ b/types/codemirror/codemirror-panel.d.ts @@ -0,0 +1,47 @@ +// Type definitions for CodeMirror +// Project: https://github.com/marijnh/CodeMirror +// Definitions by: Nikolaj Kappler +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// See docs https://codemirror.net/doc/manual.html#addon_panel + +import * as CodeMirror from "codemirror"; + +declare module "codemirror" { + interface Panel { + /**Removes the panel from the editor */ + clear(): void; + /**Notifies panel that height of DOM node has changed */ + changed(height?: number): void; + } + + interface ShowPanelOptions { + /**Controls the position of the newly added panel. The following values are recognized: + * `top` (default): Adds the panel at the very top. + * `after-top`: Adds the panel at the bottom of the top panels. + * `bottom`: Adds the panel at the very bottom. + * `before-bottom`: Adds the panel at the top of the bottom panels. + */ + position?: "top" | "after-top" | "bottom" | "before-bottom"; + /**The new panel will be added before the given panel. */ + before?: Panel; + /**The new panel will be added after the given panel. */ + after?: Panel; + /**The new panel will replace the given panel. */ + replace?: Panel; + /**Whether to scroll the editor to keep the text's vertical position stable, when adding a panel above it. Defaults to false. */ + stable?: boolean; + } + + interface Editor { + + /** + * Places a DOM node above or below an editor and shrinks the editor to make room for the node. + * When using the `after`, `before` or `replace` options, if the panel doesn't exists or has been removed, the value of the `position` option will be used as a fallback. + * @param node the DOM node + * @param options optional options object + */ + addPanel(node: HTMLElement, options?: ShowPanelOptions): Panel; + + } +} diff --git a/types/codemirror/codemirror-showhint.d.ts b/types/codemirror/codemirror-showhint.d.ts index c6f367d0d2..dfbbcdc4e1 100644 --- a/types/codemirror/codemirror-showhint.d.ts +++ b/types/codemirror/codemirror-showhint.d.ts @@ -76,7 +76,3 @@ declare module "codemirror" { hintOptions?: ShowHintOptions; } } - -declare module "codemirror/addon/hint/show-hint" { - export = CodeMirror; -} diff --git a/types/codemirror/index.d.ts b/types/codemirror/index.d.ts index 730fc1cb65..cdc3c4cd7c 100644 --- a/types/codemirror/index.d.ts +++ b/types/codemirror/index.d.ts @@ -4,6 +4,7 @@ // nrbernard // Pr1st0n // rileymiller +// toddself // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = CodeMirror; @@ -260,16 +261,7 @@ declare namespace CodeMirror { line should be either an integer or a line handle, and node should be a DOM node, which will be displayed below the given line. options, when given, should be an object that configures the behavior of the widget. Note that the widget node will become a descendant of nodes with CodeMirror-specific CSS classes, and those classes might in some cases affect it. */ - addLineWidget(line: any, node: HTMLElement, options?: { - /** Whether the widget should cover the gutter. */ - coverGutter?: boolean; - /** Whether the widget should stay fixed in the face of horizontal scrolling. */ - noHScroll?: boolean; - /** Causes the widget to be placed above instead of below the text of the line. */ - above?: boolean; - /** When true, will cause the widget to be rendered even if the line it is associated with is hidden. */ - showIfHidden?: boolean; - }): CodeMirror.LineWidget; + addLineWidget(line: any, node: HTMLElement, options?: CodeMirror.LineWidgetOptions): CodeMirror.LineWidget; /** Programatically set the size of the editor (overriding the applicable CSS rules). @@ -364,6 +356,12 @@ declare namespace CodeMirror { It will call the function, buffering up all changes, and only doing the expensive update after the function returns. This can be a lot faster. The return value from this method will be the return value of your function. */ operation(fn: ()=> T): T; + + /** In normal circumstances, use the above operation method. But if you want to buffer operations happening asynchronously, or that can't all be wrapped in a callback + function, you can call startOperation to tell CodeMirror to start buffering changes, and endOperation to actually render all the updates. Be careful: if you use this + API and forget to call endOperation, the editor will just never update. */ + startOperation(): void; + endOperation(): void; /** Adjust the indentation of the given line. The second argument (which defaults to "smart") may be one of: @@ -672,6 +670,11 @@ declare namespace CodeMirror { /** Returns an array containing all marked ranges in the document. */ getAllMarks(): CodeMirror.TextMarker[]; + /** Adds a line widget, an element shown below a line, spanning the whole of the editor's width, and moving the lines below it downwards. + line should be either an integer or a line handle, and node should be a DOM node, which will be displayed below the given line. + options, when given, should be an object that configures the behavior of the widget. + Note that the widget node will become a descendant of nodes with CodeMirror-specific CSS classes, and those classes might in some cases affect it. */ + addLineWidget(line: any, node: HTMLElement, options?: CodeMirror.LineWidgetOptions): CodeMirror.LineWidget; /** Gets the mode object for the editor. Note that this is distinct from getOption("mode"), which gives you the mode specification, rather than the resolved, instantiated mode object. */ @@ -709,8 +712,27 @@ declare namespace CodeMirror { or undefined if the marker is no longer in the document. */ find(): {from: CodeMirror.Position, to: CodeMirror.Position}; + /** Called when you've done something that might change the size of the marker and want to cheaply update the display*/ + changed(): void; + /** Returns an object representing the options for the marker. If copyWidget is given true, it will clone the value of the replacedWith option, if any. */ getOptions(copyWidget: boolean): CodeMirror.TextMarkerOptions; + + /** Fired when the cursor enters the marked range */ + on(eventName: 'beforeCursorEnter', handler: () => void) : void; + off(eventName: 'beforeCursorEnter', handler: () => void) : void; + + /** Fired when the range is cleared, either through cursor movement in combination with clearOnEnter or through a call to its clear() method */ + on(eventName: 'clear', handler: (from: Position, to: Position) => void) : void; + off(eventName: 'clear', handler: () => void) : void; + + /** Fired when the last part of the marker is removed from the document by editing operations */ + on(eventName: 'hide', handler: () => void) : void; + off(eventname: 'hide', handler: () => void) : void; + + /** Fired when, after the marker was removed by editing, a undo operation brough the marker back */ + on(eventName: 'unhide', handler: () => void) : void; + off(eventname: 'unhide', handler: () => void) : void; } interface LineWidget { @@ -722,6 +744,17 @@ declare namespace CodeMirror { changed(): void; } + interface LineWidgetOptions { + /** Whether the widget should cover the gutter. */ + coverGutter?: boolean; + /** Whether the widget should stay fixed in the face of horizontal scrolling. */ + noHScroll?: boolean; + /** Causes the widget to be placed above instead of below the text of the line. */ + above?: boolean; + /** When true, will cause the widget to be rendered even if the line it is associated with is hidden. */ + showIfHidden?: boolean; + } + interface EditorChange { /** Position (in the pre-change coordinate system) where the change started. */ from: CodeMirror.Position; diff --git a/types/codemirror/test/comment.ts b/types/codemirror/test/comment.ts new file mode 100644 index 0000000000..f022704a86 --- /dev/null +++ b/types/codemirror/test/comment.ts @@ -0,0 +1,16 @@ +const editor = CodeMirror(document.body); +const position: CodeMirror.Position = { ch: 0, line: 0 }; +const opt: CodeMirror.CommentOptions = { + blockCommentEnd: "*/", + blockCommentStart: "/*", + blockCommentLead: "*", + commentBlankLines: true, + fullLines: true, + indent: true, + lineComment: "//", + padding: " " +}; +editor.toggleComment(opt); +editor.blockComment(position, position, opt); +editor.lineComment(position, position, opt); +const b: boolean = editor.uncomment(position, position, opt); diff --git a/types/codemirror/test/index.ts b/types/codemirror/test/index.ts index bd2aefac88..851e891e8f 100644 --- a/types/codemirror/test/index.ts +++ b/types/codemirror/test/index.ts @@ -91,3 +91,12 @@ CodeMirror.registerHelper("lint", "javascript", {}); myCodeMirror.isReadOnly(); myCodeMirror.execCommand('selectAll'); + +let htmlElement1 = document.createElement('div'); +let htmlElement2 = document.createElement('div'); +let widget1 = myCodeMirror.addLineWidget(1, htmlElement1, {}); +let widget2 = doc.addLineWidget(1, htmlElement2, {}); +widget1.clear(); +widget2.clear(); +htmlElement1.remove(); +htmlElement2.remove(); diff --git a/types/codemirror/test/panel.ts b/types/codemirror/test/panel.ts new file mode 100644 index 0000000000..3cf200beae --- /dev/null +++ b/types/codemirror/test/panel.ts @@ -0,0 +1,17 @@ + +var cm: CodeMirror.Editor = CodeMirror(document.body); + +var panel1 = cm.addPanel(document.body); + +var panel2: CodeMirror.Panel = cm.addPanel(document.body, { + position: "top", + after: panel1, + before: panel1, + replace: panel1, + stable: true +}); + +panel2.changed(); +panel2.changed(100); + +panel2.clear(); diff --git a/types/codemirror/tsconfig.json b/types/codemirror/tsconfig.json index a2c6a52430..d081586f6e 100644 --- a/types/codemirror/tsconfig.json +++ b/types/codemirror/tsconfig.json @@ -20,13 +20,17 @@ "files": [ "index.d.ts", "codemirror-matchbrackets.d.ts", + "codemirror-panel.d.ts", "codemirror-runmode.d.ts", "codemirror-showhint.d.ts", + "codemirror-comment.d.ts", "searchcursor.d.ts", "test/index.ts", "test/matchbrackets.ts", + "test/panel.ts", "test/runmode.ts", "test/searchcursor.ts", - "test/showhint.ts" + "test/showhint.ts", + "test/comment.ts" ] } \ No newline at end of file diff --git a/types/colresizable/colresizable-tests.ts b/types/colresizable/colresizable-tests.ts new file mode 100644 index 0000000000..9fc62512c1 --- /dev/null +++ b/types/colresizable/colresizable-tests.ts @@ -0,0 +1,61 @@ +$("#table").colResizable(); // $ExpectType JQuery + +$("#table").colResizable({ + resizeMode: "fit", + disable: false, + disabledColumns: [1, 2, 3], + liveDrag: true, + postbackSafe: false, + partialRefresh: true, + headerOnly: false, + gripInnerHtml: "", + draggingClass: ".myClass", + minWidth: 100, + hoverCursor: 'pointer', + dragCursor: 'e-resize', + flush: false, + marginLeft: "14px", + marginRight: "auto", + fixed: false, + + onResize(evt) { + evt.currentTarget; // $ExpectType Element + }, + onDrag(evt) { + evt.currentTarget; // $ExpectType Element + } +}); + +// Samples at http://www.bacubacu.com/colresizable +function onSampleResized(e: JQueryMouseEventObject) { + const table = $(e.currentTarget); // reference to the resized table +} + +$("#sample").colResizable({ + liveDrag: true, + gripInnerHtml: "
", + draggingClass: "dragging", + onResize: onSampleResized +}); + +function postbackSample() { + $("#updatePanelSample").colResizable({ + liveDrag: true, + postbackSafe: true, + partialRefresh: true + }); +} + +$("#flexSample").colResizable({resizeMode: 'flex'}); + +$("#overflowSample").colResizable({resizeMode: 'overflow'}); + +function onSlide() {} + +$("#sample5").colResizable({ + liveDrag: true, + draggingClass: "rangeDrag", + gripInnerHtml: "
", + onResize: onSlide, + minWidth: 8 +}); diff --git a/types/colresizable/index.d.ts b/types/colresizable/index.d.ts new file mode 100644 index 0000000000..693c40923c --- /dev/null +++ b/types/colresizable/index.d.ts @@ -0,0 +1,149 @@ +// Type definitions for colresizable 1.6 +// Project: http://bacubacu.com/colresizable/ +// Definitions by: Gilles Waeber +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +/// + +interface JQuery { + colResizable(param?: colResizable.Settings): JQuery; +} + +declare namespace colResizable { + interface Settings { + /** + * [default: 'fit'] It is used to set how the resize method works. Those are the possible values: + * - 'fit': this is default resizing model, in which resizing a column does not alter table width, which means that when a column is expanded the next one shrinks. + * - 'flex': in this mode tables can change its width and each column can shrink or expand independently if there is enough space in the parent container. + * If there is not enough space, columns will share its width as they are resized. Table will never get bigger than its parent. + * - 'overflow': allows to resize columns with overflow of parent container. + * [version: 1.6] + */ + resizeMode?: 'fit' | 'flex' | 'overflow'; + + /** + * [default: false] When set to true the table layout is updated while dragging column anchors. + * liveDrag enabled is more CPU consuming so it is not recommended for slow computers, specially when dealing with huge or extremely complicated tables. + * [version: 1.0] + */ + liveDrag?: boolean; + + /** + * @deprecated use resizeMode instead + * [default: true] It is used to set how the resize method works. + * In fixed mode resizing a column does not alter total table width, which means that when a column is expanded the next one shrinks. + * If fixed is set to false then table can change its width and each column can shrink or expand independently. + * [version: 1.5] + */ + fixed?: boolean; + + /** + * [default: false] This attribute can be used to specify that the manually selected column widths must remain unaltered after a postback or browser refresh. + * This feature is mainly oriented to those pages created with server-side logic (codebehind), such as PHP or .NET, and it is only compatible with browsers + * with sessionStorage support (all modern browsers). + * However, if you are targeting older browsers (such as IE7 and IE8) you can still emulate sessionStorage using sessionStorage.js. + * It is important to note that some browsers (IE and FF) doesn’t enable the sessionStorage object while running the website directly from the local file system, + * so if you want to test this feature it is recommended to view the website through a web server or use browsers such as Chrome or Opera which doesn’t have this limitation. + * Don't worry about compatibility issues, once your site is up on the internet, all browsers will act in exactly the same way. + * [version: 1.3] + */ + postbackSafe?: boolean; + + /** + * [default: false] This attribute should be set to true if the table is inside of an updatePanel or any other kind of partial page refresh using ajax. + * Table's ID should be same before and after the partial partial refresh. + * [version: 1.5] + */ + partialRefresh?: boolean; + + /** + * [default: false] This attribute can be used to prevent vertical expansion of the column anchors to fit the table height. + * If it is set to true, column handler's size will be bounded to the first row's vertical size. + * [version: 1.2] + */ + headerOnly?: boolean; + + /** + * [default: ""] Its purpose is to allow column anchor customization by defining the HTML to be used in the column grips to provide some visual feedback. + * It can be used in a wide range of ways to obtain very different outputs, and its flexibility can be increased by combining it with the draggingClass attribute. + * [version: 1.0] + */ + gripInnerHtml?: string; + + /** + * [default: (internal class)] This attribute is used as the css class assigned to column anchors while being dragged. It can be used for visual feedback purposes. + * [version: 1.0] + */ + draggingClass?: string; + + /** + * [default: false] When set to true it aims to remove all previously added enhancements such as events and additional DOM elements assigned by this plugin to + * a single or collection of tables. It is required to disable a previously colResized table prior its removal from the document object tree. + * [version: 1.0] + */ + disable?: boolean; + + /** + * [default: [ ] ] An array of column indexes to be excluded, so it will not be possible to drag them manually. + * [version: 1.6] + */ + disabledColumns?: number[]; + + /** + * [default: 15] This value specifies the minimum width (measured in pixels) that is allowed for the columns. + * [version: 1.1] + */ + minWidth?: number; + + /** + * [default: "e-resize"] This attribute can be used to customize the cursor that will be displayed when the user is positioned on the column anchors. + * [version: 1.3] + */ + hoverCursor?: string; + + /** + * [default: "e-resize"] Defines the cursor that will be used while the user is resizing a column. + * [version: 1.3] + */ + dragCursor?: string; + + /** + * [default: false] Flush is only effective when postbackSafe is enabled. + * Its purpose is to remove all previously stored data related to the current table layout to get it back to its original layout preventing width restoration after postback. + * [version: ] + */ + flush?: boolean; + + /** + * [default: null] If the target table contains an explicit margin-left CSS rule, the same value must be used in this attribute (for example: "auto", "20%", "10px"). + * The reason why it is needed it is because most browsers (all except of IE) don’t allow direct access to the current CSS rule applied to an element in + * its original units (such as "%", "em" or "auto" values). + * If you know any workaround which doesn’t involve iteration through all the styles defined in the site and any other external dependencies, please let me know! + * [version: 1.3] + */ + marginLeft?: string; + + /** + * [default: null] It behaves in exactly the same way than the marginLeft attribute but applied to the right margin. + * [version: 1.3] + */ + marginRight?: string; + + /** + * If a callback function is supplied it will be fired when the user has ended dragging a column anchor altering the previous table layout. + * The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters + * [version: 1.0] + */ + onResize?: FunctionCallback; + + /** + * This event is fired while dragging a column anchor if liveDrag is enabled. It can be useful if the table is being used as a multiple range slider. + * The callback function can obtain a reference to the updated table through the currentTarget attribute of the event retrieved by parameters + * [version: 1.1] + */ + onDrag?: FunctionCallback; + } + + type FunctionCallback = (e: JQueryMouseEventObject) => void; +} diff --git a/types/colresizable/tsconfig.json b/types/colresizable/tsconfig.json new file mode 100644 index 0000000000..35bf902824 --- /dev/null +++ b/types/colresizable/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", + "colresizable-tests.ts" + ] +} diff --git a/types/colresizable/tslint.json b/types/colresizable/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/colresizable/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/combined-stream/combined-stream-tests.ts b/types/combined-stream/combined-stream-tests.ts index ffdc0eaac7..540db77b68 100644 --- a/types/combined-stream/combined-stream-tests.ts +++ b/types/combined-stream/combined-stream-tests.ts @@ -1,17 +1,17 @@ -import CombinedStream = require("combined-stream"); -import { createReadStream, createWriteStream } from "fs"; +import CombinedStream = require('combined-stream'); +import { createReadStream, createWriteStream } from 'fs'; const stream1 = new CombinedStream(); -stream1.append(createReadStream("tsconfig.json")); -stream1.append(createReadStream("tslint.json")); -stream1.append(createReadStream("index.d.ts")); +stream1.append(createReadStream('tsconfig.json')); +stream1.append(createReadStream('tslint.json')); +stream1.append(createReadStream('index.d.ts')); -stream1.pipe(createWriteStream("combined.txt")); +stream1.pipe(createWriteStream('combined.txt')); const stream2 = CombinedStream.create({ maxDataSize: 1 << 32, - pauseStreams: false, + pauseStreams: false }); stream1.destroy(); @@ -19,12 +19,29 @@ stream1.destroy(); // should log true console.log(CombinedStream.isStreamLike(stream2)); -stream2.on("data", (data) => { +stream2.on('data', data => { console.log(data); }); -stream2.pipe(createWriteStream("combined.txt")); +stream2.pipe(createWriteStream('combined.txt')); stream2.write(CombinedStream.name); stream2.destroy(); + +const arrowFunction = (): CombinedStream => { + const stream3 = new CombinedStream(); + + // test next function + stream3.append(next => { + stream3.append('hello world'); + next(createReadStream('')); + }); + + // next function with no next + stream3.append(() => { + stream3.append('hello again'); + }); + + return stream3; +}; diff --git a/types/combined-stream/index.d.ts b/types/combined-stream/index.d.ts index 271814a4af..b82b399e7f 100644 --- a/types/combined-stream/index.d.ts +++ b/types/combined-stream/index.d.ts @@ -1,19 +1,27 @@ // Type definitions for combined-stream 1.0 // Project: https://github.com/felixge/node-combined-stream -// Definitions by: Felix Geisendörfer , Tomek Łaziuk +// Definitions by: Felix Geisendörfer , Tomek Łaziuk , Kon Pik // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// -import { Stream } from "stream"; +import { Stream } from 'stream'; -declare class CombinedStream extends Stream implements CombinedStream.Options { +type Appendable = NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string | NextFunction; +type NextFunction = (next: (stream: Appendable) => any) => any; + +interface Options { + maxDataSize?: number; + pauseStreams?: boolean; +} + +declare class CombinedStream extends Stream implements Options { readonly writable: boolean; readonly readable: boolean; readonly dataSize: number; maxDataSize: number; pauseStreams: boolean; - append(stream: NodeJS.ReadableStream | NodeJS.WritableStream | Buffer | string): this; + append(stream: Appendable): this; write(data: any): void; pause(): void; resume(): void; @@ -34,23 +42,15 @@ declare class CombinedStream extends Stream implements CombinedStream.Options { _emitError(error: Error): void; // events - on(event: "close" | "end" | "resume" | "pause", cb: () => void): this; - on(event: "error", cb: (err: Error) => void): this; - on(event: "data", cb: (data: any) => void): this; - once(event: "close" | "end" | "resume" | "pause", cb: () => void): this; - once(event: "error", cb: (err: Error) => void): this; - once(event: "data", cb: (data: any) => void): this; -} + on(event: 'close' | 'end' | 'resume' | 'pause', cb: () => void): this; + on(event: 'error', cb: (err: Error) => void): this; + on(event: 'data', cb: (data: any) => void): this; + once(event: 'close' | 'end' | 'resume' | 'pause', cb: () => void): this; + once(event: 'error', cb: (err: Error) => void): this; + once(event: 'data', cb: (data: any) => void): this; -declare namespace CombinedStream { - interface Options { - maxDataSize?: number; - pauseStreams?: boolean; - } - - function create(options?: Options): CombinedStream; - - function isStreamLike(stream: any): stream is Stream; + static create(options?: Options): CombinedStream; + static isStreamLike(stream: any): stream is Stream; } export = CombinedStream; diff --git a/types/cometd/cometd-tests.ts b/types/cometd/cometd-tests.ts index ada9412c04..ef56879d6f 100644 --- a/types/cometd/cometd-tests.ts +++ b/types/cometd/cometd-tests.ts @@ -1,4 +1,4 @@ -import { CometD, Listener, Message } from "cometd"; +import { CometD, Listener, Message, SubscriptionHandle } from "cometd"; const cometd = new CometD(); @@ -78,7 +78,7 @@ cometd.unsubscribe(subscription3, additionalInfoUnsubscribe, unsubscribeReply => // Subscribers versus Listeners // ============================ -let _reportListener: Listener | undefined; +let _reportListener: SubscriptionHandle | undefined; cometd.addListener("/meta/handshake", message => { // Only subscribe if the handshake is successful @@ -106,7 +106,7 @@ cometd.addListener("/meta/handshake", message => { // Dynamic Resubscription // ====================== -let _subscription: Listener | undefined; +let _subscription: SubscriptionHandle | undefined; class Controller { dynamicSubscribe = () => { diff --git a/types/cometd/index.d.ts b/types/cometd/index.d.ts index 32e4f962bb..cd829d444c 100644 --- a/types/cometd/index.d.ts +++ b/types/cometd/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for CometD 4.0 // Project: http://cometd.org -// Definitions by: Derek Cicerone , Daniel Perez Alvarez +// Definitions by: Derek Cicerone , Daniel Perez Alvarez , Alex Henry // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -75,6 +75,15 @@ export interface Message { } export type Listener = (message: Message) => void; +export type Callback = (data: any) => void; + +export interface SubscriptionHandle { + id: number; + channel: string; + listener: boolean; + callback: Callback; + scope?: any; +} export interface Extension { incoming?: Listener; @@ -202,14 +211,14 @@ export class CometD { * @param callback the callback to call when a message is sent to the channel * @returns the subscription handle to be passed to `removeListener` */ - addListener(channel: string, callback: Listener): Listener; + addListener(channel: string, callback: Listener): SubscriptionHandle; /** * Removes the subscription obtained with a call to `addListener`. * * @param subscription the subscription to unsubscribe. */ - removeListener(subscription: Listener): void; + removeListener(subscription: SubscriptionHandle): void; /** * Removes all listeners registered with `addListener` or `subscribe`. @@ -234,7 +243,7 @@ export class CometD { * @param subscribeCallback a function to be invoked when the subscription is acknowledged * @return the subscription handle to be passed to `unsubscribe` */ - subscribe(channel: string, callback: Listener, subscribeCallback?: Listener): Listener; + subscribe(channel: string, callback: Callback, subscribeCallback?: Listener): SubscriptionHandle; /** * Subscribes to the given channel, performing the given callback in the given scope when a @@ -255,7 +264,7 @@ export class CometD { * @param subscribeCallback a function to be invoked when the subscription is acknowledged * @return the subscription handle to be passed to `unsubscribe` */ - subscribe(channel: string, callback: Listener, subscribeProps: object, subscribeCallback?: Listener): Listener; + subscribe(channel: string, callback: Callback, subscribeProps: object, subscribeCallback?: Listener): SubscriptionHandle; /** * Unsubscribes the subscription obtained with a call to `subscribe`. @@ -263,7 +272,7 @@ export class CometD { * @param subscription the subscription to unsubscribe. * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged */ - unsubscribe(subscription: Listener, unsubscribeCallback?: Listener): void; + unsubscribe(subscription: SubscriptionHandle, unsubscribeCallback?: Listener): void; /** * Unsubscribes the subscription obtained with a call to `subscribe`. @@ -272,12 +281,12 @@ export class CometD { * @param unsubscribeProps an object to be merged with the unsubscribe message * @param unsubscribeCallback a function to be invoked when the unsubscription is acknowledged */ - unsubscribe(subscription: Listener, unsubscribeProps: object, unsubscribeCallback?: Listener): void; + unsubscribe(subscription: SubscriptionHandle, unsubscribeProps: object, unsubscribeCallback?: Listener): void; /** * Resubscribes as necessary in case of a re-handshake. */ - resubscribe(subscription: Listener, subscribeProps?: object): Listener; + resubscribe(subscription: SubscriptionHandle, subscribeProps?: object): SubscriptionHandle; /** * Removes all subscriptions added via `subscribe`, but does not remove the listeners added via @@ -463,5 +472,5 @@ export class CometD { * @param isListener whether it was a listener * @param message the message received from the Bayeux server */ - onListenerException: (exception: any, subscriptionHandle: Listener, isListener: boolean, message: string) => void; + onListenerException: (exception: any, subscriptionHandle: SubscriptionHandle, isListener: boolean, message: string) => void; } 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/commangular/commangular-mock.d.ts b/types/commangular/commangular-mock.d.ts index 134e4d0d1e..a31563bc9e 100644 --- a/types/commangular/commangular-mock.d.ts +++ b/types/commangular/commangular-mock.d.ts @@ -4,33 +4,33 @@ // Definitions: https://github.com/borisyankov/DefinitelyTyped declare module commangular { - + /////////////////////////////////////////////////////////////////////////// // Commangular Static // see http://commangular.org/docs/#commangular-namespace /////////////////////////////////////////////////////////////////////////// interface ICommAngularStatic { - + /** * Mock dispatch function for testing commands. */ dispatch( ec: ICommandCall, callback: Function ): void; } - + interface ICommandCall { /** * Name of the command that needs to * execute */ command: string; - + /** * Data that needs to be passed to the command */ data?: any; } - - + + /** * Object type expected to be passed into the callback function * of the dispatch() function @@ -41,25 +41,25 @@ declare module commangular { * @param key The property name that is in the object that was passed */ dataPassed( key : string ) : any; - + /** * The data that was returned by the command * @param key The result key that was defined in the command. If no result * was defined use 'lastResult' as the key */ resultKey( key: string ): any; - + /** * Indicates if the command execution was cancelled. */ canceled( ): boolean; - + /** * Indicates if the command was executed???? */ commandExecuted( ): boolean; } - + } @@ -67,7 +67,6 @@ declare module commangular { * Mock dispatch function for testing commands. * @param ec an ICommandCall object * @param callback The function that will be called upon the completion of the command -* function should expecte an ICommandInfo paramter. +* function should expecte an ICommandInfo parameter. */ -declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; - +declare function dispatch( ec: commangular.ICommandCall, callback: Function ): void; diff --git a/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx new file mode 100644 index 0000000000..bceab689e7 --- /dev/null +++ b/types/commercetools__enzyme-extensions/commercetools__enzyme-extensions-tests.tsx @@ -0,0 +1,30 @@ +import React = require('react'); +import enzyme = require('enzyme'); +import configureExtensions = require('@commercetools/enzyme-extensions'); + +configureExtensions(enzyme.ShallowWrapper); + +function App() { + return 'Hello world'} />; +} + +interface ChildProps { + cb: () => string; +} + +function Child(props: ChildProps) { + return
{props.cb()}
; +} + +enzyme.shallow() + .find(App) + .renderProp('render'); +enzyme.shallow() + .find(Child) + .renderProp('render', 1, 2); + +enzyme.shallow() + .find(Child) + .drill(props => props.cb()); + +enzyme.shallow().until(Child); diff --git a/types/commercetools__enzyme-extensions/index.d.ts b/types/commercetools__enzyme-extensions/index.d.ts new file mode 100644 index 0000000000..7c009f8e95 --- /dev/null +++ b/types/commercetools__enzyme-extensions/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for @commercetools/enzyme-extensions 3.0 +// Project: https://github.com/commercetools/enzyme-extensions +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as enzyme from 'enzyme'; + +declare module 'enzyme' { + interface UntilOptions { + maxDepth: number; + } + interface ShallowWrapper

{ + renderProp(propName: string, ...args: any[]): ShallowWrapper

; + drill(expander: (props: any) => ShallowWrapper): ShallowWrapper

; + until(selector: EnzymeSelector, options?: UntilOptions): ShallowWrapper

; + } +} + +declare function monkeyPatchShallowWrapper(s: typeof enzyme.ShallowWrapper): void; + +export = monkeyPatchShallowWrapper; diff --git a/types/commercetools__enzyme-extensions/tsconfig.json b/types/commercetools__enzyme-extensions/tsconfig.json new file mode 100644 index 0000000000..9e6d70239e --- /dev/null +++ b/types/commercetools__enzyme-extensions/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react", + "paths": { + "@commercetools/enzyme-extensions": ["commercetools__enzyme-extensions"] + } + }, + "files": [ + "index.d.ts", + "commercetools__enzyme-extensions-tests.tsx" + ] +} diff --git a/types/commercetools__enzyme-extensions/tslint.json b/types/commercetools__enzyme-extensions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/commercetools__enzyme-extensions/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/compare-func/compare-func-tests.ts b/types/compare-func/compare-func-tests.ts new file mode 100644 index 0000000000..47b2842724 --- /dev/null +++ b/types/compare-func/compare-func-tests.ts @@ -0,0 +1,30 @@ +import compareFunc = require("compare-func"); + +// This is taken from https://github.com/stevemao/compare-func/blob/master/README.md#usage and extended + +// sort by an object property +[{ x: "b" }, { x: "a" }, { x: "c" }].sort(compareFunc("x")); +// => [{x: "a"}, {x: "b"}, {x: "c"}] + +// sort by a nested object property +[{ x: { y: "b" } }, { x: { y: "a" } }].sort(compareFunc("x.y")); +// => [{x: {y: "a"}}, {x: {y: "b"}}] + +// sort by the `x` property, then `y` +[{ x: "c", y: "c" }, { x: "b", y: "a" }, { x: "b", y: "b" }].sort(compareFunc(["x", "y"])); +// => [{x: "b", y: "a"}, {x: "b", y: "b"}, {x: "c", y: "c"}] + +// sort by the returned value +[{ x: "b" }, { x: "a" }, { x: "c" }].sort(compareFunc((el) => el.x)); +// => [{x: "a"}, {x: "b"}, {x: "c"}] + +// sort by an array of functions +[{ x: "c", y: "c" }, { x: "b", y: "a" }, { x: "b", y: "b" }].sort(compareFunc([ + (el) => el.x, + (el) => el.y, +])); +// => [{x: "a"}, {x: "b"}, {x: "c"}] + +// sort by itself +[1, 3, 2].sort(compareFunc()); +// => [1, 2, 3] diff --git a/types/compare-func/index.d.ts b/types/compare-func/index.d.ts new file mode 100644 index 0000000000..357de04fb0 --- /dev/null +++ b/types/compare-func/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for compare-func 1.3 +// Project: https://github.com/stevemao/compare-func +// Definitions by: Dogan Fennibay +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +type extractFunc = (e: T) => number | string; + +declare function compare_func(prop?: ReadonlyArray> | string | extractFunc): + (e1: T, e2: T) => number; + +export = compare_func; diff --git a/types/compare-func/tsconfig.json b/types/compare-func/tsconfig.json new file mode 100644 index 0000000000..9aa5f60c9d --- /dev/null +++ b/types/compare-func/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", + "compare-func-tests.ts" + ] +} diff --git a/types/compare-func/tslint.json b/types/compare-func/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/compare-func/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-datadog/connect-datadog-tests.ts b/types/connect-datadog/connect-datadog-tests.ts new file mode 100644 index 0000000000..4160ba4bc0 --- /dev/null +++ b/types/connect-datadog/connect-datadog-tests.ts @@ -0,0 +1,16 @@ +import connectDD = require('connect-datadog'); +import dogstatsd = require('node-dogstatsd'); + +// works with no options +const middleware = connectDD({}); + +// works with all options +const middleware2 = connectDD({ + stat: 'foo', + path: true, + method: true, + protocol: true, + response_code: true, + tags: ['abc', 'def'], + dogstatsd: new dogstatsd.StatsD('localhost'), +}); diff --git a/types/connect-datadog/index.d.ts b/types/connect-datadog/index.d.ts new file mode 100644 index 0000000000..c3aad8aac7 --- /dev/null +++ b/types/connect-datadog/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for connect-datadog 0.0 +// Project: https://github.com/AppPress/node-connect-datadog +// Definitions by: Moshe Good +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import express = require('express'); +import dogstatsd = require('node-dogstatsd'); + +export = Factory; + +declare function Factory(options?: Factory.Options): express.RequestHandler; + +declare namespace Factory { + interface Options { + stat?: string; + tags?: string[]; + path?: boolean; + method?: boolean; + protocol?: boolean; + response_code?: boolean; + dogstatsd?: dogstatsd.StatsD; + } +} diff --git a/types/connect-datadog/tsconfig.json b/types/connect-datadog/tsconfig.json new file mode 100644 index 0000000000..fa91239b96 --- /dev/null +++ b/types/connect-datadog/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", + "connect-datadog-tests.ts" + ] +} diff --git a/types/connect-datadog/tslint.json b/types/connect-datadog/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/connect-datadog/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/connect-redis/index.d.ts b/types/connect-redis/index.d.ts index 5675512795..c5a26de73a 100644 --- a/types/connect-redis/index.d.ts +++ b/types/connect-redis/index.d.ts @@ -1,7 +1,6 @@ // Type definitions for connect-redis // Project: https://npmjs.com/package/connect-redis // Definitions by: Xavier Stouder -// Albert Kurniawan // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 diff --git a/types/consola/consola-tests.ts b/types/consola/consola-tests.ts new file mode 100644 index 0000000000..f6cc225346 --- /dev/null +++ b/types/consola/consola-tests.ts @@ -0,0 +1,15 @@ +import * as consola from 'consola'; + +consola.start('TEST'); +consola.info('TEST'); +consola.success('TEST'); +consola.error('TEST'); + +const logger = new consola.Consola({ + level: 30, +}); + +logger.start('TEST'); +logger.info('TEST'); +logger.success('TEST'); +logger.error('TEST'); diff --git a/types/consola/index.d.ts b/types/consola/index.d.ts new file mode 100644 index 0000000000..a17c0c5c8f --- /dev/null +++ b/types/consola/index.d.ts @@ -0,0 +1,39 @@ +// Type definitions for consola 1.x +// Project: https://github.com/nuxt/consola +// Definitions by: Jungwoo An +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +export interface LevelType { + level: number; + color: string; + isError?: boolean; +} + +export interface Reporter { + log(logObj: any): void; +} + +export interface Option { + level?: number; + types?: LevelType; + reporters?: Reporter[]; +} + +export class Consola { + constructor(option?: Option); + + add(reporter: Reporter): Consola; + remove(reporter: Reporter): Consola; + clear(): Consola; + withScope(scope: string): void; + start(...arguments: string[]): void; + success(...arguments: string[]): void; + info(...arguments: string[]): void; + error(...arguments: Array): void; +} + +export function start(...arguments: string[]): void; +export function success(...arguments: string[]): void; +export function info(...arguments: string[]): void; +export function error(...arguments: Array): void; diff --git a/types/consola/tsconfig.json b/types/consola/tsconfig.json new file mode 100644 index 0000000000..aab34c3363 --- /dev/null +++ b/types/consola/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noEmit": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "consola-tests.ts"] +} diff --git a/types/consola/tslint.json b/types/consola/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/consola/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/consul/index.d.ts b/types/consul/index.d.ts index 3d344ae983..096a906c8b 100644 --- a/types/consul/index.d.ts +++ b/types/consul/index.d.ts @@ -625,6 +625,7 @@ declare namespace Consul { dc?: string; tag?: string; passing?: boolean; + near?: string; } interface StateOptions extends CommonOptions { 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/cookie/index.d.ts b/types/cookie/index.d.ts index bb7fc2cb54..cb03c91980 100644 --- a/types/cookie/index.d.ts +++ b/types/cookie/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for cookie 0.3 // Project: https://github.com/jshttp/cookie -// Definitions by: Pine Mizune +// Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface CookieSerializeOptions { diff --git a/types/copy-text-to-clipboard/tslint.json b/types/copy-text-to-clipboard/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/copy-text-to-clipboard/tslint.json +++ b/types/copy-text-to-clipboard/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts new file mode 100644 index 0000000000..72925fe5ba --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/cordova-plugin-bluetoothclassic-serial-tests.ts @@ -0,0 +1,63 @@ +let BluetoothClassicSerial: BluetoothClassicSerial = + window.BluetoothClassicSerial; + +BluetoothClassicSerial.connect( + "", + [""] +); +BluetoothClassicSerial.connect( + "", + [""], + results => {} +); +BluetoothClassicSerial.connect( + "", + [""], + results => {}, + error => {} +); +BluetoothClassicSerial.connectInsecure("", [""]); +BluetoothClassicSerial.connectInsecure("", [""], results => {}); +BluetoothClassicSerial.connectInsecure("", [""], results => {}, error => {}); +BluetoothClassicSerial.register(() => {}); +BluetoothClassicSerial.disconnect(results => {}); +BluetoothClassicSerial.disconnect(results => {}, error => {}); +BluetoothClassicSerial.write("", ""); +BluetoothClassicSerial.write("", "", results => {}); +BluetoothClassicSerial.write("", "", results => {}, error => {}); +BluetoothClassicSerial.available(""); +BluetoothClassicSerial.available("", results => {}); +BluetoothClassicSerial.available("", results => {}, error => {}); +BluetoothClassicSerial.read(""); +BluetoothClassicSerial.read("", results => {}); +BluetoothClassicSerial.read("", results => {}, error => {}); +BluetoothClassicSerial.readUntil("", ""); +BluetoothClassicSerial.readUntil("", "", results => {}); +BluetoothClassicSerial.readUntil("", "", results => {}, error => {}); +BluetoothClassicSerial.subscribe("", ""); +BluetoothClassicSerial.subscribe("", "", results => {}); +BluetoothClassicSerial.subscribe("", "", results => {}, error => {}); +BluetoothClassicSerial.unsubscribe(""); +BluetoothClassicSerial.unsubscribe("", results => {}); +BluetoothClassicSerial.unsubscribe("", results => {}, error => {}); +BluetoothClassicSerial.subscribeRawData(""); +BluetoothClassicSerial.subscribeRawData("", results => {}); +BluetoothClassicSerial.subscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.unsubscribeRawData(""); +BluetoothClassicSerial.unsubscribeRawData("", results => {}); +BluetoothClassicSerial.unsubscribeRawData("", results => {}, error => {}); +BluetoothClassicSerial.clear(""); +BluetoothClassicSerial.clear("", results => {}); +BluetoothClassicSerial.clear("", results => {}, error => {}); +BluetoothClassicSerial.list(results => {}); +BluetoothClassicSerial.list(results => {}, error => {}); +BluetoothClassicSerial.isConnected(results => {}); +BluetoothClassicSerial.isConnected(results => {}, error => {}); +BluetoothClassicSerial.isEnabled(results => {}); +BluetoothClassicSerial.isEnabled(results => {}, error => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}); +BluetoothClassicSerial.showBluetoothSettings(results => {}, error => {}); +BluetoothClassicSerial.enable(results => {}); +BluetoothClassicSerial.enable(results => {}, error => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}); +BluetoothClassicSerial.discoverUnpaired(results => {}, error => {}); diff --git a/types/cordova-plugin-bluetoothclassic-serial/index.d.ts b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts new file mode 100644 index 0000000000..2dfe8c94ae --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/index.d.ts @@ -0,0 +1,105 @@ +// Type definitions for cordova-plugin-bluetoothClassic-serial 0.9 +// Project: https://github.com/soltius/BluetoothClassicSerial +// Definitions by: Wouter Roosendaal +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Global object bluetoothClassicSerial. + */ +interface Window { + BluetoothClassicSerial: BluetoothClassicSerial; +} + +interface BluetoothClassicSerial { + connect: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + connectInsecure: ( + deviceId: string, + interfaceArray: [any], + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + register: (data_cb?: () => any) => void; + disconnect: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + write: ( + interfaceId: string, + data: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + available: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + read: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + readUntil: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribe: ( + interfaceId: string, + delimiter: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribe: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + subscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + unsubscribeRawData: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + clear: ( + interfaceId: string, + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + list: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isConnected: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + isEnabled: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + showBluetoothSettings: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + enable: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; + discoverUnpaired: ( + success_cb?: (results: any) => any, + fail_cb?: (error: any) => any + ) => void; +} + +declare var bluetoothClassicSerial: BluetoothClassicSerial; diff --git a/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json b/types/cordova-plugin-bluetoothclassic-serial/tsconfig.json new file mode 100644 index 0000000000..5cd12b710a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/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", + "cordova-plugin-bluetoothclassic-serial-tests.ts" + ] +} diff --git a/types/cordova-plugin-bluetoothclassic-serial/tslint.json b/types/cordova-plugin-bluetoothclassic-serial/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/cordova-plugin-bluetoothclassic-serial/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/cordova/tslint.json b/types/cordova/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/cordova/tslint.json +++ b/types/cordova/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/countdown/tslint.json b/types/countdown/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/countdown/tslint.json +++ b/types/countdown/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/country-list/country-list-tests.ts b/types/country-list/country-list-tests.ts index d96fe630e2..50952d2a87 100644 --- a/types/country-list/country-list-tests.ts +++ b/types/country-list/country-list-tests.ts @@ -1,5 +1,4 @@ -import countries from 'country-list'; -const Countries = countries(); +import * as Countries from 'country-list'; Countries.getCode('Barbados'); // BB @@ -14,3 +13,5 @@ Countries.getName('BB'); // Barbados Countries.getNameList(); Countries.getNames(); + +Countries.overwrite([{ code: 'TW', name: 'Taiwan' }]); diff --git a/types/country-list/index.d.ts b/types/country-list/index.d.ts index 6c1747ff2a..ac3c80c9d5 100644 --- a/types/country-list/index.d.ts +++ b/types/country-list/index.d.ts @@ -1,41 +1,45 @@ -// Type definitions for country-list 1.1 +// Type definitions for country-list 2.1 // Project: https://github.com/fannarsh/country-list // Definitions by: Kyle Roach +// Adam Binford // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export default function Countries(): { - /** - * Expects a two-digit country code. Returns the name for that country. If not found, it returns undefined. - */ - getName(code: string): string | undefined; +/** + * Expects an array of code and country name pairs to add to the list. Doesn't return anything. + */ +export function overwrite(countries: Array<{ code: string, name: string}>): void; - /** - * Expects the English country name. Returns the code for that country. If not found, it returns undefined. - */ - getCode(name: string): string | undefined; +/** + * Expects a two-digit country code. Returns the name for that country. If not found, it returns undefined. + */ +export function getName(code: string): string | undefined; - /** - * Returns an array of all country names. - */ - getNames(): string[]; +/** + * Expects the English country name. Returns the code for that country. If not found, it returns undefined. + */ +export function getCode(name: string): string | undefined; - /** - * Returns an array of all country codes. - */ - getCodes(): string[]; +/** + * Returns an array of all country names. + */ +export function getNames(): string[]; - /** - * Returns a key-value object of all countries using the name as key. - */ - getNameList(): {[name: string]: string}; +/** + * Returns an array of all country codes. + */ +export function getCodes(): string[]; - /** - * Returns a key-value object of all countries using the code as key. - */ - getCodeList(): {[code: string]: string}; +/** + * Returns a key-value object of all countries using the name as key. + */ +export function getNameList(): {[name: string]: string}; - /** - * Returns an array of all country information, in the same format as it gets imported. - */ - getData(): Array<{ code: string, name: string }>; -}; +/** + * Returns a key-value object of all countries using the code as key. + */ +export function getCodeList(): {[code: string]: string}; + +/** + * Returns an array of all country information, in the same format as it gets imported. + */ +export function getData(): Array<{ code: string, name: string }>; diff --git a/types/country-list/v1/country-list-tests.ts b/types/country-list/v1/country-list-tests.ts new file mode 100644 index 0000000000..d96fe630e2 --- /dev/null +++ b/types/country-list/v1/country-list-tests.ts @@ -0,0 +1,16 @@ +import countries from 'country-list'; +const Countries = countries(); + +Countries.getCode('Barbados'); // BB + +Countries.getCodes(); + +Countries.getCodeList(); + +Countries.getData(); + +Countries.getName('BB'); // Barbados + +Countries.getNameList(); + +Countries.getNames(); diff --git a/types/country-list/v1/index.d.ts b/types/country-list/v1/index.d.ts new file mode 100644 index 0000000000..e225845bde --- /dev/null +++ b/types/country-list/v1/index.d.ts @@ -0,0 +1,41 @@ +// Type definitions for country-list 1.1 +// Project: https://github.com/fannarsh/country-list +// Definitions by: Kyle Roach +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export default function Countries(): { + /** + * Expects a two-digit country code. Returns the name for that country. If not found, it returns undefined. + */ + getName(code: string): string | undefined; + + /** + * Expects the English country name. Returns the code for that country. If not found, it returns undefined. + */ + getCode(name: string): string | undefined; + + /** + * Returns an array of all country names. + */ + getNames(): string[]; + + /** + * Returns an array of all country codes. + */ + getCodes(): string[]; + + /** + * Returns a key-value object of all countries using the name as key. + */ + getNameList(): {[name: string]: string}; + + /** + * Returns a key-value object of all countries using the code as key. + */ + getCodeList(): {[code: string]: string}; + + /** + * Returns an array of all country information, in the same format as it gets imported. + */ + getData(): Array<{ code: string, name: string }>; +}; diff --git a/types/country-list/v1/tsconfig.json b/types/country-list/v1/tsconfig.json new file mode 100644 index 0000000000..f10adfdde5 --- /dev/null +++ b/types/country-list/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "country-list": ["country-list/v1"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "country-list-tests.ts" + ] +} \ No newline at end of file diff --git a/types/country-list/v1/tslint.json b/types/country-list/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/country-list/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/critters-webpack-plugin/critters-webpack-plugin-tests.ts b/types/critters-webpack-plugin/critters-webpack-plugin-tests.ts new file mode 100644 index 0000000000..69d520eaff --- /dev/null +++ b/types/critters-webpack-plugin/critters-webpack-plugin-tests.ts @@ -0,0 +1,14 @@ +import Critters from 'critters-webpack-plugin'; + +new Critters({ + compress: true, + external: true, + inlineFonts: false, + preloadFonts: true, + keyframes: 'critical', + noscriptFallback: true, + inlineThreshold: 0, + mergeStylesheets: true, + pruneSource: true, + minimumExternalSize: 0, +}); diff --git a/types/critters-webpack-plugin/index.d.ts b/types/critters-webpack-plugin/index.d.ts new file mode 100644 index 0000000000..daf9b3c218 --- /dev/null +++ b/types/critters-webpack-plugin/index.d.ts @@ -0,0 +1,85 @@ +// Type definitions for critters-webpack-plugin 2.0 +// Project: https://github.com/GoogleChromeLabs/critters +// Definitions by: Juan José González Giraldo +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin } from 'webpack'; + +export default Critters; +declare class Critters extends Plugin { + constructor(options?: Critters.CrittersOptions); +} + +declare namespace Critters { + interface CrittersOptions { + /** + * Inline styles from external stylesheets. + * @default true + */ + external?: boolean; + /** + * Inline external stylesheets smaller than a given size. + * @default 0 + */ + inlineThreshold?: number; + /** + * If the non-critical external stylesheet would be below this size, just inline it. + * @default 0 + */ + minimumExternalSize?: number; + /** + * Remove inlined rules from the external stylesheet. + * @default true + */ + pruneSource?: boolean; + /** + * Merged inlined stylesheets into a single + + + +​ +
​ + +​ + + +``` + */ + length: number; + /** + * Create a new jQuery object with elements added to the set of matched elements. + * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. + * @param context The point in the document at which the selector should begin matching; similar to the context + * argument of the $(selector, context) method. + * @see \`{@link https://api.jquery.com/add/ }\` + * @since 1.4 + */ + add(selector: JQuery.Selector, context: Element): this; + /** + * Create a new jQuery object with elements added to the set of matched elements. + * @param selector_elements_html_selection _@param_ `selector_elements_html_selection` + *
+ * * `selector` — A string representing a selector expression to find additional elements to add to the set of matched elements.
+ * * `elements` — One or more elements to add to the set of matched elements.
+ * * `html` — An HTML fragment to add to the set of matched elements.
+ * * `selection` — An existing jQuery object to add to the set of matched elements. + * @see \`{@link https://api.jquery.com/add/ }\` + * @since 1.0 + * @since 1.3.2 + * @example ​ ````Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow. +```html + + + + + add demo + + + + +​ +
+
+
+
+
+
+​ +

Added this... (notice no border)

+​ + +​ + + +``` + * @example ​ ````Adds more elements, matched by the given expression, to the set of matched elements. +```html + + + + + add demo + + + +​ +

Hello

+Hello Again +​ + +​ + + +``` + * @example ​ ````Adds more elements, created on the fly, to the set of matched elements. +```html + + + + + add demo + + + +​ +

Hello

+​ + +​ + + +``` + * @example ​ ````Adds one or more Elements to the set of matched elements. +```html + + + + + add demo + + + +​ +

Hello

+Hello Again +​ + +​ + + +``` + * @example ​ ````Demonstrates how to add (or push) elements to an existing collection +```html + + + + + add demo + + + +​ +

Hello

+Hello Again +​ + +​ + + +``` + */ + add(selector_elements_html_selection: JQuery.Selector | JQuery.TypeOrArray | JQuery.htmlString | JQuery): this; + /** + * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. + * @param selector A string containing a selector expression to match the current set of elements against. + * @see \`{@link https://api.jquery.com/addBack/ }\` + * @since 1.8 + * @example ​ ````The .addBack() method causes the previous set of DOM elements in the traversal stack to be added to the current set. In the first example, the top stack contains the set resulting from .find("p"). In the second example, .addBack() adds the previous set of elements on the stack — in this case $("div.after-addback") — to the current set, selecting both the div and its enclosed paragraphs. +```html + + + + + addBack demo + + + + +​ +
+

Before addBack()

+
+

First Paragraph

+

Second Paragraph

+
+
+
+

After addBack()

+
+

First Paragraph

+

Second Paragraph

+
+
+​ + +​ + + +``` + */ + addBack(selector?: JQuery.Selector): this; + /** + * Adds the specified class(es) to each element in the set of matched elements. + * @param className_function _@param_ `className_function` + *
+ * * `className` — One or more space-separated classes to be added to the class attribute of each matched element.
+ * * `function` — A function returning one or more space-separated class names to be added to the existing class + * name(s). Receives the index position of the element in the set and the existing class name(s) as + * arguments. Within the function, `this` refers to the current element in the set. + * @see \`{@link https://api.jquery.com/addClass/ }\` + * @since 1.0 + * @since 1.4 + * @since 3.3 + * @example ​ ````Add the class "selected" to the matched elements. +```html + + + + + addClass demo + + + + +​ +

Hello

+

and

+

Goodbye

+​ + +​ + + +``` + * @example ​ ````Add the classes "selected" and "highlight" to the matched elements. +```html + + + + + addClass demo + + + + +​ +

Hello

+

and

+

Goodbye

+​ + +​ + + +``` + * @example ​ ````Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class. +```html + + + + + addClass demo + + + + +​ +
This div should be white
+
This div will be green because it now has the "green" and "red" classes. + It would be red if the addClass function failed.
+
This div should be white
+

There are zero green divs

+​ + +​ + + +``` + */ + addClass(className_function: JQuery.TypeOrArray | ((this: TElement, index: number, currentClassName: string) => string)): this; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or + * jQuery objects to insert after each element in the set of matched elements. + * @see \`{@link https://api.jquery.com/after/ }\` + * @since 1.0 + * @example ​ ````Inserts some HTML after all paragraphs. +```html + + + + + after demo + + + + +​ +

I would like to say:

+​ + +​ + + +``` + * @example ​ ````Inserts a DOM element after all paragraphs. +```html + + + + + after demo + + + + +​ +

I would like to say:

+​ + +​ + + +``` + * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs. +```html + + + + + after demo + + + + +​ +Hello +

I would like to say:

+​ + +​ + + +``` + */ + after(...contents: Array>>): this; + /** + * Insert content, specified by the parameter, after each element in the set of matched elements. + * @param function_functionーhtml _@param_ `function_functionーhtml` + *
+ * * `function` — A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert + * after each element in the set of matched elements. Receives the index position of the element in the + * set as an argument. Within the function, `this` refers to the current element in the set.
+ * * `functionーhtml` — A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert + * after each element in the set of matched elements. Receives the index position of the element in the + * set and the old HTML value of the element as arguments. Within the function, `this` refers to the + * current element in the set. + * @see \`{@link https://api.jquery.com/after/ }\` + * @since 1.4 + * @since 1.10 + */ + after(function_functionーhtml: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; + /** + * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. + * @param handler The function to be invoked. + * @see \`{@link https://api.jquery.com/ajaxComplete/ }\` + * @since 1.0 + * @example ​ ````Show a message when an Ajax request completes. +```javascript +$( document ).ajaxComplete(function( event, request, settings ) { + $( "#msg" ).append( "
  • Request Complete.
  • " ); +}); +``` + */ + 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. + * @see \`{@link https://api.jquery.com/ajaxError/ }\` + * @since 1.0 + * @example ​ ````Show a message when an Ajax request fails. +```javascript +$( document ).ajaxError(function( event, request, settings ) { + $( "#msg" ).append( "
  • Error requesting page " + settings.url + "
  • " ); +}); +``` + */ + 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. + * @see \`{@link https://api.jquery.com/ajaxSend/ }\` + * @since 1.0 + * @example ​ ````Show a message before an Ajax request is sent. +```javascript +$( document ).ajaxSend(function( event, request, settings ) { + $( "#msg" ).append( "
  • Starting request at " + settings.url + "
  • " ); +}); +``` + */ + 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. + * @see \`{@link https://api.jquery.com/ajaxStart/ }\` + * @since 1.0 + * @example ​ ````Show a loading message whenever an Ajax request starts (and none is already active). +```javascript +$( document ).ajaxStart(function() { + $( "#loading" ).show(); +}); +``` + */ + ajaxStart(handler: (this: Document) => void | false): this; + /** + * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. + * @param handler The function to be invoked. + * @see \`{@link https://api.jquery.com/ajaxStop/ }\` + * @since 1.0 + * @example ​ ````Hide a loading message after all the Ajax requests have stopped. +```javascript +$( document ).ajaxStop(function() { + $( "#loading" ).hide(); +}); +``` + */ + ajaxStop(handler: (this: Document) => void | false): this; + /** + * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. + * @param handler The function to be invoked. + * @see \`{@link https://api.jquery.com/ajaxSuccess/ }\` + * @since 1.0 + * @example ​ ````Show a message when an Ajax request completes successfully. +```javascript +$( document ).ajaxSuccess(function( event, request, settings ) { + $( "#msg" ).append( "
  • Successful Request!
  • " ); +}); +``` + */ + 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. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/animate/ }\` + * @since 1.0 + * @example ​ ````An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. +```javascript +$( "p" ).animate({ + opacity: "show" +}, "slow", "easein" ); +``` + * @example ​ ````Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. +```javascript +$( "p" ).animate({ + height: 200, + width: 400, + opacity: 0.5 +}, 1000, "linear", function() { + alert( "all done" ); +}); +``` + */ + animate(properties: JQuery.PlainObject, + duration: JQuery.Duration, + easing: string, + complete?: (this: TElement) => void): 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. + * @param duration_easing _@param_ `duration_easing` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/animate/ }\` + * @since 1.0 + * @example ​ ````Click the button to animate the div with a number of different properties. +```html + + + + + animate demo + + + + +​ + +
    Hello!
    +​ + +​ + + +``` + * @example ​ ````Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. +```html + + + + + animate demo + + + + +​ + + +
    +​ + +​ + + +``` + * @example ​ ````Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. +```javascript +$( "p" ).animate({ + height: "toggle", + opacity: "toggle" +}, "slow" ); +``` + * @example ​ ````Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. +```javascript +$( "p" ).animate({ + left: 50, + opacity: 1 +}, 500 ); +``` + */ + animate(properties: JQuery.PlainObject, + duration_easing: JQuery.Duration | string, + complete?: (this: TElement) => void): 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. + * @param options A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/animate/ }\` + * @since 1.0 + * @example ​ ````The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. + +The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed. +```html + + + + + animate demo + + + + +​ + + + + +
    Block1
    +
    Block2
    +​ + +​ + + +``` + * @example ​ ````Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. +```html + + + + + animate demo + + + + +​ +

    +
    +
    +
    +
    +
    +
    +​ + +​ + + +``` + * @example ​ ````Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. +```javascript +$( "p" ).animate({ + left: "50px", + opacity: 1 +}, { + duration: 500, + queue: false +}); +``` + * @example ​ ````Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. +```javascript +$( "p" ).animate({ + height: "toggle", + opacity: "toggle" +}, { + duration: "slow" +}); +``` + * @example ​ ````Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. +```javascript +$( "p" ).animate({ + opacity: "show" +}, { + duration: "slow", + easing: "easein" +}); +``` + */ + animate(properties: JQuery.PlainObject, + options: JQuery.EffectsOptions): 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. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/animate/ }\` + * @since 1.0 + */ + animate(properties: JQuery.PlainObject, + complete?: (this: TElement) => void): this; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or + * jQuery objects to insert at the end of each element in the set of matched elements. + * @see \`{@link https://api.jquery.com/append/ }\` + * @since 1.0 + * @example ​ ````Appends some HTML to all paragraphs. +```html + + + + + append demo + + + + +​ +

    I would like to say:

    +​ + +​ + + +``` + * @example ​ ````Appends an Element to all paragraphs. +```html + + + + + append demo + + + + +​ +

    I would like to say:

    +​ + +​ + + +``` + * @example ​ ````Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. +```html + + + + + append demo + + + + +​ +Hello world!!! +

    I would like to say:

    +​ + +​ + + +``` + */ + append(...contents: Array>>): this; + /** + * Insert content, specified by the parameter, to the end of each element in the set of matched elements. + * @param funсtion A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at + * the end of each element in the set of matched elements. Receives the index position of the element + * in the set and the old HTML value of the element as arguments. Within the function, `this` refers to + * the current element in the set. + * @see \`{@link https://api.jquery.com/append/ }\` + * @since 1.4 + */ + append(funсtion: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; + /** + * Insert every element in the set of matched elements to the end of the target. + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements + * will be inserted at the end of the element(s) specified by this parameter. + * @see \`{@link https://api.jquery.com/appendTo/ }\` + * @since 1.0 + * @example ​ ````Append all spans to the element with the ID "foo" (Check append() documentation for more examples) +```html + + + + + appendTo demo + + + + +​ +I have nothing more to say... +​ +
    FOO!
    +​ + +​ + + +``` + */ + appendTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + /** + * Set one or more attributes for the set of matched elements. + * @param attributeName The name of the attribute to set. + * @param value_function _@param_ `value_function` + *
    + * * `value` — A value to set for the attribute. If `null`, the specified attribute will be removed (as in \`{@link removeAttr .removeAttr()}`).
    + * * `function` — A function returning the value to set. `this` is the current element. Receives the index position of + * the element in the set and the old attribute value as arguments. + * @see \`{@link https://api.jquery.com/attr/ }\` + * @since 1.0 + * @since 1.1 + * @example ​ ````Set the id for divs based on the position in the page. +```html + + + + + attr demo + + + + +​ +
    Zero-th
    +
    First
    +
    Second
    +​ + +​ + + +``` + * @example ​ ````Set the src attribute from title attribute on the image. +```html + + + + + attr demo + + + +​ + +​ + +​ + + +``` + */ + attr(attributeName: string, + value_function: string | number | null | ((this: TElement, index: number, attr: string) => string | number | void | undefined)): this; + /** + * Set one or more attributes for the set of matched elements. + * @param attributes An object of attribute-value pairs to set. + * @see \`{@link https://api.jquery.com/attr/ }\` + * @since 1.0 + * @example ​ ````Set some attributes for all <img>s in the page. +```html + + + + + attr demo + + + + +​ + + + +​ +
    Attribute of Ajax
    +​ + +​ + + +``` + */ + attr(attributes: JQuery.PlainObject): this; + /** + * Get the value of an attribute for the first element in the set of matched elements. + * @param attributeName The name of the attribute to get. + * @see \`{@link https://api.jquery.com/attr/ }\` + * @since 1.0 + * @example ​ ````Display the checked attribute and property of a checkbox as it changes. +```html + + + + + attr demo + + + + +​ + + +

    +​ + +​ + + +``` + * @example ​ ````Find the title attribute of the first <em> in the page. +```html + + + + + attr demo + + + + +​ +

    Once there was a large dinosaur...

    +​ +The title of the emphasis is:
    +​ + +​ + + +``` + */ + attr(attributeName: string): string | undefined; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or + * jQuery objects to insert before each element in the set of matched elements. + * @see \`{@link https://api.jquery.com/before/ }\` + * @since 1.0 + * @example ​ ````Inserts some HTML before all paragraphs. +```html + + + + + before demo + + + + +​ +

    is what I said...

    +​ + +​ + + +``` + * @example ​ ````Inserts a DOM element before all paragraphs. +```html + + + + + before demo + + + + +​ +

    is what I said...

    +​ + +​ + + +``` + * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs. +```html + + + + + before demo + + + + +​ +

    is what I said...

    Hello +​ + +​ + + +``` + */ + before(...contents: Array>>): this; + /** + * Insert content, specified by the parameter, before each element in the set of matched elements. + * @param function_functionーhtml _@param_ `function_functionーhtml` + *
    + * * `function` — A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert + * before each element in the set of matched elements. Receives the index position of the element in + * the set as an argument. Within the function, `this` refers to the current element in the set.
    + * * `functionーhtml` — A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert + * before each element in the set of matched elements. Receives the index position of the element in + * the set and the old HTML value of the element as arguments. Within the function, `this` refers to the + * current element in the set. + * @see \`{@link https://api.jquery.com/before/ }\` + * @since 1.4 + * @since 1.10 + */ + before(function_functionーhtml: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; + // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 + /** + * 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. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/bind/ }\` + * @since 1.0 + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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: 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. + * @param handler_preventBubble _@param_ `handler_preventBubble` + *
    + * * `handler` — A function to execute each time the event is triggered.
    + * * `preventBubble` — Setting the third argument to false will attach a function that prevents the default action from + * occurring and stops the event from bubbling. The default is `true`. + * @see \`{@link https://api.jquery.com/bind/ }\` + * @since 1.0 + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe. +```html + + + + + bind demo + + + + +​ +

    Click or double click here.

    + +​ + +​ + + +``` + * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: +```javascript +$( "p" ).bind( "click", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Cancel a default action and prevent it from bubbling up by returning false: +```javascript +$( "form" ).bind( "submit", function() { + return false; +}) +``` + * @example ​ ````Cancel only the default action by using the .preventDefault() method. +```javascript +$( "form" ).bind( "submit", function( event ) { + event.preventDefault(); +}); +``` + * @example ​ ````Stop an event from bubbling without preventing the default action by using the .stopPropagation() method. +```javascript +$( "form" ).bind( "submit", function( event ) { + event.stopPropagation(); +}); +``` + * @example ​ ````Bind custom events. +```html + + + + + bind demo + + + + +​ +

    Has an attached custom event.

    + + +​ + +​ + + +``` + */ + 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. + * @see \`{@link https://api.jquery.com/bind/ }\` + * @since 1.4 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````Bind multiple events simultaneously. +```javascript +$( "div.test" ).bind({ + click: function() { + $( this ).addClass( "active" ); + }, + mouseenter: function() { + $( this ).addClass( "inside" ); + }, + mouseleave: function() { + $( this ).removeClass( "inside" ); + } +}); +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/blur/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + blur(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/blur/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To trigger the blur event on all paragraphs: +```javascript +$( "p" ).blur(); +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/change/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + change(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/change/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw. +```html + + + + + change demo + + + + +​ + +
    +​ + +​ + + +``` + * @example ​ ````To add a validity test to all text input elements: +```javascript +$( "input[type='text']" ).change(function() { + // Check input( $( this ).val() ) for validity here +}); +``` + */ + 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. + * @see \`{@link https://api.jquery.com/children/ }\` + * @since 1.0 + * @example ​ ````Find all children of the clicked element. +```html + + + + + children demo + + + + +​ +
    +
    +

    This is the way we + write the demo,

    +
    +​ +
    + write the demo, demo, +
    +​ +
    + This the way we write the demo so + in +
    +​ +

    + the morning. + Found 0 children in TAG. +

    +
    +​ + +​ + + +``` + * @example ​ ````Find all children of each div. +```html + + + + + children demo + + + + +​ +

    Hello (this is a paragraph)

    +​ +
    Hello Again (this span is a child of the a div)
    +

    And Again (in another paragraph)

    +​ +
    And One Last Time (most text directly in a div)
    +​ + +​ + + +``` + * @example ​ ````Find all children with a class "selected" of each div. +```html + + + + + children demo + + + + +​ +
    + Hello +

    Hello Again

    +
    And Again
    +

    And One Last Time

    +
    +​ + +​ + + +``` + */ + children(selector?: JQuery.Selector): this; + /** + * Remove from the queue all items that have not yet been run. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @see \`{@link https://api.jquery.com/clearQueue/ }\` + * @since 1.4 + * @example ​ ````Empty the queue. +```html + + + + + clearQueue demo + + + + +​ + + +
    +​ + +​ + + +``` + */ + clearQueue(queueName?: string): this; + /** + * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/click/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + click(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/click/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Hide paragraphs on a page when they are clicked: +```html + + + + + click demo + + + + +​ +

    First Paragraph

    +

    Second Paragraph

    +

    Yet one more Paragraph

    +​ + +​ + + +``` + * @example ​ ````Trigger the click event on all of the paragraphs on the page: +```javascript +$( "p" ).click(); +``` + */ + 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 + * default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back + * to false in 1.5.1 and up. + * @param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should + * be copied. By default its value matches the first argument's value (which defaults to false). + * @see \`{@link https://api.jquery.com/clone/ }\` + * @since 1.0 + * @since 1.5 + * @example ​ ````Clones all b elements (and selects the clones) and prepends them to all paragraphs. +```html + + + + + clone demo + + + +​ +Hello

    , how are you?

    +​ + +​ + + +``` + */ + clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): this; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param selector A string containing a selector expression to match elements against. + * @param context A DOM element within which a matching element may be found. + * @see \`{@link https://api.jquery.com/closest/ }\` + * @since 1.4 + */ + closest(selector: JQuery.Selector, context: Element): this; + /** + * For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree. + * @param selector_selection_element _@param_ `selector_selection_element` + *
    + * * `selector` — A string containing a selector expression to match elements against.
    + * * `selection` — A jQuery object to match elements against.
    + * * `element` — An element to match elements against. + * @see \`{@link https://api.jquery.com/closest/ }\` + * @since 1.3 + * @since 1.6 + * @example ​ ````Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked. +```html + + + + + closest demo + + + + +​ +
      +
    • Click me!
    • +
    • You can also Click me!
    • +
    +​ + +​ + + +``` + * @example ​ ````Pass a jQuery object to closest. The closest list element toggles a yellow background when it or its descendent is clicked. +```html + + + + + closest demo + + + + +​ +
      +
    • Click me!
    • +
    • You can also Click me!
    • +
    +​ + +​ + + +``` + */ + closest(selector_selection_element: JQuery.Selector | Element | JQuery): this; + /** + * Get the children of each element in the set of matched elements, including text and comment nodes. + * @see \`{@link https://api.jquery.com/contents/ }\` + * @since 1.2 + * @example ​ ````Find all the text nodes inside a paragraph and wrap them with a bold tag. +```html + + + + + contents demo + + + +​ +

    Hello John, how are you doing?

    +​ + +​ + + +``` + * @example ​ ````Change the background color of links inside of an iframe. +```html + + + + + contents demo + + + +​ + +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/contextmenu/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + contextmenu(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/contextmenu/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page: +```javascript +$( "p" ).contextmenu(function() { + alert( "Hello World!" ); +}); +``` + * @example ​ ````Right click to toggle background color. +```html + + + + + contextmenu demo + + + + +​ +
    +Right click the block +​ + +​ + + +``` + */ + contextmenu(handler?: JQuery.TypeEventHandler | + false): this; + /** + * Set one or more CSS properties for the set of matched elements. + * @param propertyName A CSS property name. + * @param value_function _@param_ `value_function` + *
    + * * `value` — A value to set for the property.
    + * * `function` — A function returning the value to set. `this` is the current element. Receives the index position of + * the element in the set and the old value as arguments. + * @see \`{@link https://api.jquery.com/css/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Change the color of any paragraph to red on mouseover event. +```html + + + + + css demo + + + + +​ +

    Just roll the mouse over me.

    +​ +

    Or me to see a color change.

    +​ + +​ + + +``` + * @example ​ ````Increase the width of #box by 200 pixels the first time it is clicked. +```html + + + + + css demo + + + + +​ +
    Click me to grow
    +​ + +​ + + +``` + * @example ​ ````Highlight a clicked word in the paragraph. +```html + + + + + css demo + + + + +​ +

    + Once upon a time there was a man + who lived in a pizza parlor. This + man just loved pizza and ate it all + the time. He went on to be the + happiest man in the world. The end. +

    +​ + +​ + + +``` + */ + css(propertyName: string, + value_function: string | number | ((this: TElement, index: number, value: string) => string | number | void | undefined)): this; + /** + * Set one or more CSS properties for the set of matched elements. + * @param properties An object of property-value pairs to set. + * @see \`{@link https://api.jquery.com/css/ }\` + * @since 1.0 + * @example ​ ````Change the font weight and background color on mouseenter and mouseleave. +```html + + + + + css demo + + + + +​ +

    Move the mouse over a paragraph.

    +

    Like this one or the one above.

    +​ + +​ + + +``` + * @example ​ ````Increase the size of a div when you click it. +```html + + + + + css demo + + + + +​ +
    click
    +
    click
    +​ + +​ + + +``` + */ + css(properties: JQuery.PlainObject string | number | void | undefined)>): this; + /** + * Get the computed style properties for the first element in the set of matched elements. + * @param propertyName A CSS property. + * @see \`{@link https://api.jquery.com/css/ }\` + * @since 1.0 + * @example ​ ````Get the background color of a clicked div. +```html + + + + + css demo + + + + +​ +  +
    +
    +
    +
    +​ + +​ + + +``` + */ + css(propertyName: string): string; + /** + * Get the computed style properties for the first element in the set of matched elements. + * @param propertyNames An array of one or more CSS properties. + * @see \`{@link https://api.jquery.com/css/ }\` + * @since 1.9 + * @example ​ ````Get the width, height, text color, and background color of a clicked div. +```html + + + + + css demo + + + + +​ +

     

    +
    1
    +
    2
    +
    3
    +
    4
    +​ + +​ + + +``` + */ + css(propertyNames: string[]): JQuery.PlainObject; + /** + * Store arbitrary data associated with the matched elements. + * @param key A string naming the piece of data to set. + * @param value The new data value; this can be any Javascript type except `undefined`. + * @see \`{@link https://api.jquery.com/data/ }\` + * @since 1.2.3 + * @example ​ ````Store then retrieve a value from the div element. +```html + + + + + data demo + + + + +​ +
    + The values stored were + + and + +
    +​ + +​ + + +``` + */ + data(key: string, value: string | number | boolean | symbol | object | null): this; + /** + * Store arbitrary data associated with the matched elements. + * @param obj An object of key-value pairs of data to update. + * @see \`{@link https://api.jquery.com/data/ }\` + * @since 1.4.3 + */ + data(obj: JQuery.PlainObject): this; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * @param key Name of the data stored. + * @param value `undefined` is not recognized as a data value. Calls such as `.data( "name", undefined )` + * will return the jQuery object that it was called on, allowing for chaining. + * @see \`{@link https://api.jquery.com/data/ }\` + * @since 1.2.3 + */ + // `unified-signatures` is disabled so that behavior when passing `undefined` to `value` can be documented. Unifying the signatures + // results in potential confusion for users from an unexpected parameter. + // tslint:disable-next-line:unified-signatures + data(key: string, value: undefined): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * @param key Name of the data stored. + * @see \`{@link https://api.jquery.com/data/ }\` + * @since 1.2.3 + * @example ​ ````Get the data named "blah" stored at for an element. +```html + + + + + data demo + + + + +​ +
    A div
    + + + + +

    The "blah" value of this div is ?

    +​ + +​ + + +``` + */ + data(key: string): any; + /** + * Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute. + * @see \`{@link https://api.jquery.com/data/ }\` + * @since 1.4 + */ + data(): JQuery.PlainObject; + /** + * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/dblclick/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + dblclick(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/dblclick/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To bind a "Hello World!" alert box to the dblclick event on every paragraph on the page: +```javascript +$( "p" ).dblclick(function() { + alert( "Hello World!" ); +}); +``` + * @example ​ ````Double click to toggle background color. +```html + + + + + dblclick demo + + + + +​ +
    +Double click the block +​ + +​ + + +``` + */ + 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. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @see \`{@link https://api.jquery.com/delay/ }\` + * @since 1.4 + * @example ​ ````Animate the hiding and showing of two divs, delaying the first before showing it. +```html + + + + + delay demo + + + + +​ +

    +
    +
    +​ + +​ + + +``` + */ + delay(duration: JQuery.Duration, queueName?: string): 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. + * @param eventType A string containing one or more space-separated JavaScript event types, such as "click" or + * "keydown," or custom event names. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/delegate/ }\` + * @since 1.4.2 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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: 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. + * @param eventType A string containing one or more space-separated JavaScript event types, such as "click" or + * "keydown," or custom event names. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/delegate/ }\` + * @since 1.4.2 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones. +```html + + + + + delegate demo + + + + +​ +

    Click me!

    +​ + +​ + +​ + + +``` + * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: +```javascript +$( "body" ).delegate( "p", "click", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````To cancel a default action and prevent it from bubbling up, return false: +```javascript +$( "body" ).delegate( "a", "click", function() { + return false; +}); +``` + * @example ​ ````To cancel only the default action by using the preventDefault method. +```javascript +$( "body" ).delegate( "a", "click", function( event ) { + event.preventDefault(); +}); +``` + * @example ​ ````Can bind custom events too. +```html + + + + + delegate demo + + + + +​ +

    Has an attached custom event.

    + + +​ + +​ + + +``` + */ + 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. + * @param events A plain object of one or more event types and functions to execute for them. + * @see \`{@link https://api.jquery.com/delegate/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.0. Use \`{@link on }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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.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. + * @see \`{@link https://api.jquery.com/dequeue/ }\` + * @since 1.2 + * @example ​ ````Use dequeue to end a custom queue function which allows the queue to keep going. +```html + + + + + dequeue demo + + + + +​ + +
    +​ + +​ + + +``` + */ + dequeue(queueName?: string): this; + /** + * Remove the set of matched elements from the DOM. + * @param selector A selector expression that filters the set of matched elements to be removed. + * @see \`{@link https://api.jquery.com/detach/ }\` + * @since 1.4 + * @example ​ ````Detach all paragraphs from the DOM +```html + + + + + detach demo + + + + +​ +

    Hello

    +how are +

    you?

    + +​ + +​ + + +``` + */ + detach(selector?: JQuery.Selector): this; + /** + * Iterate over a jQuery object, executing a function for each matched element. + * @param funсtion A function to execute for each matched element. + * @see \`{@link https://api.jquery.com/each/ }\` + * @since 1.0 + * @example ​ ````Iterate over three divs and sets their color property. +```html + + + + + each demo + + + + +​ +
    Click here
    +
    to iterate through
    +
    these divs.
    +​ + +​ + + +``` + * @example ​ ````To access a jQuery object instead of the regular DOM element, use $( this ). For example: +```html + + + + + each demo + + + + +​ +To do list: (click here to change) +
      +
    • Eat
    • +
    • Sleep
    • +
    • Be merry
    • +
    +​ + +​ + + +``` + * @example ​ ````Use return false to break out of each() loops early. +```html + + + + + each demo + + + + +​ + + +
    +
    +
    +
    +
    Stop here
    +
    +
    +
    +​ + +​ + + +``` + */ + each(funсtion: (this: TElement, index: number, element: TElement) => void | false): this; + /** + * Remove all child nodes of the set of matched elements from the DOM. + * @see \`{@link https://api.jquery.com/empty/ }\` + * @since 1.0 + * @example ​ ````Removes all child nodes (including text nodes) from all paragraphs +```html + + + + + empty demo + + + + +​ +

    + Hello, Person and person. +

    +​ + +​ + +​ + + +``` + */ + empty(): this; + /** + * End the most recent filtering operation in the current chain and return the set of matched elements to its previous state. + * @see \`{@link https://api.jquery.com/end/ }\` + * @since 1.0 + * @example ​ ````Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. +```html + + + + + end demo + + + + +​ +

    + Hi there how are you doing? +

    +​ +

    + This span is one of + several spans in this + sentence. +

    +​ +
    + Tags in jQuery object initially: +
    +​ +
    + Tags in jQuery object after find: +
    +​ +
    + Tags in jQuery object after end: +
    +​ + +​ + + +``` + * @example ​ ````Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. +```html + + + + + end demo + + + + +​ +

    Hello, how are you?

    +​ + +​ + + +``` + */ + end(): this; + /** + * Reduce the set of matched elements to the one at the specified index. + * @param index An integer indicating the 0-based position of the element. + * An integer indicating the position of the element, counting backwards from the last element in the set. + * @see \`{@link https://api.jquery.com/eq/ }\` + * @since 1.1.2 + * @since 1.4 + * @example ​ ````Turn the div with index 2 blue by adding an appropriate class. +```html + + + + + eq demo + + + + +​ +
    +
    +
    +
    +
    +
    +​ + +​ + + +``` + */ + eq(index: number): this; + /** + * Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. + * @param obj An object to merge onto the jQuery prototype. + * @see \`{@link https://api.jquery.com/jQuery.fn.extend/ }\` + * @since 1.0 + * @example ​ ````Add two methods to the jQuery prototype ($.fn) object and then use one of them. +```html + + + + + jQuery.fn.extend demo + + + + +​ + + +​ + +​ + + +``` + */ + extend(obj: object): this; + /** + * Display the matched elements by fading them to opaque. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeIn/ }\` + * @since 1.4.3 + */ + fadeIn(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Display the matched elements by fading them to opaque. + * @param duration_easing _@param_ `duration_easing` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeIn/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top. +```html + + + + + fadeIn demo + + + + +​ +

    + Let it be known that the party of the first part + and the party of the second part are henceforth + and hereto directed to assess the allegations + for factual correctness... (click!) +

    CENSORED!
    +

    +​ + +​ + + +``` + */ + fadeIn(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Display the matched elements by fading them to opaque. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition.
    + * * `complete` — A function to call once the animation is complete, called once per matched element.
    + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/fadeIn/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds. +```html + + + + + fadeIn demo + + + + +​ +Click here... +
    +
    +
    +​ + +​ + + +``` + */ + fadeIn(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Hide the matched elements by fading them to transparent. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeOut/ }\` + * @since 1.4.3 + * @example ​ ````Fades out two divs, one with a "linear" easing and one with the default, "swing," easing. +```html + + + + + fadeOut demo + + + + +​ + + +​ +
    +​ +
    linear
    +
    swing
    +​ + +​ + + +``` + */ + fadeOut(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Hide the matched elements by fading them to transparent. + * @param duration_easing _@param_ `duration_easing` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeOut/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Fades out spans in one section that you click on. +```html + + + + + fadeOut demo + + + + +​ +

    Find the modifiers -

    +

    + If you really want to go outside + in the cold then make sure to wear + your warm jacket given to you by + your favorite teacher. +

    +​ + +​ + + +``` + */ + fadeOut(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Hide the matched elements by fading them to transparent. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition.
    + * * `complete` — A function to call once the animation is complete, called once per matched element.
    + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/fadeOut/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all paragraphs to fade out, completing the animation within 600 milliseconds. +```html + + + + + fadeOut demo + + + + +​ +

    + If you click on this paragraph + you'll see it just fade away. +

    +​ + +​ + + +``` + */ + fadeOut(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Adjust the opacity of the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeTo/ }\` + * @since 1.4.3 + */ + fadeTo(duration: JQuery.Duration, opacity: number, easing: string, complete?: (this: TElement) => void): this; + /** + * Adjust the opacity of the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param opacity A number between 0 and 1 denoting the target opacity. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeTo/ }\` + * @since 1.0 + * @example ​ ````Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds. +```html + + + + + fadeTo demo + + + +​ +

    +Click this paragraph to see it fade. +

    +​ +

    +Compare to this one that won't fade. +

    +​ + +​ + + +``` + * @example ​ ````Fade div to a random opacity on each click, completing the animation within 200 milliseconds. +```html + + + + + fadeTo demo + + + + +​ +

    And this is the library that John built...

    +​ +
    +
    +
    +​ + +​ + + +``` + * @example ​ ````Find the right answer! The fade will take 250 milliseconds and change various styles when it completes. +```html + + + + + fadeTo demo + + + + +​ +

    Wrong

    +
    +

    Wrong

    +
    +

    Right!

    +
    +​ + +​ + + +``` + */ + fadeTo(duration: JQuery.Duration, opacity: number, complete?: (this: TElement) => void): this; + /** + * Display or hide the matched elements by animating their opacity. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` + * @since 1.4.4 + * @example ​ ````Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. +```html + + + + + fadeToggle demo + + + +​ + + +

    This paragraph has a slow, linear fade.

    +

    This paragraph has a fast animation.

    +
    +​ + +​ + + +``` + */ + fadeToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Display or hide the matched elements by animating their opacity. + * @param duration_easing _@param_ `duration_easing` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. +```html + + + + + fadeToggle demo + + + +​ + + +

    This paragraph has a slow, linear fade.

    +

    This paragraph has a fast animation.

    +
    +​ + +​ + + +``` + */ + fadeToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Display or hide the matched elements by animating their opacity. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `easing` — A string indicating which easing function to use for the transition.
    + * * `complete` — A function to call once the animation is complete, called once per matched element.
    + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/fadeToggle/ }\` + * @since 1.0 + * @since 1.4.3 + */ + fadeToggle(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Reduce the set of matched elements to those that match the selector or pass the function's test. + * @param selector_elements_selection_function _@param_ `selector_elements_selection_function` + *
    + * * `selector` — A string containing a selector expression to match the current set of elements against.
    + * * `elements` — One or more DOM elements to match the current set of elements against.
    + * * `selection` — An existing jQuery object to match the current set of elements against.
    + * * `function` — A function used as a test for each element in the set. this is the current DOM element. + * @see \`{@link https://api.jquery.com/filter/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Change the color of all divs; then add a border to those with a "middle" class. +```html + + + + + filter demo + + + + +​ +
    +
    +
    +
    +
    +
    +​ + +​ + + +``` + * @example ​ ````Change the color of all divs; then add a border to the second one (index == 1) and the div with an id of "fourth." +```html + + + + + filter demo + + + + +​ +
    +
    +
    +
    +
    +
    +​ + +​ + + +``` + * @example ​ ````Select all divs and filter the selection with a DOM element, keeping only the one with an id of "unique". +```javascript +$( "div" ).filter( document.getElementById( "unique" ) ); +``` + * @example ​ ````Select all divs and filter the selection with a jQuery object, keeping only the one with an id of "unique". +```javascript +$( "div" ).filter( $( "#unique" ) ); +``` + */ + filter(selector_elements_selection_function: + JQuery.Selector | + JQuery.TypeOrArray | + JQuery | + ((this: TElement, index: number, element: TElement) => boolean) + ): this; + /** + * Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element. + * @param selector_element _@param_ `selector_element` + *
    + * * `selector` — A string containing a selector expression to match elements against.
    + * * `element` — An element or a jQuery object to match elements against. + * @see \`{@link https://api.jquery.com/find/ }\` + * @since 1.0 + * @since 1.6 + * @example ​ ````Starts with all paragraphs and searches for descendant span elements, same as $( "p span" ) +```html + + + + + find demo + + + +​ +

    Hello, how are you?

    +

    Me? I'm good.

    +​ + +​ + + +``` + * @example ​ ````A selection using a jQuery collection of all span tags. Only spans within p tags are changed to red while others are left blue. +```html + + + + + find demo + + + + +​ +

    Hello, how are you?

    +

    Me? I'm good.

    +
    Did you eat yet?
    +​ + +​ + + +``` + * @example ​ ````Add spans around each word then add a hover and italicize words with the letter t. +```html + + + + + find demo + + + + +​ +

    + When the day is short + find that which matters to you + or stop believing +

    +​ + +​ + + +``` + */ + find(selector_element: JQuery.Selector | Element | JQuery): this; + /** + * Stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements. + * @param queue The name of the queue in which to stop animations. + * @see \`{@link https://api.jquery.com/finish/ }\` + * @since 1.9 + * @example ​ ````Click the Go button once to start the animation, and then click the other buttons to see how they affect the current and queued animations. +```html + + + + + finish demo + + + + +​ +
    +
    + +
    + + +
    + + +
    + + +
    + +
    + +
    +​ + +​ + + +``` + */ + finish(queue?: string): this; + /** + * Reduce the set of matched elements to the first in the set. + * @see \`{@link https://api.jquery.com/first/ }\` + * @since 1.4 + * @example ​ ````Highlight the first span in a paragraph. +```html + + + + + first demo + + + + +​ +

    + Look: + This is some text in a paragraph. + This is a note about it. +

    +​ + +​ + + +``` + */ + first(): this; + /** + * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/focus/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + focus(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/focus/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Fire focus. +```html + + + + + focus demo + + + + +​ +

    focus fire

    +

    focus fire

    +​ + +​ + + +``` + * @example ​ ````To stop people from writing in text input boxes, try: +```javascript +$( "input[type=text]" ).focus(function() { + $( this ).blur(); +}); +``` + * @example ​ ````To focus on a login input box with id 'login' on page startup, try: +```javascript +$( document ).ready(function() { + $( "#login" ).focus(); +}); +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/focusin/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + focusin(eventData: TData, + handler: JQuery.TypeEventHandler): this; + /** + * Bind an event handler to the "focusin" event. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/focusin/ }\` + * @since 1.4 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Watch for a focus to occur within the paragraphs on the page. +```html + + + + + focusin demo + + + + +​ +

    focusin fire

    +

    focusin fire

    +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/focusout/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + focusout(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/focusout/ }\` + * @since 1.4 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Watch for a loss of focus to occur inside paragraphs and note the difference between the focusout count and the blur count. (The blur count does not change because those events do not bubble.) +```html + + + + + focusout demo + + + + +​ +
    +

    +
    + +

    +

    + +

    +
    +
    focusout fire
    +
    blur fire
    +​ + +​ + + +``` + */ + 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. + * @see \`{@link https://api.jquery.com/get/ }\` + * @since 1.0 + * @example ​ ````Display the tag name of the click element. +```html + + + + + get demo + + + + +​ +  +

    In this paragraph is an important section

    +
    +​ + +​ + + +``` + */ + get(index: number): TElement; + /** + * Retrieve the elements matched by the jQuery object. + * @see \`{@link https://api.jquery.com/get/ }\` + * @since 1.0 + * @example ​ ````Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. +```html + + + + + get demo + + + + +​ +Reversed - +​ +
    One
    +
    Two
    +
    Three
    +​ + +​ + + +``` + */ + get(): TElement[]; + /** + * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. + * @param selector_contained _@param_ `selector_contained` + *
    + * * `selector` — A string containing a selector expression to match elements against.
    + * * `contained` — A DOM element to match elements against. + * @see \`{@link https://api.jquery.com/has/ }\` + * @since 1.4 + * @example ​ ````Check if an element is inside another. +```html + + + + + has demo + + + + +​ +
    • Does the UL contain an LI?
    +​ + +​ + + +``` + */ + has(selector_contained: string | Element): this; + /** + * Determine whether any of the matched elements are assigned the given class. + * @param className The class name to search for. + * @see \`{@link https://api.jquery.com/hasClass/ }\` + * @since 1.2 + * @example ​ ````Looks for the paragraph that contains 'selected' as a class. +```html + + + + + hasClass demo + + + + +​ +

    This paragraph is black and is the first paragraph.

    +

    This paragraph is red and is the second paragraph.

    +
    First paragraph has selected class:
    +
    Second paragraph has selected class:
    +
    At least one paragraph has selected class:
    +​ + +​ + + +``` + */ + hasClass(className: string): boolean; + /** + * Set the CSS height of every matched element. + * @param value_function _@param_ `value_function` + *
    + * * `value` — An integer representing the number of pixels, or an integer with an optional unit of measure + * appended (as a string).
    + * * `function` — A function returning the height to set. Receives the index position of the element in the set and + * the old height as arguments. Within the function, `this` refers to the current element in the set. + * @see \`{@link https://api.jquery.com/height/ }\` + * @since 1.0 + * @since 1.4.1 + * @example ​ ````To set the height of each div on click to 30px plus a color change. +```html + + + + + height demo + + + + +​ +
    +
    +
    +
    +
    +​ + +​ + + +``` + */ + height(value_function: string | number | ((this: TElement, index: number, height: number) => string | number)): this; + /** + * Get the current computed height for the first element in the set of matched elements. + * @see \`{@link https://api.jquery.com/height/ }\` + * @since 1.0 + * @example ​ ````Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. +```html + + + + + height demo + + + + +​ + + + +​ +
     
    +

    + Sample paragraph to test height +

    +​ + +​ + + +``` + */ + height(): number | undefined; + /** + * Hide the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/hide/ }\` + * @since 1.4.3 + */ + hide(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; + /** + * Hide the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param easing_complete _@param_ `easing_complete` + *
    + * * `easing` — A string indicating which easing function to use for the transition.
    + * * `complete` — A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/hide/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one. +```html + + + + + hide demo + + + + +​ + + +
    + Once upon a + time there were + three programmers... +
    +​ + +​ + + +``` + * @example ​ ````Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time. +```html + + + + + hide demo + + + + +​ +
    +​ + +​ + + +``` + */ + hide(duration: JQuery.Duration, easing_complete: string | ((this: TElement) => void)): this; + /** + * Hide the matched elements. + * @param duration_complete_options _@param_ `duration_complete_options` + *
    + * * `duration` — A string or number determining how long the animation will run.
    + * * `complete` — A function to call once the animation is complete, called once per matched element.
    + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/hide/ }\` + * @since 1.0 + * @example ​ ````Hides all paragraphs then the link on click. +```html + + + + + hide demo + + + +​ +

    Hello

    +Click to hide me too +

    Here is another paragraph

    +​ + +​ + + +``` + * @example ​ ````Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds. +```html + + + + + hide demo + + + + +​ + +

    Hiya

    +

    Such interesting text, eh?

    +​ + +​ + + +``` + */ + hide(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * 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 + * @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 ​ ````To add a special style to list items that are being hovered over, try: +```html + + + + + hover demo + + + + +​ +
      +
    • Milk
    • +
    • Bread
    • +
    • Chips
    • +
    • Socks
    • +
    +​ + +​ + + +``` + * @example ​ ````To add a special style to table cells that are being hovered over, try: +```javascript +$( "td" ).hover( + function() { + $( this ).addClass( "hover" ); + }, function() { + $( this ).removeClass( "hover" ); + } +); +``` + * @example ​ ````To unbind the above example use: +```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 + + + + + hover demo + + + + +​ +
      +
    • Milk
    • +
    • White
    • +
    • Carrots
    • +
    • Orange
    • +
    • Broccoli
    • +
    • Green
    • +
    +​ + +​ + + +``` + */ + 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` + *
    + * * `htmlString` — A string of HTML to set as the content of each matched element.
    + * * `function` — A function returning the HTML content to set. Receives the index position of the element in the set + * and the old HTML value as arguments. jQuery empties the element before calling the function; use the + * oldhtml argument to reference the previous content. Within the function, `this` refers to the current + * element in the set. + * @see \`{@link https://api.jquery.com/html/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Add some html to each div. +```html + + + + + html demo + + + + +​ +Hello +
    +
    +
    +​ + +​ + + +``` + * @example ​ ````Add some html to each div then immediately do further manipulations to the inserted html. +```html + + + + + html demo + + + + +​ +
    +
    +
    +​ + +​ + + +``` + */ + html(htmlString_function: JQuery.htmlString | ((this: TElement, index: number, oldhtml: JQuery.htmlString) => JQuery.htmlString)): this; + /** + * Get the HTML contents of the first element in the set of matched elements. + * @see \`{@link https://api.jquery.com/html/ }\` + * @since 1.0 + * @example ​ ````Click a paragraph to convert it from html to text. +```html + + + + + html demo + + + + +​ +

    + Click to change the html +

    +

    + to a text node. +

    +

    + This does nothing. +

    +​ + +​ + + +``` + */ + html(): string; + /** + * Search for a given element from among the matched elements. + * @param selector_element _@param_ `selector_element` + *
    + * * `selector` — A selector representing a jQuery collection in which to look for an element.
    + * * `element` — The DOM element or first element within the jQuery object to look for. + * @see \`{@link https://api.jquery.com/index/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````On click, returns the index (zero-based) of that div in the page. +```html + + + + + index demo + + + + +​ +Click a div! +
    First div
    +
    Second div
    +
    Third div
    +​ + +​ + + +``` + * @example ​ ````Returns the index for the element with ID bar. +```html + + + + + index demo + + + + +​ +
      +
    • foo
    • +
    • bar
    • +
    • baz
    • +
    +
    +​ + +​ + + +``` + * @example ​ ````Returns the index for the first item in the jQuery collection. +```html + + + + + index demo + + + + +​ +
      +
    • foo
    • +
    • bar
    • +
    • baz
    • +
    +
    +​ + +​ + + +``` + * @example ​ ````Returns the index for the element with ID bar in relation to all <li> elements. +```html + + + + + index demo + + + + +​ +
      +
    • foo
    • +
    • bar
    • +
    • baz
    • +
    +
    +​ + +​ + + +``` + * @example ​ ````Returns the index for the element with ID bar in relation to its siblings. +```html + + + + + index demo + + + + +​ +
      +
    • foo
    • +
    • bar
    • +
    • baz
    • +
    +
    +​ + +​ + + +``` + * @example ​ ````Returns -1, as there is no element with ID foobar. +```html + + + + + index demo + + + + +​ +
      +
    • foo
    • +
    • bar
    • +
    • baz
    • +
    +
    +​ + +​ + + +``` + */ + index(selector_element?: JQuery.Selector | Element | JQuery): number; + /** + * Set the CSS inner height of each element in the set of matched elements. + * @param value_function _@param_ `value_function` + *
    + * * `value` — A number representing the number of pixels, or a number along with an optional unit of measure + * appended (as a string).
    + * * `function` — A function returning the inner height (including padding but not border) to set. Receives the index + * position of the element in the set and the old inner height as arguments. Within the function, `this` + * refers to the current element in the set. + * @see \`{@link https://api.jquery.com/innerHeight/ }\` + * @since 1.8.0 + * @example ​ ````Change the inner height of each div the first time it is clicked (and change its color). +```html + + + + + innerHeight demo + + + + +​ +
    d
    +
    d
    +
    d
    +
    d
    +
    d
    +​ + +​ + + +``` + */ + innerHeight(value_function: string | number | ((this: TElement, index: number, height: number) => string | number)): this; + /** + * Get the current computed height for the first element in the set of matched elements, including padding but not border. + * @see \`{@link https://api.jquery.com/innerHeight/ }\` + * @since 1.2.6 + * @example ​ ````Get the innerHeight of a paragraph. +```html + + + + + innerHeight demo + + + + +​ +

    Hello

    +

    +​ + +​ + + +``` + */ + innerHeight(): number | undefined; + /** + * Set the CSS inner width of each element in the set of matched elements. + * @param value_function _@param_ `value_function` + *
    + * * `value` — A number representing the number of pixels, or a number along with an optional unit of measure + * appended (as a string).
    + * * `function` — A function returning the inner width (including padding but not border) to set. Receives the index + * position of the element in the set and the old inner width as arguments. Within the function, `this` + * refers to the current element in the set. + * @see \`{@link https://api.jquery.com/innerWidth/ }\` + * @since 1.8.0 + * @example ​ ````Change the inner width of each div the first time it is clicked (and change its color). +```html + + + + + innerWidth demo + + + + +​ +
    d
    +
    d
    +
    d
    +
    d
    +
    d
    +​ + +​ + + +``` + */ + innerWidth(value_function: string | number | ((this: TElement, index: number, width: number) => string | number)): this; + /** + * Get the current computed inner width for the first element in the set of matched elements, including padding but not border. + * @see \`{@link https://api.jquery.com/innerWidth/ }\` + * @since 1.2.6 + * @example ​ ````Get the innerWidth of a paragraph. +```html + + + + + innerWidth demo + + + + +​ +

    Hello

    +

    +​ + +​ + + +``` + */ + innerWidth(): number | undefined; + /** + * Insert every element in the set of matched elements after the target. + * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements + * will be inserted after the element(s) specified by this parameter. + * @see \`{@link https://api.jquery.com/insertAfter/ }\` + * @since 1.0 + * @example ​ ````Insert all paragraphs after an element with id of "foo". Same as $( "#foo" ).after( "p" ) +```html + + + + + insertAfter demo + + + + +​ +

    is what I said...

    +
    FOO!
    +​ + +​ + + +``` + */ + insertAfter(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + /** + * Insert every element in the set of matched elements before the target. + * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements + * will be inserted before the element(s) specified by this parameter. + * @see \`{@link https://api.jquery.com/insertBefore/ }\` + * @since 1.0 + * @example ​ ````Insert all paragraphs before an element with id of "foo". Same as $( "#foo" ).before( "p" ) +```html + + + + + insertBefore demo + + + + +​ +
    FOO!
    +

    I would like to say:

    +​ + +​ + + +``` + */ + insertBefore(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + /** + * Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments. + * @param selector_function_selection_elements _@param_ `selector_function_selection_elements` + *
    + * * `selector` — A string containing a selector expression to match elements against.
    + * * `function` — A function used as a test for every element in the set. It accepts two arguments, `index`, which is + * the element's index in the jQuery collection, and `element`, which is the DOM element. Within the + * function, `this` refers to the current DOM element.
    + * * `selection` — An existing jQuery object to match the current set of elements against.
    + * * `elements` — One or more elements to match the current set of elements against. + * @see \`{@link https://api.jquery.com/is/ }\` + * @since 1.0 + * @since 1.6 + * @example ​ ````Shows a few ways is() can be used inside an event handler. +```html + + + + + is demo + + + + +​ +
    +
    +
    +
    +

    Peter
    +
    +

     

    +​ + +​ + + +``` + * @example ​ ````Returns true, because the parent of the input is a form element. +```html + + + + + is demo + + + + +​ +
    + +
    +
    +​ + +​ + + +``` + * @example ​ ````Returns false, because the parent of the input is a p element. +```html + + + + + is demo + + + + +​ +
    +

    +
    +
    +​ + +​ + + +``` + * @example ​ ````Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. +```html + + + + + is demo + + + + +​ +
      +
    • Chrome
    • +
    • Safari
    • +
    • Firefox
    • +
    • Opera
    • +
    +​ + +​ + + +``` + * @example ​ ````An alternate way to achieve the above example using an element rather than a jQuery object. Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. +```html + + + + + is demo + + + + +​ +
      +
    • Chrome
    • +
    • Safari
    • +
    • Firefox
    • +
    • Opera
    • +
    +​ + +​ + + +``` + */ + is(selector_function_selection_elements: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): boolean; + /** + * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/keydown/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + keydown(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/keydown/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the event object for the keydown handler when a key is pressed in the input. +```html + + + + + keydown demo + + + + +​ +
    +
    + + +
    +
    + + +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/keypress/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + keypress(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/keypress/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (https://api.jquery.com/resources/events.js) for the event object's output. +```html + + + + + keypress demo + + + + +​ +
    +
    + + +
    +
    + + +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/keyup/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + keyup(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/keyup/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the event object for the keyup handler (using a simple $.print plugin) when a key is released in the input. +```html + + + + + keyup demo + + + + +​ +
    +
    + + +
    +
    + + +​ + +​ + + +``` + */ + 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/ }\` + * @since 1.4 + * @example ​ ````Highlight the last span in a paragraph. +```html + + + + + last demo + + + + +​ +

    Look: This is some text in a paragraph. This is a note about it.

    +​ + +​ + + +``` + */ + last(): this; + /** + * Load data from the server and place the returned HTML into the matched element. + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param complete A callback function that is executed when the request completes. + * @see \`{@link https://api.jquery.com/load/ }\` + * @since 1.0 + * @example ​ ````Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding. +```javascript +$( "#feeds" ).load( "feeds.php", { limit: 25 }, function() { + alert( "The last 25 entries in the feed have been loaded" ); +}); +``` + */ + load(url: string, + data: string | JQuery.PlainObject, + complete: (this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void): this; + /** + * Load data from the server and place the returned HTML into the matched element. + * @param url A string containing the URL to which the request is sent. + * @param complete_data _@param_ `complete_data` + *
    + * * `complete` — A callback function that is executed when the request completes.
    + * * `data` — A plain object or string that is sent to the server with the request. + * @see \`{@link https://api.jquery.com/load/ }\` + * @since 1.0 + * @example ​ ````Load another page's list items into an ordered list. +```html + + + + + load demo + + + + +​ +Projects: +
      +​ + +​ + + +``` + * @example ​ ````Display a notice if the Ajax request encounters an error. +```html + + + + + load demo + + + + +​ +Successful Response (should be blank): +
      +Error Response: +
      +​ + +​ + + +``` + * @example ​ ````Load the feeds.html file into the div with the ID of feeds. +```javascript +$( "#feeds" ).load( "feeds.html" ); +``` + * @example ​ ````pass arrays of data to the server. +```javascript +$( "#objectID" ).load( "test.php", { "choices[]": [ "Jon", "Susan" ] } ); +``` + */ + load(url: string, + complete_data?: ((this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void) | string | JQuery.PlainObject): this; + /** + * Pass each element in the current matched set through a function, producing a new jQuery object containing the return values. + * @param callback A function object that will be invoked for each element in the current set. + * @see \`{@link https://api.jquery.com/map/ }\` + * @since 1.2 + * @example ​ ````Build a list of all the values within a form. +```html + + + + + map demo + + + + +​ +

      Values:

      +
      + + + +
      +​ + +​ + + +``` + * @example ​ ````A contrived example to show some functionality. +```html + + + + + map demo + + + + +​ +
        +
      • First
      • +
      • Second
      • +
      • Third
      • +
      • Fourth
      • +
      • Fifth
      • +
      +
        +
      +​ + +​ + + +``` + * @example ​ ````Equalize the heights of the divs. +```html + + + + + map demo + + + + +​ + +
      +
      +
      +​ + +​ + + +``` + */ + map(callback: (this: TElement, index: number, domElement: TElement) => JQuery.TypeOrArray | null | undefined): JQuery; + /** + * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mousedown/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mousedown(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mousedown/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show texts when mouseup and mousedown event triggering. +```html + + + + + mousedown demo + + + +​ +

      Press mouse and release here.

      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mouseenter/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mouseenter(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mouseenter/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show texts when mouseenter and mouseout event triggering. + mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. +```html + + + + + mouseenter demo + + + + +​ +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +​ +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mouseleave/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mouseleave(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mouseleave/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show number of times mouseout and mouseleave events are triggered. mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element. +```html + + + + + mouseleave demo + + + + +​ +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mousemove/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mousemove(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mousemove/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe. +```html + + + + + mousemove demo + + + + +​ +

      + Move the mouse over the div. +   +

      +
      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mouseout/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mouseout(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mouseout/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the number of times mouseout and mouseleave events are triggered. + mouseout fires when the pointer moves out of the child element as well, while mouseleave fires only when the pointer moves out of the bound element. +```html + + + + + mouseout demo + + + + +​ +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +​ +
      +

      move your mouse

      +

      move your mouse

      0

      +

      0

      +
      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mouseover/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mouseover(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mouseover/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show the number of times mouseover and mouseenter events are triggered. +mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. +```html + + + + + mouseover demo + + + + +​ +
      + move your mouse +
      +
      +
      +​ +
      + move your mouse +
      +
      +
      +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/mouseup/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + mouseup(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/mouseup/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````Show texts when mouseup and mousedown event triggering. +```html + + + + + mouseup demo + + + +​ +

      Press mouse and release here.

      +​ + +​ + + +``` + */ + 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. + * @see \`{@link https://api.jquery.com/next/ }\` + * @since 1.0 + * @example ​ ````Find the very next sibling of each disabled button and change its text "this button is disabled". +```html + + + + + next demo + + + + +​ +
      -
      +
      -
      +
      -
      +​ + +​ + + +``` + * @example ​ ````Find the very next sibling of each paragraph. Keep only the ones with a class "selected". +```html + + + + + next demo + + + +​ +

      Hello

      +

      Hello Again

      +
      And Again
      +​ + +​ + + +``` + */ + next(selector?: JQuery.Selector): this; + /** + * Get all following siblings 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. + * @see \`{@link https://api.jquery.com/nextAll/ }\` + * @since 1.2 + * @example ​ ````Locate all the divs after the first and give them a class. +```html + + + + + nextAll demo + + + + +​ +
      first
      +
      sibling
      child
      +
      sibling
      +
      sibling
      ​ + +​ + + +``` + * @example ​ ````Locate all the paragraphs after the second child in the body and give them a class. +```html + + + + + nextAll demo + + + + +​ +

      p

      +
      div
      +

      p

      +

      p

      +
      div
      +

      p

      +
      div
      +​ + +​ + + +``` + */ + nextAll(selector?: string): this; + /** + * Get all following siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object passed. + * @param selector_element _@param_ `selector_element` + *
      + * * `selector` — A string containing a selector expression to indicate where to stop matching following sibling elements.
      + * * `element` — A DOM node or jQuery object indicating where to stop matching following sibling elements. + * @param filter A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/nextUntil/ }\` + * @since 1.4 + * @since 1.6 + * @example ​ ````Find the siblings that follow <dt id="term-2"> up to the next <dt> and give them a red background color. Also, find <dd> siblings that follow <dt id="term-1"> up to <dt id="term-3"> and give them a green text color. +```html + + + + + nextUntil demo + + + +​ +
      +
      term 1
      +
      definition 1-a
      +
      definition 1-b
      +
      definition 1-c
      +
      definition 1-d
      +
      term 2
      +
      definition 2-a
      +
      definition 2-b
      +
      definition 2-c
      +
      term 3
      +
      definition 3-a
      +
      definition 3-b
      +
      +​ + +​ + + +``` + */ + nextUntil(selector_element?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; + /** + * Remove elements from the set of matched elements. + * @param selector_function_selection _@param_ `selector_function_selection` + *
      + * * `selector` — A string containing a selector expression, a DOM element, or an array of elements to match against the set.
      + * * `function` — A function used as a test for each element in the set. It accepts two arguments, `index`, which is + * the element's index in the jQuery collection, and `element`, which is the DOM element. Within the + * function, `this` refers to the current DOM element.
      + * * `selection` — An existing jQuery object to match the current set of elements against. + * @see \`{@link https://api.jquery.com/not/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Adds a border to divs that are not green or blue. +```html + + + + + not demo + + + + +​ +
      +
      +
      +
      +
      +
      +
      +​ + +​ + + +``` + * @example ​ ````Removes the element with the ID "selected" from the set of all paragraphs. +```javascript +$( "p" ).not( $( "#selected" )[ 0 ] ); +``` + * @example ​ ````Removes the element with the ID "selected" from the set of all paragraphs. +```javascript +$( "p" ).not( "#selected" ); +``` + * @example ​ ````Removes all elements that match "div p.selected" from the total set of all paragraphs. +```javascript +$( "p" ).not( $( "div p.selected" ) ); +``` + */ + not(selector_function_selection: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): this; + /** + * Remove an event handler. + * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as + * "click", "keydown.myPlugin", or ".myPlugin". + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/off/ }\` + * @since 1.7 + * @example ​ ````Add and remove event handlers on the colored button. +```html + + + + + off demo + + + + +​ + + + +
      Click!
      +​ + +​ + + +``` + * @example ​ ````Remove just one previously bound handler by passing it as the third argument: +```javascript +var foo = function() { + // Code to handle some kind of event +}; +​ +// ... Now foo will be called when paragraphs are clicked ... +$( "body" ).on( "click", "p", foo ); +​ +// ... Foo will no longer be called. +$( "body" ).off( "click", "p", foo ); +``` + */ + off(events: string, + 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 + * "click", "keydown.myPlugin", or ".myPlugin". + * @param selector_handler _@param_ `selector_handler` + *
      + * * `selector` — A selector which should match the one originally passed to `.on()` when attaching event handlers.
      + * * `handler` — A handler function previously attached for the event(s), or the special value `false`. + * @see \`{@link https://api.jquery.com/off/ }\` + * @since 1.7 + * @example ​ ````Remove all delegated click handlers from all paragraphs: +```javascript +$( "p" ).off( "click", "**" ); +``` + * @example ​ ````Unbind all delegated event handlers by their namespace: +```javascript +var validate = function() { + // Code to validate form entries +}; +​ +// Delegate events under the ".validator" namespace +$( "form" ).on( "click.validator", "button", validate ); +​ +$( "form" ).on( "keypress.validator", "input[type='text']", validate ); +​ +// Remove event handlers in the ".validator" namespace +$( "form" ).off( ".validator" ); +``` + */ + off(events: string, + 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 + * namespaces, and the values represent handler functions previously attached for the event(s). + * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. + * @see \`{@link https://api.jquery.com/off/ }\` + * @since 1.7 + */ + off(events: JQuery.TypeEventHandlers, + selector?: JQuery.Selector): this; + /** + * Remove an event handler. + * @param event A jQuery.Event object. + * @see \`{@link https://api.jquery.com/off/ }\` + * @since 1.7 + * @example ​ ````Remove all event handlers from all paragraphs: +```javascript +$( "p" ).off(); +``` + */ + 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` + *
      + * * `coordinates` — An object containing the properties `top` and `left`, which are numbers indicating the new top and + * left coordinates for the elements.
      + * * `function` — A function to return the coordinates to set. Receives the index of the element in the collection as + * the first argument and the current coordinates as the second argument. The function should return an + * object with the new `top` and `left` properties. + * @see \`{@link https://api.jquery.com/offset/ }\` + * @since 1.4 + * @example ​ ````Set the offset of the second paragraph: +```html + + + + + offset demo + + + + +​ +

      Hello

      2nd Paragraph

      +​ + +​ + + +``` + */ + offset(coordinates_function: JQuery.CoordinatesPartial | ((this: TElement, index: number, coords: JQuery.Coordinates) => JQuery.CoordinatesPartial)): this; + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the document. + * @see \`{@link https://api.jquery.com/offset/ }\` + * @since 1.2 + * @example ​ ````Access the offset of the second paragraph: +```html + + + + + offset demo + + + + +​ +

      Hello

      2nd Paragraph

      +​ + +​ + + +``` + * @example ​ ````Click to see the offset. +```html + + + + + offset demo + + + + +​ +
      Click an element.
      +

      + This is the best way to find an offset. +

      +
      +
      +​ + +​ + + +``` + */ + offset(): JQuery.Coordinates | undefined; + /** + * Get the closest ancestor element that is positioned. + * @see \`{@link https://api.jquery.com/offsetParent/ }\` + * @since 1.2.6 + * @example ​ ````Find the offsetParent of item "A." +```html + + + + + offsetParent demo + + + +​ +
        +
      • I
      • +
      • II +
          +
        • A
        • +
        • B +
            +
          • 1
          • +
          • 2
          • +
          • 3
          • +
          +
        • +
        • C
        • +
        +
      • +
      • III
      • +
      +​ + +​ + + +``` + */ + offsetParent(): 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: 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". + * @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 + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. + */ + on(events: string, + selector: JQuery.Selector | null | undefined, + data: any, + 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 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand + * for a function that simply does return false. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. +```html + + + + + on demo + + + + +​ +

      Click me!

      + +​ + +​ + + +``` + * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: +```javascript +$( "body" ).on( "click", "p", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Cancel a link's default action using the .preventDefault() method: +```javascript +$( "body" ).on( "click", "a", function( event ) { + event.preventDefault(); +}); +``` + */ + 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 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 + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\` in place of \`{@link JQueryEventObject }\`. + * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. +```html + + + + + on demo + + + + +​ +

      Click me!

      + +​ + +​ + + +``` + * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: +```javascript +$( "body" ).on( "click", "p", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Cancel a link's default action using the .preventDefault() method: +```javascript +$( "body" ).on( "click", "a", function( event ) { + event.preventDefault(); +}); +``` + * @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, + selector_data: any, + 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand + * for a function that simply does return false. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + * @example ​ ````Display a paragraph's text in an alert when it is clicked: +```javascript +$( "p" ).on( "click", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: +```javascript +$( "form" ).on( "submit", false ); +``` + * @example ​ ````Cancel only the default action by using .preventDefault(). +```javascript +$( "form" ).on( "submit", function( event ) { + event.preventDefault(); +}); +``` + * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). +```javascript +$( "form" ).on( "submit", function( event ) { + event.stopPropagation(); +}); +``` + * @example ​ ````Pass data to the event handler using the second argument to .trigger() +```javascript +$( "div" ).on( "click", function( event, person ) { + alert( "Hello, " + person.name ); +}); +$( "div" ).trigger( "click", { name: "Jim" } ); +``` + * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler +```javascript +$( "div" ).on( "click", function( event, salutation, name ) { + alert( salutation + ", " + name ); +}); +$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] ); +``` + * @example ​ ````Attach and trigger custom (non-browser) events. +```html + + + + + on demo + + + + +​ +

      Has an attached custom event.

      + + +​ + +​ + + +``` + * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: +```javascript +$( "#cart" ).on( "mouseenter mouseleave", function( event ) { + $( this ).toggleClass( "active" ); +}); +``` + */ + 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". + * @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 ​ ````Display a paragraph's text in an alert when it is clicked: +```javascript +$( "p" ).on( "click", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: +```javascript +$( "form" ).on( "submit", false ); +``` + * @example ​ ````Cancel only the default action by using .preventDefault(). +```javascript +$( "form" ).on( "submit", function( event ) { + event.preventDefault(); +}); +``` + * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). +```javascript +$( "form" ).on( "submit", function( event ) { + event.stopPropagation(); +}); +``` + * @example ​ ````Pass data to the event handler using the second argument to .trigger() +```javascript +$( "div" ).on( "click", function( event, person ) { + alert( "Hello, " + person.name ); +}); +$( "div" ).trigger( "click", { name: "Jim" } ); +``` + * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler +```javascript +$( "div" ).on( "click", function( event, salutation, name ) { + alert( salutation + ", " + name ); +}); +$( "div" ).trigger( "click", [ "Goodbye", "Jim" ] ); +``` + * @example ​ ````Attach and trigger custom (non-browser) events. +```html + + + + + on demo + + + + +​ +

      Has an attached custom event.

      + + +​ + +​ + + +``` + * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: +```javascript +$( "#cart" ).on( "mouseenter mouseleave", function( event ) { + $( this ).toggleClass( "active" ); +}); +``` + */ + on(events: string, + handler: ((event: JQueryEventObject) => void)): 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: 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 + * 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. + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + */ + 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 + * namespaces, and the values represent a handler function to be called for the event(s). + * @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, + 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). + * @see \`{@link https://api.jquery.com/on/ }\` + * @since 1.7 + * @example ​ ````Attach multiple event handlers simultaneously using a plain object. +```html + + + + + on demo + + + + +​ +
      test div
      +​ + +​ + + +``` + */ + 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". + * @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: 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". + * @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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand + * for a function that simply does return false. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + one( + events: TType, + selector: JQuery.Selector, + 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". + * @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, + 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand + * for a function that simply does return false. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + * @example ​ ````Tie a one-time click to each div. +```html + + + + + one demo + + + + +​ +
      +
      +
      +
      +
      +

      Click a green square...

      +​ + +​ + + +``` + * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: +```javascript +$( "p" ).one( "click", function() { + alert( $( this ).text() ); +}); +``` + * @example ​ ````Event handlers will trigger once per element per event type +```html + + + + + one demo + + + +​ +
      0
      +
      Hover/click me
      +​ + +​ + + +``` + */ + 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 + * 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: 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 + * 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. + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + 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. + * @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 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, + 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). + * @see \`{@link https://api.jquery.com/one/ }\` + * @since 1.7 + */ + 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` + *
      + * * `value` — A number representing the number of pixels, or a number along with an optional unit of measure + * appended (as a string).
      + * * `function` — A function returning the outer height to set. Receives the index position of the element in the set + * and the old outer height as arguments. Within the function, `this` refers to the current element in + * the set. + * @see \`{@link https://api.jquery.com/outerHeight/ }\` + * @since 1.8.0 + * @example ​ ````Change the outer height of each div the first time it is clicked (and change its color). +```html + + + + + outerHeight demo + + + + +​ +
      d
      +
      d
      +
      d
      +
      d
      +
      d
      +​ + +​ + + +``` + */ + outerHeight(value_function: string | number | ((this: TElement, index: number, height: number) => string | number), + includeMargin?: boolean): this; + /** + * Get the current computed outer height (including padding, border, and optionally margin) for the first element in the set of matched elements. + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + * @see \`{@link https://api.jquery.com/outerHeight/ }\` + * @since 1.2.6 + * @example ​ ````Get the outerHeight of a paragraph. +```html + + + + + outerHeight demo + + + + +​ +

      Hello

      +​ + +​ + + +``` + */ + outerHeight(includeMargin?: boolean): number | undefined; + /** + * Set the CSS outer width of each element in the set of matched elements. + * @param value_function _@param_ `value_function` + *
      + * * `value` — A number representing the number of pixels, or a number along with an optional unit of measure + * appended (as a string).
      + * * `function` — A function returning the outer width to set. Receives the index position of the element in the set + * and the old outer width as arguments. Within the function, `this` refers to the current element in + * the set. + * @see \`{@link https://api.jquery.com/outerWidth/ }\` + * @since 1.8.0 + * @example ​ ````Change the outer width of each div the first time it is clicked (and change its color). +```html + + + + + outerWidth demo + + + + +​ +
      d
      +
      d
      +
      d
      +
      d
      +
      d
      +​ + +​ + + +``` + */ + outerWidth(value_function: string | number | ((this: TElement, index: number, width: number) => string | number), + includeMargin?: boolean): this; + /** + * Get the current computed outer width (including padding, border, and optionally margin) for the first element in the set of matched elements. + * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. + * @see \`{@link https://api.jquery.com/outerWidth/ }\` + * @since 1.2.6 + * @example ​ ````Get the outerWidth of a paragraph. +```html + + + + + outerWidth demo + + + + +​ +

      Hello

      +​ + +​ + + +``` + */ + outerWidth(includeMargin?: boolean): number | undefined; + /** + * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. + * @param selector A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/parent/ }\` + * @since 1.0 + * @example ​ ````Shows the parent of each element as (parent > child). Check the View Source to see the raw html. +```html + + + + + parent demo + + + + +​ +
      div, + span, + b +
      +​ +

      p, + span, + em + +

      +​ +
      div, + strong, + span, + em, + b, + + + b +
      +​ + +​ + + +``` + * @example ​ ````Find the parent element of each paragraph with a class "selected". +```html + + + + + parent demo + + + +​ +

      Hello

      +

      Hello Again

      +​ + +​ + + +``` + */ + parent(selector?: JQuery.Selector): this; + /** + * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. + * @param selector A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/parents/ }\` + * @since 1.0 + * @example ​ ````Find all parent elements of each b. +```html + + + + + parents demo + + + + +​ +
      +

      + + My parents are: + +

      +
      +​ + +​ + + +``` + * @example ​ ````Click to find all unique div parent elements of each span. +```html + + + + + parents demo + + + + +​ +

      +

      +
      Hello
      + Hello Again +
      +
      + And Hello Again +
      +

      + Click Hellos to toggle their parents. +​ + +​ + + +``` + */ + parents(selector?: JQuery.Selector): this; + /** + * Get the ancestors of each element in the current set of matched elements, up to but not including the element matched by the selector, DOM node, or jQuery object. + * @param selector_element _@param_ `selector_element` + *
      + * * `selector` — A string containing a selector expression to indicate where to stop matching ancestor elements.
      + * * `element` — A DOM node or jQuery object indicating where to stop matching ancestor elements. + * @param filter A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/parentsUntil/ }\` + * @since 1.4 + * @since 1.6 + * @example ​ ````Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color. Also, find ancestors of <li class="item-2"> that have a class of "yes" up to <ul class="level-1"> and give them a green border. +```html + + + + + parentsUntil demo + + + +​ +
        +
      • I
      • +
      • II +
          +
        • A
        • +
        • B +
            +
          • 1
          • +
          • 2
          • +
          • 3
          • +
          +
        • +
        • C
        • +
        +
      • +
      • III
      • +
      +​ + +​ + + +``` + */ + parentsUntil(selector_element?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; + /** + * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. + * @see \`{@link https://api.jquery.com/position/ }\` + * @since 1.2 + * @example ​ ````Access the position of the second paragraph: +```html + + + + + position demo + + + + +​ +
      +

      Hello

      +
      +

      +​ + +​ + + +``` + */ + position(): JQuery.Coordinates; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or + * jQuery objects to insert at the beginning of each element in the set of matched elements. + * @see \`{@link https://api.jquery.com/prepend/ }\` + * @since 1.0 + * @example ​ ````Prepends some HTML to all paragraphs. +```html + + + + + prepend demo + + + + +​ +

      there, friend!

      +

      amigo!

      +​ + +​ + + +``` + * @example ​ ````Prepends a DOM Element to all paragraphs. +```html + + + + + prepend demo + + + + +​ +

      is what I'd say

      +

      is what I said

      +​ + +​ + + +``` + * @example ​ ````Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. +```html + + + + + prepend demo + + + + +​ +

      is what was said.

      Hello +​ + +​ + + +``` + */ + prepend(...contents: Array>>): this; + /** + * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. + * @param funсtion A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at + * the beginning of each element in the set of matched elements. Receives the index position of the + * element in the set and the old HTML value of the element as arguments. Within the function, `this` + * refers to the current element in the set. + * @see \`{@link https://api.jquery.com/prepend/ }\` + * @since 1.4 + */ + prepend(funсtion: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; + /** + * Insert every element in the set of matched elements to the beginning of the target. + * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements + * will be inserted at the beginning of the element(s) specified by this parameter. + * @see \`{@link https://api.jquery.com/prependTo/ }\` + * @since 1.0 + * @example ​ ````Prepend all spans to the element with the ID "foo" (Check .prepend() documentation for more examples) +```html + + + + + prependTo demo + + + + +​ +
      FOO!
      +I have something to say... +​ + +​ + + +``` + */ + prependTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; + /** + * Get the immediately preceding sibling of each element in the set of matched elements. If a selector is provided, it retrieves the previous sibling only if it matches that selector. + * @param selector A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/prev/ }\` + * @since 1.0 + * @example ​ ````Find the very previous sibling of each div. +```html + + + + + prev demo + + + + +​ +
      +
      +
      has child
      +
      +
      +
      +
      +
      +

      +​ + +​ + + +``` + * @example ​ ````For each paragraph, find the very previous sibling that has a class "selected". +```html + + + + + prev demo + + + +​ +
      Hello
      +

      Hello Again

      +

      And Again

      +​ + +​ + + +``` + */ + prev(selector?: JQuery.Selector): this; + /** + * Get all preceding siblings 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. + * @see \`{@link https://api.jquery.com/prevAll/ }\` + * @since 1.2 + * @example ​ ````Locate all the divs preceding the last div and give them a class. +```html + + + + + prevAll demo + + + + +​ +
      +
      +
      +
      +​ + +​ + + +``` + */ + prevAll(selector?: JQuery.Selector): this; + /** + * Get all preceding siblings of each element up to but not including the element matched by the selector, DOM node, or jQuery object. + * @param selector_element _@param_ `selector_element` + *
      + * * `selector` — A string containing a selector expression to indicate where to stop matching preceding sibling elements.
      + * * `element` — A DOM node or jQuery object indicating where to stop matching preceding sibling elements. + * @param filter A string containing a selector expression to match elements against. + * @see \`{@link https://api.jquery.com/prevUntil/ }\` + * @since 1.4 + * @since 1.6 + * @example ​ ````Find the siblings that precede <dt id="term-2"> up to the preceding <dt> and give them a red background color. Also, find previous <dd> siblings of <dt id="term-3"> up to <dt id="term-1"> and give them a green text color. +```html + + + + + prevUntil demo + + + +​ +
      +
      term 1
      +
      definition 1-a
      +
      definition 1-b
      +
      definition 1-c
      +
      definition 1-d
      +​ +
      term 2
      +
      definition 2-a
      +
      definition 2-b
      +
      definition 2-c
      +​ +
      term 3
      +
      definition 3-a
      +
      definition 3-b
      +
      +​ + +​ + + +``` + */ + prevUntil(selector_element?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * @param type The type of queue that needs to be observed. + * @param target Object onto which the promise methods have to be attached + * @see \`{@link https://api.jquery.com/promise/ }\` + * @since 1.6 + */ + promise(type: string, target: T): T & JQuery.Promise; + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * @param target Object onto which the promise methods have to be attached + * @see \`{@link https://api.jquery.com/promise/ }\` + * @since 1.6 + */ + promise(target: T): T & JQuery.Promise; + /** + * Return a Promise object to observe when all actions of a certain type bound to the collection, queued or not, have finished. + * @param type The type of queue that needs to be observed. + * @see \`{@link https://api.jquery.com/promise/ }\` + * @since 1.6 + * @example ​ ````Using .promise() on a collection with no active animation returns a resolved Promise: +```javascript +var div = $( "
      " ); +​ +div.promise().done(function( arg1 ) { + // Will fire right away and alert "true" + alert( this === div && arg1 === div ); +}); +``` + * @example ​ ````Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on): +```html + + + + + promise demo + + + + +​ + +

      Ready...

      +
      +
      +
      +
      +​ + +​ + + +``` + * @example ​ ````Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections): +```html + + + + + promise demo + + + + +​ + +

      Ready...

      +
      +
      +
      +
      +​ + +​ + + +``` + */ + promise(type?: string): JQuery.Promise; + /** + * Set one or more properties for the set of matched elements. + * @param propertyName The name of the property to set. + * @param value_function _@param_ `value_function` + *
      + * * `value` — A value to set for the property.
      + * * `function` — A function returning the value to set. Receives the index position of the element in the set and the + * old property value as arguments. Within the function, the keyword `this` refers to the current element. + * @see \`{@link https://api.jquery.com/prop/ }\` + * @since 1.6 + */ + prop(propertyName: string, + value_function: string | number | boolean | symbol | object | null | undefined | ((this: TElement, index: number, oldPropertyValue: any) => any)): this; + /** + * Set one or more properties for the set of matched elements. + * @param properties An object of property-value pairs to set. + * @see \`{@link https://api.jquery.com/prop/ }\` + * @since 1.6 + * @example ​ ````Disable all checkboxes on the page. +```html + + + + + prop demo + + + + +​ + + + + +​ + +​ + + +``` + */ + prop(properties: JQuery.PlainObject): this; + /** + * Get the value of a property for the first element in the set of matched elements. + * @param propertyName The name of the property to get. + * @see \`{@link https://api.jquery.com/prop/ }\` + * @since 1.6 + * @example ​ ````Display the checked property and attribute of a checkbox as it changes. +```html + + + + + prop demo + + + + +​ + + +

      +​ + +​ + + +``` + */ + prop(propertyName: string): any; + /** + * Add a collection of DOM elements onto the jQuery stack. + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @param name The name of a jQuery method that generated the array of elements. + * @param args The arguments that were passed in to the jQuery method (for serialization). + * @see \`{@link https://api.jquery.com/pushStack/ }\` + * @since 1.3 + */ + pushStack(elements: ArrayLike, name: string, args: any[]): this; + /** + * Add a collection of DOM elements onto the jQuery stack. + * @param elements An array of elements to push onto the stack and make into a new jQuery object. + * @see \`{@link https://api.jquery.com/pushStack/ }\` + * @since 1.0 + * @example ​ ````Add some elements onto the jQuery stack, then pop back off again. +```javascript +jQuery([]) + .pushStack( document.getElementsByTagName( "div" ) ) + .remove() + .end(); +``` + */ + pushStack(elements: ArrayLike): this; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. + * An array of functions to replace the current queue contents. + * @see \`{@link https://api.jquery.com/queue/ }\` + * @since 1.2 + * @example ​ ````Set a queue array to delete the queue. +```html + + + + + queue demo + + + + +​ + + +
      +​ + +​ + + +``` + */ + queue(queueName: string, newQueue: JQuery.TypeOrArray>): this; + /** + * Manipulate the queue of functions to be executed, once for each matched element. + * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. + * An array of functions to replace the current queue contents. + * @see \`{@link https://api.jquery.com/queue/ }\` + * @since 1.2 + * @example ​ ````Queue a custom function. +```html + + + + + queue demo + + + + +​ +Click here... +
      +​ + +​ + + +``` + */ + queue(newQueue: JQuery.TypeOrArray>): this; + /** + * Show the queue of functions to be executed on the matched elements. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @see \`{@link https://api.jquery.com/queue/ }\` + * @since 1.2 + * @example ​ ````Show the length of the queue. +```html + + + + + queue demo + + + + +​ +

      The queue length is:

      +
      +​ + +​ + + +``` + */ + queue(queueName?: string): JQuery.Queue; + /** + * Specify a function to execute when the DOM is fully loaded. + * @param handler A function to execute after the DOM is ready. + * @see \`{@link https://api.jquery.com/ready/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.0. Use `jQuery(function() { })`. + * @example ​ ````Display a message when the DOM is loaded. +```html + + + + + ready demo + + + + + +​ +

      Not loaded yet.

      +​ + + +``` + */ + ready(handler: ($: JQueryStatic) => void): this; + /** + * Remove the set of matched elements from the DOM. + * @param selector A selector expression that filters the set of matched elements to be removed. + * @see \`{@link https://api.jquery.com/remove/ }\` + * @since 1.0 + * @example ​ ````Removes all paragraphs from the DOM +```html + + + + + remove demo + + + + +​ +

      Hello

      +how are +

      you?

      + +​ + +​ + + +``` + * @example ​ ````Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing $("p").filter(":contains('Hello')").remove(). +```html + + + + + remove demo + + + + +​ +

      Hello

      +how are +

      you?

      + +​ + +​ + + +``` + */ + remove(selector?: string): this; + /** + * Remove an attribute from each element in the set of matched elements. + * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. + * @see \`{@link https://api.jquery.com/removeAttr/ }\` + * @since 1.0 + * @example ​ ````Clicking the button changes the title of the input next to it. Move the mouse pointer over the text input to see the effect of adding and removing the title attribute. +```html + + + + + removeAttr demo + + + +​ + + +
      +​ + +​ + + +``` + */ + removeAttr(attributeName: string): this; + /** + * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. + * @param className_function _@param_ `className_function` + *
      + * * `className` — One or more space-separated classes to be removed from the class attribute of each matched element.
      + * * `function` — A function returning one or more space-separated class names to be removed. Receives the index + * position of the element in the set and the old class value as arguments. + * @see \`{@link https://api.jquery.com/removeClass/ }\` + * @since 1.0 + * @since 1.4 + * @since 3.3 + * @example ​ ````Remove the class 'blue' from the matched elements. +```html + + + + + removeClass demo + + + + +​ +

      Hello

      +

      and

      +

      then

      +

      Goodbye

      +​ + +​ + + +``` + * @example ​ ````Remove the class 'blue' and 'under' from the matched elements. +```html + + + + + removeClass demo + + + + +​ +

      Hello

      +

      and

      +

      then

      +

      Goodbye

      +​ + +​ + + +``` + * @example ​ ````Remove all the classes from the matched elements. +```html + + + + + removeClass demo + + + + +​ +

      Hello

      +

      and

      +

      then

      +

      Goodbye

      +​ + +​ + + +``` + */ + removeClass(className_function?: JQuery.TypeOrArray | ((this: TElement, index: number, className: string) => string)): this; + /** + * Remove a previously-stored piece of data. + * @param name A string naming the piece of data to delete. + * An array or space-separated string naming the pieces of data to delete. + * @see \`{@link https://api.jquery.com/removeData/ }\` + * @since 1.2.3 + * @since 1.7 + * @example ​ ````Set a data store for 2 names then remove one of them. +```html + + + + + removeData demo + + + + +​ +
      value1 before creation:
      +
      value1 after creation:
      +
      value1 after removal:
      +
      value2 after removal:
      +​ + +​ + + +``` + */ + removeData(name?: JQuery.TypeOrArray): this; + /** + * Remove a property for the set of matched elements. + * @param propertyName The name of the property to remove. + * @see \`{@link https://api.jquery.com/removeProp/ }\` + * @since 1.6 + * @example ​ ````Set a numeric property on a paragraph and then remove it. +```html + + + + + removeProp demo + + + + +​ +

      +​ + +​ + + +``` + */ + removeProp(propertyName: string): this; + /** + * Replace each target element with the set of matched elements. + * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. + * @see \`{@link https://api.jquery.com/replaceAll/ }\` + * @since 1.2 + * @example ​ ````Replace all the paragraphs with bold words. +```html + + + + + replaceAll demo + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + */ + replaceAll(target: JQuery.Selector | JQuery | JQuery.TypeOrArray): this; + /** + * Replace each element in the set of matched elements with the provided new content and return the set of elements that was removed. + * @param newContent_function _@param_ `newContent_function` + *
      + * * `newContent` — The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object.
      + * * `function` — A function that returns content with which to replace the set of matched elements. + * @see \`{@link https://api.jquery.com/replaceWith/ }\` + * @since 1.2 + * @since 1.4 + * @example ​ ````On click, replace the button with a div containing the same word. +```html + + + + + replaceWith demo + + + + +​ + + + +​ + +​ + + +``` + * @example ​ ````Replace all paragraphs with bold words. +```html + + + + + replaceWith demo + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````On click, replace each paragraph with a div that is already in the DOM and selected with the $() function. Notice it doesn't clone the object but rather moves it to replace the paragraph. +```html + + + + + replaceWith demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +
      Replaced!
      +​ + +​ + + +``` + * @example ​ ````On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph. +```html + + + + + replaceWith demo + + + + +​ +

      + +

      +
      +
      Scooby
      +
      Dooby
      +
      Doo
      +
      +​ + +​ + + +``` + */ + replaceWith(newContent_function: JQuery.htmlString | JQuery | JQuery.TypeOrArray | ((this: TElement) => any)): this; + /** + * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/resize/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + resize(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/resize/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To see the window width while (or after) it is resized, try: +```javascript +$( window ).resize(function() { + $( "body" ).prepend( "
      " + $( window ).width() + "
      " ); +}); +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/scroll/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + scroll(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/scroll/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To do something when your page is scrolled: +```html + + + + + scroll demo + + + + +​ +
      Try scrolling the iframe.
      +

      Paragraph - Scroll happened!

      +​ + +​ + + +``` + */ + 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. + * @see \`{@link https://api.jquery.com/scrollLeft/ }\` + * @since 1.2.6 + * @example ​ ````Set the scrollLeft of a div. +```html + + + + + scrollLeft demo + + + + +​ +

      lalala

      Hello

      +​ + +​ + + +``` + */ + scrollLeft(value: number): this; + /** + * Get the current horizontal position of the scroll bar for the first element in the set of matched elements. + * @see \`{@link https://api.jquery.com/scrollLeft/ }\` + * @since 1.2.6 + * @example ​ ````Get the scrollLeft of a paragraph. +```html + + + + + scrollLeft demo + + + + +​ +

      Hello

      +​ + +​ + + +``` + */ + scrollLeft(): number | undefined; + /** + * Set the current vertical position of the scroll bar for each of the set of matched elements. + * @param value A number indicating the new position to set the scroll bar to. + * @see \`{@link https://api.jquery.com/scrollTop/ }\` + * @since 1.2.6 + * @example ​ ````Set the scrollTop of a div. +```html + + + + + scrollTop demo + + + + +​ +

      lalala

      Hello

      +​ + +​ + + +``` + */ + scrollTop(value: number): this; + /** + * Get the current vertical position of the scroll bar for the first element in the set of matched elements or set the vertical position of the scroll bar for every matched element. + * @see \`{@link https://api.jquery.com/scrollTop/ }\` + * @since 1.2.6 + * @example ​ ````Get the scrollTop of a paragraph. +```html + + + + + scrollTop demo + + + + +​ +

      Hello

      +​ + +​ + + +``` + */ + scrollTop(): number | undefined; + /** + * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/select/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + select(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/select/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````To do something when text in input boxes is selected: +```html + + + + + select demo + + + + +​ +

      Click and drag the mouse to select text in the inputs.

      + + +
      + ​ + +​ + + +``` + * @example ​ ````To trigger the select event on all input elements, try: +```javascript +$( "input" ).select(); +``` + */ + select(handler?: JQuery.TypeEventHandler | + false): this; + /** + * Encode a set of form elements as a string for submission. + * @see \`{@link https://api.jquery.com/serialize/ }\` + * @since 1.0 + * @example ​ ````Serialize a form to a query string that could be sent to a server in an Ajax request. +```html + + + + + serialize demo + + + + +​ +
      + +​ +
      + +​ +
      + + + + +​ +
      + + + + +
      +​ +

      +​ + +​ + + +``` + */ + serialize(): string; + /** + * Encode a set of form elements as an array of names and values. + * @see \`{@link https://api.jquery.com/serializeArray/ }\` + * @since 1.2 + * @example ​ ````Get the values from a form, iterate through them, and append them to a results display. +```html + + + + + serializeArray demo + + + + +​ +

      Results:

      +
      + + +
      + + + + + + + + +
      +​ + +​ + + +``` + */ + serializeArray(): JQuery.NameValuePair[]; + /** + * Display the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/show/ }\` + * @since 1.4.3 + */ + show(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; + /** + * Display the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param easing_complete _@param_ `easing_complete` + *
      + * * `easing` — A string indicating which easing function to use for the transition.
      + * * `complete` — A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/show/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Show the first div, followed by each next adjacent sibling div in order, with a 200ms animation. Each animation starts when the previous sibling div's animation ends. +```html + + + + + show demo + + + + +​ + + +
      Hello 3,
      +
      how
      +
      are
      +
      you?
      +​ + +​ + + +``` + * @example ​ ````Show all span and input elements with an animation. Change the text once the animation is done. +```html + + + + + show demo + + + + +​ + +Are you sure? (type 'yes' if you are) +
      +
      + +
      +
      +

      I'm hidden...

      +​ + +​ + + +``` + */ + show(duration: JQuery.Duration, easing_complete: string | ((this: TElement) => void)): this; + /** + * Display the matched elements. + * @param duration_complete_options _@param_ `duration_complete_options` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/show/ }\` + * @since 1.0 + * @example ​ ````Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. +```html + + + + + show demo + + + + +​ + +

      Hello 2

      +​ + +​ + + +``` + */ + show(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Get the siblings 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. + * @see \`{@link https://api.jquery.com/siblings/ }\` + * @since 1.0 + * @example ​ ````Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate). +```html + + + + + siblings demo + + + + +​ +
        +
      • One
      • +
      • Two
      • +
      • Three
      • +
      • Four
      • +
      +​ +
        +
      • Five
      • +
      • Six
      • +
      • Seven
      • +
      +​ +
        +
      • Eight
      • +
      • Nine
      • +
      • Ten
      • +
      • Eleven
      • +
      +​ +

      Unique siblings:

      +​ + +​ + + +``` + * @example ​ ````Find all siblings with a class "selected" of each div. +```html + + + + + siblings demo + + + +​ +
      Hello
      +

      Hello Again

      +

      And Again

      +​ + +​ + + +``` + */ + siblings(selector?: JQuery.Selector): this; + /** + * Reduce the set of matched elements to a subset specified by a range of indices. + * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, + * it indicates an offset from the end of the set. + * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, + * it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. + * @see \`{@link https://api.jquery.com/slice/ }\` + * @since 1.1.4 + * @example ​ ````Turns divs yellow based on a random slice. +```html + + + + + slice demo + + + + +​ +

      + Click the button!

      +
      +
      +
      +
      +
      +
      +
      +
      +
      + ​ + +​ + + +``` + * @example ​ ````Selects all paragraphs, then slices the selection to include only the first element. +```javascript +$( "p" ).slice( 0, 1 ).wrapInner( "" ); +``` + * @example ​ ````Selects all paragraphs, then slices the selection to include only the first and second element. +```javascript +$( "p" ).slice( 0, 2 ).wrapInner( "" ); +``` + * @example ​ ````Selects all paragraphs, then slices the selection to include only the second element. +```javascript +$( "p" ).slice( 1, 2 ).wrapInner( "" ); +``` + * @example ​ ````Selects all paragraphs, then slices the selection to include only the second and third element. +```javascript +$( "p" ).slice( 1 ).wrapInner( "" ); +``` + * @example ​ ````Selects all paragraphs, then slices the selection to include only the third element. +```javascript +$( "p" ).slice( -1 ).wrapInner( "" ); +``` + */ + slice(start: number, end?: number): this; + /** + * Display the matched elements with a sliding motion. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideDown/ }\` + * @since 1.4.3 + */ + slideDown(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Display the matched elements with a sliding motion. + * @param duration_easing _@param_ `duration_easing` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideDown/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus. +```html + + + + + slideDown demo + + + + +​ +
      Push!
      + + + + ​ + +​ + + +``` + */ + slideDown(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Display the matched elements with a sliding motion. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/slideDown/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all divs to slide down and show themselves over 600 milliseconds. +```html + + + + + slideDown demo + + + + +​ +Click me! +
      +
      +
      +​ + +​ + + +``` + */ + slideDown(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Display or hide the matched elements with a sliding motion. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideToggle/ }\` + * @since 1.4.3 + */ + slideToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Display or hide the matched elements with a sliding motion. + * @param duration_easing _@param_ `duration_easing` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideToggle/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates divs between dividers with a toggle that makes some appear and some disappear. +```html + + + + + slideToggle demo + + + + +​ +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +
      +

      There have been 0 toggled divs.

      +​ + +​ + + +``` + */ + slideToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Display or hide the matched elements with a sliding motion. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/slideToggle/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds. +```html + + + + + slideToggle demo + + + + +​ + +

      + This is the paragraph to end all paragraphs. You + should feel lucky to have seen such a paragraph in + your life. Congratulations! +

      +​ + +​ + + +``` + */ + slideToggle(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Hide the matched elements with a sliding motion. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideUp/ }\` + * @since 1.4.3 + */ + slideUp(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Hide the matched elements with a sliding motion. + * @param duration_easing _@param_ `duration_easing` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/slideUp/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert. +```html + + + + + slideUp demo + + + + +​ +
      + + +
      +​ +
      + + +
      +​ +
      + + +
      +​ +
      +​ + +​ + + +``` + */ + slideUp(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; + /** + * Hide the matched elements with a sliding motion. + * @param duration_easing_complete_options _@param_ `duration_easing_complete_options` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `easing` — A string indicating which easing function to use for the transition.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `options` — A map of additional options to pass to the method. + * @see \`{@link https://api.jquery.com/slideUp/ }\` + * @since 1.0 + * @since 1.4.3 + * @example ​ ````Animates all divs to slide up, completing the animation within 400 milliseconds. +```html + + + + + slideUp demo + + + + +​ +Click me! +
      +
      +
      +
      +
      +​ + +​ + + +``` + */ + slideUp(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; + /** + * Stop the currently-running animation on the matched elements. + * @param queue The name of the queue in which to stop animations. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + * @see \`{@link https://api.jquery.com/stop/ }\` + * @since 1.7 + */ + stop(queue: string, clearQueue?: boolean, jumpToEnd?: boolean): this; + /** + * Stop the currently-running animation on the matched elements. + * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. + * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. + * @see \`{@link https://api.jquery.com/stop/ }\` + * @since 1.2 + * @example ​ ````Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one. +```html + + + + + stop demo + + + + +​ + + + +
      +​ + +​ + + +``` + * @example ​ ````Click the slideToggle button to start the animation, then click again before the animation is completed. The animation will toggle the other direction from the saved starting point. +```html + + + + + stop demo + + + + +​ + +
      +​ + +​ + + +``` + */ + stop(clearQueue?: boolean, jumpToEnd?: boolean): this; + /** + * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. + * @param eventData An object containing data that will be passed to the event handler. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/submit/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + */ + submit(eventData: TData, + 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. + * @see \`{@link https://api.jquery.com/submit/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.3. Use \`{@link on }\` or \`{@link trigger }\`. + * + * **Cause**: The `.on()` and `.trigger()` methods can set an event handler or generate an event for any event type, and should be used instead of the shortcut methods. This message also applies to the other event shorthands, including: blur, focus, focusin, focusout, resize, scroll, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mouseenter, mouseleave, change, select, submit, keydown, keypress, keyup, and contextmenu. + * + * **Solution**: Instead of `.click(fn)` use `.on("click", fn)`. Instead of `.click()` use `.trigger("click")`. + * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: +```html + + + + + submit demo + + + + +​ +

      Type 'correct' to validate.

      +
      +
      + + +
      +
      + +​ + +​ + + +``` + * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: +```javascript +$( "form" ).submit(function() { + return this.some_flag_variable; +}); +``` + * @example ​ ````To trigger the submit event on the first form on the page, try: +```javascript +$( "form:first" ).submit(); +``` + */ + 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` + *
      + * * `text` — The text to set as the content of each matched element. When Number or Boolean is supplied, it will + * be converted to a String representation.
      + * * `function` — A function returning the text content to set. Receives the index position of the element in the set + * and the old text value as arguments. + * @see \`{@link https://api.jquery.com/text/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Add text to the paragraph (notice the bold tag is escaped). +```html + + + + + text demo + + + + +​ +

      Test Paragraph.

      +​ + +​ + + +``` + */ + text(text_function: string | number | boolean | ((this: TElement, index: number, text: string) => string | number | boolean)): this; + /** + * Get the combined text contents of each element in the set of matched elements, including their descendants. + * @see \`{@link https://api.jquery.com/text/ }\` + * @since 1.0 + * @example ​ ````Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone). +```html + + + + + text demo + + + + +​ +

      Test Paragraph.

      +

      +​ + +​ + + +``` + */ + text(): string; + /** + * Retrieve all the elements contained in the jQuery set, as an array. + * @see \`{@link https://api.jquery.com/toArray/ }\` + * @since 1.4 + * @example ​ ````Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. +```html + + + + + toArray demo + + + + +​ +Reversed - +​ +
      One
      +
      Two
      +
      Three
      ​ + +​ + + +``` + */ + toArray(): TElement[]; + /** + * Display or hide the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/toggle/ }\` + * @since 1.4.3 + */ + toggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; + /** + * Display or hide the matched elements. + * @param duration A string or number determining how long the animation will run. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/toggle/ }\` + * @since 1.0 + */ + toggle(duration: JQuery.Duration, complete: (this: TElement) => void): this; + /** + * Display or hide the matched elements. + * @param duration_complete_options_display _@param_ `duration_complete_options_display` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `options` — A map of additional options to pass to the method.
      + * * `display` — Use true to show the element or false to hide it. + * @see \`{@link https://api.jquery.com/toggle/ }\` + * @since 1.0 + * @since 1.3 + * @example ​ ````Toggles all paragraphs. +```html + + + + + toggle demo + + + +​ + +

      Hello

      +

      Good Bye

      +​ + +​ + + +``` + * @example ​ ````Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds. +```html + + + + + toggle demo + + + + +​ + +

      Hiya

      +

      Such interesting text, eh?

      +​ + +​ + + +``` + * @example ​ ````Shows all paragraphs, then hides them all, back and forth. +```html + + + + + toggle demo + + + +​ + +

      Hello

      +

      Good Bye

      +​ + +​ + + +``` + */ + toggle(duration_complete_options_display?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions | boolean): this; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument. + * @param className_function _@param_ `className_function` + *
      + * * `className` — One or more class names (separated by spaces) to be toggled for each element in the matched set.
      + * * `function` — A function that returns class names to be toggled in the class attribute of each element in the + * matched set. Receives the index position of the element in the set, the old class value, and the state as arguments. + * @param state A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. + * @see \`{@link https://api.jquery.com/toggleClass/ }\` + * @since 1.0 + * @since 1.3 + * @since 1.4 + * @since 3.3 + * @example ​ ````Toggle the class 'highlight' when a paragraph is clicked. +```html + + + + + toggleClass demo + + + + +​ +

      Click to toggle

      +

      highlight

      +

      on these

      +

      paragraphs

      +​ + +​ + + +``` + * @example ​ ````Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click. +```html + + + + + toggleClass demo + + + + +​ +

      Click to toggle (clicks: 0)

      +

      highlight (clicks: 0)

      +

      on these (clicks: 0)

      +

      paragraphs (clicks: 0)

      +​ + +​ + + +``` + * @example ​ ````Toggle the class name(s) indicated on the buttons for each div. +```html + + + + + toggleClass demo + + + + +​ +
      + + + + + reset +
      +
      +
      +
      +
      +
      +
      +​ + +​ + + +``` + */ + toggleClass(className_function: JQuery.TypeOrArray | ((this: TElement, index: number, className: string, state: TState) => string), + state?: TState): this; + /** + * Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument. + * @param state A boolean value to determine whether the class should be added or removed. + * @see \`{@link https://api.jquery.com/toggleClass/ }\` + * @since 1.4 + * @deprecated ​ Deprecated since 3.0. See \`{@link https://github.com/jquery/jquery/pull/2618 }\`. + * + * **Cause**: Calling `.toggleClass()` with no arguments, or with a single Boolean `true` or `false` argument, has been deprecated. Its behavior was poorly documented, but essentially the method saved away the current class value in a data item when the class was removed and restored the saved value when it was toggled back. If you do not believe you are specificially trying to use this form of the method, it is possible you are accidentally doing so via an inadvertent undefined value, as `.toggleClass( undefined )` toggles all classes. + * + * **Solution**: If this functionality is still needed, save the current full `.attr( "class" )` value in a data item and restore it when required. + */ + toggleClass(state?: boolean): this; + /** + * Execute all handlers and behaviors attached to the matched elements for the given event type. + * @param eventType_event _@param_ `eventType_event` + *
      + * * `eventType` — A string containing a JavaScript event type, such as `click` or `submit`.
      + * * `event` — A \`{@link https://api.jquery.com/category/events/event-object/ jQuery.Event}\` object. + * @param extraParameters Additional parameters to pass along to the event handler. + * @see \`{@link https://api.jquery.com/trigger/ }\` + * @since 1.0 + * @since 1.3 + * @example ​ ````Clicks to button #2 also trigger a click for button #1. +```html + + + + + trigger demo + + + + +​ + + +
      0 button #1 clicks.
      +
      0 button #2 clicks.
      +​ + +​ + + +``` + * @example ​ ````To submit the first form without using the submit() function, try: +```javascript +$( "form:first" ).trigger( "submit" ); +``` + * @example ​ ````To submit the first form without using the submit() function, try: +```javascript +var event = jQuery.Event( "submit" ); +$( "form:first" ).trigger( event ); +if ( event.isDefaultPrevented() ) { + // Perform an action... +} +``` + * @example ​ ````To pass arbitrary data to an event: +```javascript +$( "p" ) + .click(function( event, a, b ) { + // When a normal click fires, a and b are undefined + // for a trigger like below a refers to "foo" and b refers to "bar" + }) + .trigger( "click", [ "foo", "bar" ] ); +``` + * @example ​ ````To pass arbitrary data through an event object: +```javascript +var event = jQuery.Event( "logged" ); +event.user = "foo"; +event.pass = "bar"; +$( "body" ).trigger( event ); +``` + * @example ​ ````Alternative way to pass data through an event object: +```javascript +$( "body" ).trigger({ + type:"logged", + user:"foo", + pass:"bar" +}); +``` + */ + 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` + *
      + * * `eventType` — A string containing a JavaScript event type, such as `click` or `submit`.
      + * * `event` — A \`{@link https://api.jquery.com/category/events/event-object/ jQuery.Event}\` object. + * @param extraParameters Additional parameters to pass along to the event handler. + * @see \`{@link https://api.jquery.com/triggerHandler/ }\` + * @since 1.2 + * @since 1.3 + * @example ​ ````If you called .triggerHandler() on a focus event - the browser's default focus action would not be triggered, only the event handlers bound to the focus event. +```html + + + + + triggerHandler demo + + + +​ + +

      +​ + +​ + +​ + + +``` + */ + 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. + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/unbind/ }\` + * @since 1.0 + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.0. Use \`{@link off }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````Can bind and unbind events to the colored button. +```html + + + + + unbind demo + + + + +​ + + + +
      Click!
      +​ + +​ + + +``` + * @example ​ ````To unbind just one previously bound handler, pass the function in as the second argument: +```javascript +var foo = function() { + // Code to handle some kind of event +}; +​ +$( "p" ).bind( "click", foo ); // ... Now foo will be called when paragraphs are clicked ... +​ +$( "p" ).unbind( "click", foo ); // ... foo will no longer be called. +``` + */ + unbind(event: string, + 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. + * A jQuery.Event object. + * @see \`{@link https://api.jquery.com/unbind/ }\` + * @since 1.0 + * @deprecated ​ Deprecated since 3.0. Use \`{@link off }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````To unbind all events from all paragraphs, write: +```javascript +$( "p" ).unbind(); +``` + * @example ​ ````To unbind all click events from all paragraphs, write: +```javascript +$( "p" ).unbind( "click" ); +``` + */ + 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. + * @param eventType A string containing a JavaScript event type, such as "click" or "keydown" + * @param handler A function to execute each time the event is triggered. + * @see \`{@link https://api.jquery.com/undelegate/ }\` + * @since 1.4.2 + * @deprecated ​ Deprecated since 3.0. Use \`{@link off }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````Can bind and unbind events to the colored button. +```html + + + + + undelegate demo + + + + +​ + + + +
      Click!
      +​ + +​ + + +``` + * @example ​ ````To undelegate just one previously bound handler, pass the function in as the third argument: +```javascript +var foo = function () { + // Code to handle some kind of event +}; +​ +// ... Now foo will be called when paragraphs are clicked ... +$( "body" ).delegate( "p", "click", foo ); +​ +// ... foo will no longer be called. +$( "body" ).undelegate( "p", "click", foo ); +``` + */ + undelegate(selector: JQuery.Selector, + eventType: string, + 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 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 + * @deprecated ​ Deprecated since 3.0. Use \`{@link off }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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, + 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. + * @see \`{@link https://api.jquery.com/undelegate/ }\` + * @since 1.4.2 + * @since 1.6 + * @deprecated ​ Deprecated since 3.0. Use \`{@link off }\`. + * + * **Cause**: These event binding methods have been deprecated in favor of the `.on()` and `.off()` methods which can handle both delegated and direct event binding. Although the older methods are still present in jQuery 3.0, they may be removed as early as the next major-version update. + * + * **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. + * @example ​ ````To unbind all delegated events from all paragraphs, write: +```javascript +$( "p" ).undelegate(); +``` + * @example ​ ````To unbind all delegated click events from all paragraphs, write: +```javascript +$( "p" ).undelegate( "click" ); +``` + * @example ​ ````To unbind all delegated events by their namespace: +```javascript +var foo = function() { + // Code to handle some kind of event +}; +​ +// Delegate events under the ".whatever" namespace +$( "form" ).delegate( ":button", "click.whatever", foo ); +​ +$( "form" ).delegate( "input[type='text'] ", "keypress.whatever", foo ); +​ +// Unbind all events delegated under the ".whatever" namespace +$( "form" ).undelegate( ".whatever" ); +``` + */ + undelegate(namespace?: string): this; + /** + * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. + * @param selector A selector to check the parent element against. If an element's parent does not match the selector, + * the element won't be unwrapped. + * @see \`{@link https://api.jquery.com/unwrap/ }\` + * @since 1.4 + * @since 3.0 + * @example ​ ````Wrap/unwrap a div around each of the paragraphs. +```html + + + + + unwrap demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      ​ + +​ + + +``` + */ + unwrap(selector?: string): this; + /** + * Set the value of each element in the set of matched elements. + * @param value_function _@param_ `value_function` + *
      + * * `value` — A string of text, a number, or an array of strings corresponding to the value of each matched + * element to set as selected/checked.
      + * * `function` — A function returning the value to set. `this` is the current element. Receives the index position of + * the element in the set and the old value as arguments. + * @see \`{@link https://api.jquery.com/val/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Set the value of an input box. +```html + + + + + val demo + + + + +​ +
      + + + +
      + +​ + +​ + + +``` + * @example ​ ````Use the function argument to modify the value of an input box. +```html + + + + + val demo + + + +​ +

      Type something and then click or tab out of the input.

      + +​ + +​ + + +``` + * @example ​ ````Set a single select, a multiple select, checkboxes and a radio button . +```html + + + + + val demo + + + + +​ + +​ + +​ +
      + check1 + check2 + radio1 + radio2 +​ + +​ + + +``` + */ + val(value_function: string | number | string[] | ((this: TElement, index: number, value: string) => string)): this; + /** + * Get the current value of the first element in the set of matched elements. + * @see \`{@link https://api.jquery.com/val/ }\` + * @since 1.0 + * @example ​ ````Get the single value from a single select and an array of values from a multiple select and display their values. +```html + + + + + val demo + + + + +​ +

      +​ + +​ + +​ + +​ + + +``` + * @example ​ ````Find the value of an input box. +```html + + + + + val demo + + + + +​ + +

      +​ + +​ + + +``` + */ + val(): string | number | string[] | undefined; + /** + * Set the CSS width of each element in the set of matched elements. + * @param value_function _@param_ `value_function` + *
      + * * `value` — An integer representing the number of pixels, or an integer along with an optional unit of measure + * appended (as a string).
      + * * `function` — A function returning the width to set. Receives the index position of the element in the set and the + * old width as arguments. Within the function, `this` refers to the current element in the set. + * @see \`{@link https://api.jquery.com/width/ }\` + * @since 1.0 + * @since 1.4.1 + * @example ​ ````Change the width of each div the first time it is clicked (and change its color). +```html + + + + + width demo + + + + +​ +
      d
      +
      d
      +
      d
      +
      d
      +
      d
      +​ + +​ + + +``` + */ + width(value_function: string | number | ((this: TElement, index: number, value: number) => string | number)): this; + /** + * Get the current computed width for the first element in the set of matched elements. + * @see \`{@link https://api.jquery.com/width/ }\` + * @since 1.0 + * @example ​ ````Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. +```html + + + + + width demo + + + + +​ + + + +
       
      +

      + Sample paragraph to test width +

      +​ + +​ + + +``` + */ + width(): number | undefined; + /** + * Wrap an HTML structure around each element in the set of matched elements. + * @param wrappingElement_function _@param_ `wrappingElement_function` + *
      + * * `wrappingElement` — A selector, element, HTML string, or jQuery object specifying the structure to wrap around the + * matched elements. When you pass a jQuery collection containing more than one element, or a selector + * matching more than one element, the first element will be used.
      + * * `function` — A callback function returning the HTML content or jQuery object to wrap around the matched elements. + * Receives the index position of the element in the set as an argument. Within the function, `this` + * refers to the current element in the set. + * @see \`{@link https://api.jquery.com/wrap/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Wrap a new div around all of the paragraphs. +```html + + + + + wrap demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.> +```html + + + + + wrap demo + + + + +​ +Span Text +What about me? +Another One +​ + +​ + + +``` + * @example ​ ````Wrap a new div around all of the paragraphs. +```html + + + + + wrap demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. +```html + + + + + wrap demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +
      +​ + +​ + + +``` + */ + wrap(wrappingElement_function: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery)): this; + /** + * Wrap an HTML structure around all elements in the set of matched elements. + * @param wrappingElement_function _@param_ `wrappingElement_function` + *
      + * * `wrappingElement` — A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements.
      + * * `function` — A callback function returning the HTML content or jQuery object to wrap around all the matched + * elements. Within the function, `this` refers to the first element in the set. **Prior to jQuery + * 3.0**, the callback was incorrectly called for every element in the set and received the index + * position of the element in the set as an argument. + * @see \`{@link https://api.jquery.com/wrapAll/ }\` + * @since 1.2 + * @since 1.4 + * @example ​ ````Wrap a new div around all of the paragraphs. +```html + + + + + wrapAll demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html. +```html + + + + + wrapAll demo + + + + +​ +Span Text +What about me? +Another One +​ + +​ + + +``` + * @example ​ ````Wrap a new div around all of the paragraphs. +```html + + + + + wrapAll demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. +```html + + + + + wrapAll demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +
      +​ + +​ + + +``` + */ + wrapAll(wrappingElement_function: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement) => string | JQuery)): this; + /** + * Wrap an HTML structure around the content of each element in the set of matched elements. + * @param wrappingElement_function _@param_ `wrappingElement_function` + *
      + * * `wrappingElement` — An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap + * around the content of the matched elements.
      + * * `function` — A callback function which generates a structure to wrap around the content of the matched elements. + * Receives the index position of the element in the set as an argument. Within the function, `this` + * refers to the current element in the set. + * @see \`{@link https://api.jquery.com/wrapInner/ }\` + * @since 1.2 + * @since 1.4 + * @example ​ ````Selects all paragraphs and wraps a bold tag around each of its contents. +```html + + + + + wrapInner demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Wraps a newly created tree of objects around the inside of the body. +```html + + + + + wrapInner demo + + + + +​ +Plain old text, or is it? +​ + +​ + + +``` + * @example ​ ````Selects all paragraphs and wraps a bold tag around each of its contents. +```html + + + + + wrapInner demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + * @example ​ ````Selects all paragraphs and wraps a jQuery object around each of its contents. +```html + + + + + wrapInner demo + + + + +​ +

      Hello

      +

      cruel

      +

      World

      +​ + +​ + + +``` + */ + wrapInner(wrappingElement_function: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery | Element)): this; + + [n: number]: TElement; +} diff --git a/types/jquery/JQueryStatic.d.ts b/types/jquery/JQueryStatic.d.ts new file mode 100644 index 0000000000..20d3a9e8c5 --- /dev/null +++ b/types/jquery/JQueryStatic.d.ts @@ -0,0 +1,13516 @@ +// tslint:disable:jsdoc-format +// tslint:disable:max-line-length +// tslint:disable:no-irregular-whitespace + +interface JQueryStatic { + /** + * @see \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax1 }\` + * @deprecated ​ Deprecated. Use \`{@link ajaxSetup }\`. + */ + ajaxSettings: JQuery.AjaxSettings; + Animation: JQuery.AnimationStatic; + Callbacks: JQuery.CallbacksStatic; + /** + * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize CSS property naming, or create custom properties. + * @see \`{@link https://api.jquery.com/jQuery.cssHooks/ }\` + * @since 1.4.3 + */ + cssHooks: JQuery.CSSHooks; + /** + * An object containing all CSS properties that may be used without a unit. The .css() method uses this object to see if it may append px to unitless values. + * @see \`{@link https://api.jquery.com/jQuery.cssNumber/ }\` + * @since 1.4.3 + */ + cssNumber: JQuery.PlainObject; + Deferred: JQuery.DeferredStatic; + easing: JQuery.Easings; + Event: JQuery.EventStatic; + /** + * @see \`{@link https://learn.jquery.com/events/event-extensions/ }\` + */ + event: JQuery.EventExtensions; + expr: JQuery.Selectors; + // Set to HTMLElement to minimize breaks but should probably be Element. + readonly fn: JQuery; + fx: JQuery.Effects; + /** + * A Promise-like object (or "thenable") that resolves when the document is ready. + * @see \`{@link https://api.jquery.com/jQuery.ready/ }\` + * @since 1.8 + * @example ​ ````Listen for document ready using jQuery.when. +```javascript +$.when( $.ready ).then(function() { + // Document is ready. +}); +``` + * @example ​ ````Typical usage involving another promise, using jQuery.when. +```javascript +$.when( + $.getJSON( "ajax/test.json" ), + $.ready +).done(function( data ) { + // Document is ready. + // Value of test.json is passed as `data`. +}); +``` + */ + ready: JQuery.Thenable; + /** + * A collection of properties that represent the presence of different browser features or bugs. Intended for jQuery's internal use; specific properties may be removed when they are no longer needed internally to improve page startup performance. For your own project's feature-detection needs, we strongly recommend the use of an external library such as Modernizr instead of dependency on properties in jQuery.support. + * @see \`{@link https://api.jquery.com/jQuery.support/ }\` + * @since 1.3 + * @deprecated ​ Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. + */ + support: JQuery.PlainObject; + timers: Array>; + Tween: JQuery.TweenStatic; + valHooks: JQuery.ValHooks; + // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. + // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. + (window: Window, discriminator: boolean): JQueryStatic; + /** + * Creates DOM elements on the fly from the provided string of raw HTML. + * @param html _@param_ `html` + *
      + * * `html (ownerDocument)` — A string of HTML to create on the fly. Note that this parses HTML, not XML.
      + * * `html (attributes)` — A string defining a single, standalone, HTML element (e.g. <div/> or <div></div>). + * @param ownerDocument_attributes _@param_ `ownerDocument_attributes` + *
      + * * `ownerDocument` — A document in which the new elements will be created.
      + * * `attributes` — An object of attributes, events, and methods to call on the newly-created element. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + * @since 1.4 + * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. +```javascript +$( "

      Hello

      " ).appendTo( "body" ) +``` + * @example ​ ````Create some DOM elements. +```javascript +$( "
      ", { + "class": "test", + text: "Click me!", + click: function() { + $( this ).toggleClass( "test" ); + } +}) + .appendTo( "body" ); +``` + */ + // tslint:disable-next-line:no-unnecessary-generics + (html: JQuery.htmlString, ownerDocument_attributes?: Document | JQuery.PlainObject): JQuery; + /** + * Accepts a string containing a CSS selector which is then used to match a set of elements. + * @param selector A string containing a selector expression + * @param context A DOM Element, Document, or jQuery to use as context + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + * @example ​ ````Find all p elements that are children of a div element and apply a border to them. +```html + + + + + jQuery demo + + + +​ +

      one

      +

      two

      +

      three

      +​ + + + +``` + * @example ​ ````Find all inputs of type radio within the first form in the document. +```javascript +$( "input:radio", document.forms[ 0 ] ); +``` + * @example ​ ````Find all div elements within an XML document from an Ajax response. +```javascript +$( "div", xml.responseXML ); +``` +​ + */ + // tslint:disable-next-line:no-unnecessary-generics + (selector: JQuery.Selector, context?: Element | Document | JQuery): 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 element A DOM element 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" ); +``` + */ + // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) + (element: T): 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. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + * @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; + /** + * 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. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + */ + (selection: JQuery): JQuery; + /** + * Binds a function to be executed when the DOM has finished loading. + * @param callback The function to execute when the DOM is ready. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + * @example ​ ````Execute the function when the DOM is ready to be used. +```javascript +$(function() { + // Document is ready +}); +``` + * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. +```javascript +jQuery(function( $ ) { + // Your code using failsafe $ alias here... +}); +``` + */ + // tslint:disable-next-line:no-unnecessary-generics unified-signatures + (callback: ((this: Document, $: JQueryStatic) => void)): 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 object A plain object to wrap in a jQuery object. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.0 + */ + (object: T): JQuery; + /** + * Returns an empty jQuery set. + * @see \`{@link https://api.jquery.com/jQuery/ }\` + * @since 1.4 + */ + // tslint:disable-next-line:no-unnecessary-generics + (): JQuery; + /** + * Perform an asynchronous HTTP (Ajax) request. + * @param url A string containing the URL to which the request is sent. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can + * be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. + * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` + * @since 1.5 + */ + ajax(url: string, settings?: JQuery.AjaxSettings): JQuery.jqXHR; + /** + * Perform an asynchronous HTTP (Ajax) request. + * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can + * be set for any option with $.ajaxSetup(). + * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` + * @since 1.0 + * @example ​ ````Save some data to the server and notify the user once it's complete. +```javascript +$.ajax({ + method: "POST", + url: "some.php", + data: { name: "John", location: "Boston" } +}) + .done(function( msg ) { + alert( "Data Saved: " + msg ); + }); +``` + * @example ​ ````Retrieve the latest version of an HTML page. +```javascript +$.ajax({ + url: "test.html", + cache: false +}) + .done(function( html ) { + $( "#results" ).append( html ); + }); +``` + * @example ​ ````Send an xml document as data to the server. By setting the processData + option to false, the automatic conversion of data to strings is prevented. +```javascript +var xmlDocument = [create xml document]; +var xmlRequest = $.ajax({ + url: "page.php", + processData: false, + data: xmlDocument +}); +​ +xmlRequest.done( handleResponse ); +``` + * @example ​ ````Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user. +```javascript +var menuId = $( "ul.nav" ).first().attr( "id" ); +var request = $.ajax({ + url: "script.php", + method: "POST", + data: { id : menuId }, + dataType: "html" +}); +​ +request.done(function( msg ) { + $( "#log" ).html( msg ); +}); +​ +request.fail(function( jqXHR, textStatus ) { + alert( "Request failed: " + textStatus ); +}); +``` + * @example ​ ````Load and execute a JavaScript file. +```javascript +$.ajax({ + method: "GET", + url: "test.js", + dataType: "script" +}); +``` + */ + ajax(settings?: JQuery.AjaxSettings): JQuery.jqXHR; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * @param dataTypes An optional string containing one or more space-separated dataTypes + * @param handler A handler to set default values for future Ajax requests. + * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` + * @since 1.5 + */ + ajaxPrefilter(dataTypes: string, + handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; + /** + * Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). + * @param handler A handler to set default values for future Ajax requests. + * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` + * @since 1.5 + */ + ajaxPrefilter(handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; + /** + * Set default values for future Ajax requests. Its use is not recommended. + * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. + * @see \`{@link https://api.jquery.com/jQuery.ajaxSetup/ }\` + * @since 1.1 + * @example ​ ````Sets the defaults for Ajax requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else. +```javascript +$.ajaxSetup({ + url: "/xmlhttp/", + global: false, + type: "POST" +}); +$.ajax({ data: myData }); +``` + */ + ajaxSetup(options: JQuery.AjaxSettings): JQuery.AjaxSettings; + /** + * Creates an object that handles the actual transmission of Ajax data. + * @param dataType A string identifying the data type to use + * @param handler A handler to return the new transport object to use with the data type provided in the first argument. + * @see \`{@link https://api.jquery.com/jQuery.ajaxTransport/ }\` + * @since 1.5 + */ + ajaxTransport(dataType: string, + handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => JQuery.Transport | void): void; + /** + * @deprecated ​ Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3384 }\`. + */ + camelCase(value: string): string; + cleanData(elems: ArrayLike): void; + /** + * Check to see if a DOM element is a descendant of another DOM element. + * @param container The DOM element that may contain the other element. + * @param contained The DOM element that may be contained by (a descendant of) the other element. + * @see \`{@link https://api.jquery.com/jQuery.contains/ }\` + * @since 1.4 + * @example ​ ````Check if an element is a descendant of another. +```javascript +$.contains( document.documentElement, document.body ); // true +$.contains( document.body, document.documentElement ); // false +``` + */ + contains(container: Element, contained: Element): boolean; + css(elem: Element, name: string): any; + /** + * Store arbitrary data associated with the specified element. Returns the value that was set. + * @param element The DOM element to associate with the data. + * @param key A string naming the piece of data to set. + * @param value The new data value; this can be any Javascript type except `undefined`. + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` + * @since 1.2.3 + * @example ​ ````Get the data named "blah" stored at for an element. +```html + + + + + jQuery.data demo + + + + +​ +
      A div
      + + + + +

      The "blah" value of this div is ?

      +​ + +​ + + +``` + */ + data(element: Element | Document | Window | JQuery.PlainObject, key: string, value: T): T; + /** + * Returns value at named data store for the element, as set by `jQuery.data(element, name, value)`, or the full data store for the element. + * @param element The DOM element to query for the data. + * @param key Name of the data stored. + * @param value `undefined` is not recognized as a data value. Calls such as `jQuery.data( el, "name", undefined )` + * will return the corresponding data for "name", and is therefore the same as `jQuery.data( el, "name" )` + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` + * @since 1.2.3 + */ + // `unified-signatures` is disabled so that behavior when passing `undefined` to `value` can be documented. Unifying the signatures + // results in potential confusion for users from an unexpected parameter. + // tslint:disable-next-line:unified-signatures + data(element: Element | Document | Window | JQuery.PlainObject, key: string, value: undefined): any; + /** + * Returns value at named data store for the element, as set by `jQuery.data(element, name, value)`, or the full data store for the element. + * @param element The DOM element to query for the data. + * @param key Name of the data stored. + * @see \`{@link https://api.jquery.com/jQuery.data/ }\` + * @since 1.2.3 + * @since 1.4 + * @example ​ ````Store then retrieve a value from the div element. +```html + + + + + jQuery.data demo + + + + +​ +
      + The values stored were + + and + +
      +​ + +​ + + +``` + */ + data(element: Element | Document | Window | JQuery.PlainObject, key?: string): any; + /** + * Execute the next function on the queue for the matched element. + * @param element A DOM element from which to remove and execute a queued function. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @see \`{@link https://api.jquery.com/jQuery.dequeue/ }\` + * @since 1.3 + * @example ​ ````Use jQuery.dequeue() to end a custom queue function which allows the queue to keep going. +```html + + + + + jQuery.dequeue demo + + + + +​ + +
      +​ + +​ + + +``` + */ + dequeue(element: Element, queueName?: string): void; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * @param array The array to iterate over. + * @param callback The function that will be executed on every object. + * @see \`{@link https://api.jquery.com/jQuery.each/ }\` + * @since 1.0 + * @example ​ ````Iterates through the array displaying each number as both a word and numeral +```html + + + + + jQuery.each demo + + + + +​ +
      +
      +
      +
      +
      +​ + +​ + + +``` + * @example ​ ````Iterates over items in an array, accessing both the current item and its index. +```javascript +$.each( [ "a", "b", "c" ], function( i, l ){ + alert( "Index #" + i + ": " + l ); +}); +``` + */ + each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => any): ArrayLike; + /** + * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. Arrays and array-like objects with a length property (such as a function's arguments object) are iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. + * @param obj The object to iterate over. + * @param callback The function that will be executed on every object. + * @see \`{@link https://api.jquery.com/jQuery.each/ }\` + * @since 1.0 + * @example ​ ````Iterates through the array displaying each number as both a word and numeral +```html + + + + + jQuery.each demo + + + + +​ +
      +
      +
      +
      +
      +​ + +​ + + +``` + * @example ​ ````Iterates over the properties in an object, accessing both the current item and its key. +```javascript +$.each({ name: "John", lang: "JS" }, function( k, v ) { + alert( "Key: " + k + ", Value: " + v ); +}); +``` + */ + each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => any): T; + /** + * Takes a string and throws an exception containing it. + * @param message The message to send out. + * @see \`{@link https://api.jquery.com/jQuery.error/ }\` + * @since 1.4.1 + * @example ​ ````Override jQuery.error for display in Firebug. +```javascript +jQuery.error = console.error; +``` + */ + error(message: string): any; + /** + * Escapes any character that has a special meaning in a CSS selector. + * @param selector A string containing a selector expression to escape. + * @see \`{@link https://api.jquery.com/jQuery.escapeSelector/ }\` + * @since 3.0 + * @example ​ ````Escape an ID containing a hash. +```javascript +$.escapeSelector( "#target" ); // "\#target" +``` + * @example ​ ````Select all the elements having a class name of .box inside a div. +```javascript +$( "div" ).find( "." + $.escapeSelector( ".box" ) ); +``` + */ + escapeSelector(selector: JQuery.Selector): JQuery.Selector; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @param object5 An object containing additional properties to merge in. + * @param object6 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @param object5 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U, object2: V, object3: W): T & U & V & W; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U, object2: V): T & U & V; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: T, object1: U): T & U; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + */ + extend(deep: true, target: T): this & T; + /** + * Merge the contents of two or more objects together into the first object. + * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. + * @param target The object to extend. It will receive the new properties. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.1.4 + * @example ​ ````Merge two objects recursively, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(deep: true, target: any, object1: any, ...objectN: any[]): any; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @param object5 An object containing additional properties to merge in. + * @param object6 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @param object5 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @param object4 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @param object3 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U, object2: V, object3: W): T & U & V & W; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param object2 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U, object2: V): T & U & V; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: T, object1: U): T & U; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + */ + extend(target: T): this & T; + /** + * Merge the contents of two or more objects together into the first object. + * @param target An object that will receive the new properties if additional objects are passed in or that will + * extend the jQuery namespace if it is the sole argument. + * @param object1 An object containing additional properties to merge in. + * @param objectN Additional objects containing properties to merge in. + * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` + * @since 1.0 + * @example ​ ````Merge two objects, modifying the first. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. +```html + + + + + jQuery.extend demo + + + +​ +
      +​ + +​ + + +``` + */ + extend(target: any, object1: any, ...objectN: any[]): any; + /** + * Load data from the server using a HTTP GET request. + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` + * @since 1.0 + */ + get(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback | null, + dataType?: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` + * @since 1.0 + * @example ​ ````Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. +```javascript +$.get( "test.php", function( data ) { + $( "body" ) + .append( "Name: " + data.name ) // John + .append( "Time: " + data.time ); // 2pm +}, "json" ); +``` + */ + get(url: string, + success: JQuery.jqXHR.DoneCallback | null, + dataType: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * @param url A string containing the URL to which the request is sent. + * @param success_data _@param_ `success_data` + *
      + * * `success` — A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but you can use `null` or \`{@link noop jQuery.noop}\` as a placeholder.
      + * * `data` — A plain object or string that is sent to the server with the request. + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` + * @since 1.0 + * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). +```javascript +$.get( "test.php", { name: "John", time: "2pm" } ); +``` + * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). +```javascript +$.get( "test.php", { "choices[]": ["Jon", "Susan"] } ); +``` + * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). +```javascript +$.get( "test.php", function( data ) { + alert( "Data Loaded: " + data ); +}); +``` + * @example ​ ````Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). +```javascript +$.get( "test.cgi", { name: "John", time: "2pm" } ) + .done(function( data ) { + alert( "Data Loaded: " + data ); + }); +``` + */ + get(url: string, + success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP GET request. + * @param url_settings _@param_ `url_settings` + *
      + * * `url` — A string containing the URL to which the request is sent.
      + * * `settings` — A set of key/value pairs that configure the Ajax request. All properties except for `url` are + * optional. A default can be set for any option with \`{@link ajaxSetup $.ajaxSetup()}\`. See \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings jQuery.ajax( settings )}\` + * for a complete list of all settings. The type option will automatically be set to `GET`. + * @see \`{@link https://api.jquery.com/jQuery.get/ }\` + * @since 1.0 + * @since 1.12 + * @since 2.2 + * @example ​ ````Request the test.php page, but ignore the return results. +```javascript +$.get( "test.php" ); +``` + */ + get(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. + * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` + * @since 1.0 + */ + getJSON(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; + /** + * Load JSON-encoded data from the server using a GET HTTP request. + * @param url A string containing the URL to which the request is sent. + * @param success_data _@param_ `url_settings` + *
      + * * `success` — A callback function that is executed if the request succeeds.
      + * * `data` — A plain object or string that is sent to the server with the request. + * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` + * @since 1.0 + * @example ​ ````Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API. +```html + + + + + jQuery.getJSON demo + + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Load the JSON data from test.js and access a name from the returned JSON data. +```javascript +$.getJSON( "test.js", function( json ) { + console.log( "JSON Data: " + json.users[ 3 ].name ); + }); + ``` + * @example ​ ````Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. + If an error occurs, log an error message instead. +```javascript +$.getJSON( "test.js", { name: "John", time: "2pm" } ) + .done(function( json ) { + console.log( "JSON Data: " + json.users[ 3 ].name ); + }) + .fail(function( jqxhr, textStatus, error ) { + var err = textStatus + ", " + error; + console.log( "Request Failed: " + err ); +}); +``` + */ + getJSON(url: string, + success_data?: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. + * @see \`{@link https://api.jquery.com/jQuery.getScript/ }\` + * @since 1.0 + * @example ​ ````Define a $.cachedScript() method that allows fetching a cached script: +```javascript +jQuery.cachedScript = function( url, options ) { +​ + // Allow user to set any option except for dataType, cache, and url + options = $.extend( options || {}, { + dataType: "script", + cache: true, + url: url + }); +​ + // Use $.ajax() since it is more flexible than $.getScript + // Return the jqXHR object so we can chain callbacks + return jQuery.ajax( options ); +}; +​ +// Usage +$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) { + console.log( textStatus ); +}); +``` + * @example ​ ````Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded. +```html + + + + + jQuery.getScript demo + + + + +​ + +
      +​ + +​ + + +``` + */ + getScript(url: string, + success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; + /** + * Load a JavaScript file from the server using a GET HTTP request, then execute it. + * @see \`{@link https://api.jquery.com/jQuery.getScript/ }\` + * @since 1.12 + * @since 2.2 + */ + getScript(options: JQuery.UrlAjaxSettings): JQuery.jqXHR; + /** + * Execute some JavaScript code globally. + * @param code The JavaScript code to execute. + * @see \`{@link https://api.jquery.com/jQuery.globalEval/ }\` + * @since 1.0.4 + * @example ​ ````Execute a script in the global context. +```javascript +function test() { + jQuery.globalEval( "var newVar = true;" ) +} +test(); +// newVar === true +``` + */ + globalEval(code: string): void; + /** + * Finds the elements of an array which satisfy a filter function. The original array is not affected. + * @param array The array-like object to search through. + * @param funсtion The function to process each item against. The first argument to the function is the item, and the + * second argument is the index. The function should return a Boolean value. `this` will be the global + * window object. + * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements + * for which "callback" returns true. If "invert" is true, then the function returns an array + * consisting of all elements for which "callback" returns false. + * @see \`{@link https://api.jquery.com/jQuery.grep/ }\` + * @since 1.0 + * @example ​ ````Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s. +```html + + + + + jQuery.grep demo + + + + +​ +
      +

      + +​ + +​ + + +``` + * @example ​ ````Filter an array of numbers to include only numbers bigger then zero. +```javascript +$.grep( [ 0, 1, 2 ], function( n, i ) { + return n > 0; +}); +``` + * @example ​ ````Filter an array of numbers to include numbers that are not bigger than zero. +```javascript +$.grep( [ 0, 1, 2 ], function( n, i ) { + return n > 0; +}, true ); +``` + */ + grep(array: ArrayLike, + funсtion: (elementOfArray: T, indexInArray: number) => boolean, + invert?: boolean): T[]; + /** + * Determine whether an element has any jQuery data associated with it. + * @param element A DOM element to be checked for data. + * @see \`{@link https://api.jquery.com/jQuery.hasData/ }\` + * @since 1.5 + * @example ​ ````Set data on an element and see the results of hasData. +```html + + + + + jQuery.hasData demo + + + +​ +

      Results:

      +​ + +​ + + +``` + */ + hasData(element: Element | Document | Window | JQuery.PlainObject): boolean; + /** + * Holds or releases the execution of jQuery's ready event. + * @param hold Indicates whether the ready hold is being requested or released + * @see \`{@link https://api.jquery.com/jQuery.holdReady/ }\` + * @since 1.6 + * @deprecated ​ Deprecated since 3.2. See \`{@link https://github.com/jquery/jquery/issues/3288 }\`. + * + * **Cause**: The `jQuery.holdReady()` method has been deprecated due to its detrimental effect on the global performance of the page. This method can prevent all the code on the page from initializing for extended lengths of time. + * + * **Solution**: Rewrite the page so that it does not require all jQuery ready handlers to be delayed. This might be accomplished, for example, by late-loading only the code that requires the delay when it is safe to run. Due to the complexity of this method, jQuery Migrate does not attempt to fill the functionality. If the underlying version of jQuery used with jQuery Migrate no longer contains `jQuery.holdReady()` the code will fail shortly after this warning appears. + * @example ​ ````Delay the ready event until a custom plugin has loaded. +```javascript +$.holdReady( true ); +$.getScript( "myplugin.js", function() { + $.holdReady( false ); +}); +``` + */ + holdReady(hold: boolean): void; + /** + * Modify and filter HTML strings passed through jQuery manipulation methods. + * @param html The HTML string on which to operate. + * @see \`{@link https://api.jquery.com/jQuery.htmlPrefilter/ }\` + * @since 1.12 + * @since 2.2 + */ + htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; + /** + * Search for a specified value within an array and return its index (or -1 if not found). + * @param value The value to search for. + * @param array An array through which to search. + * @param fromIndex The index of the array at which to begin the search. The default is 0, which will search the whole array. + * @see \`{@link https://api.jquery.com/jQuery.inArray/ }\` + * @since 1.2 + * @example ​ ````Report the index of some elements in the array. +```html + + + + + jQuery.inArray demo + + + + +​ +
      "John" found at
      +
      4 found at
      +
      "Karl" not found, so
      +
      "Pete" is in the array, but not at or after index 2, so
      +​ + +​ + + +``` + */ + inArray(value: T, array: T[], fromIndex?: number): number; + /** + * Determine whether the argument is an array. + * @param obj Object to test whether or not it is an array. + * @see \`{@link https://api.jquery.com/jQuery.isArray/ }\` + * @since 1.3 + * @deprecated ​ Deprecated since 3.2. Use \`{@link ArrayConstructor.isArray Array.isArray}\`. + * @example ​ ````Finds out if the parameter is an array. +```html + + + + + jQuery.isArray demo + + + +​ +Is [] an Array? +​ + +​ + + +``` + */ + isArray(obj: any): obj is any[]; + /** + * Check to see if an object is empty (contains no enumerable properties). + * @param obj The object that will be checked to see if it's empty. + * @see \`{@link https://api.jquery.com/jQuery.isEmptyObject/ }\` + * @since 1.4 + * @example ​ ````Check an object to see if it's empty. +```javascript +jQuery.isEmptyObject({}); // true +jQuery.isEmptyObject({ foo: "bar" }); // false +``` + */ + isEmptyObject(obj: any): boolean; + /** + * Determine if the argument passed is a JavaScript function object. + * @param obj Object to test whether or not it is a function. + * @see \`{@link https://api.jquery.com/jQuery.isFunction/ }\` + * @since 1.2 + * @deprecated ​ Deprecated since 3.3. Use `typeof x === "function"`. + * @example ​ ````Test a few parameter examples. +```html + + + + + jQuery.isFunction demo + + + + +​ +
      jQuery.isFunction( objs[ 0 ] ) =
      +
      jQuery.isFunction( objs[ 1 ] ) =
      +
      jQuery.isFunction( objs[ 2 ] ) =
      +
      jQuery.isFunction( objs[ 3 ] ) =
      +
      jQuery.isFunction( objs[ 4 ] ) =
      +​ + +​ + + +``` + * @example ​ ````Finds out if the parameter is a function. +```javascript +$.isFunction(function() {}); +``` + */ + // tslint:disable-next-line:ban-types + isFunction(obj: any): obj is Function; + /** + * Determines whether its argument represents a JavaScript number. + * @param value The value to be tested. + * @see \`{@link https://api.jquery.com/jQuery.isNumeric/ }\` + * @since 1.7 + * @deprecated ​ Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/2960 }\`. + * @example ​ ````Sample return values of $.isNumeric with various inputs. +```javascript +// true (numeric) +$.isNumeric( "-10" ) +$.isNumeric( "0" ) +$.isNumeric( 0xFF ) +$.isNumeric( "0xFF" ) +$.isNumeric( "8e5" ) +$.isNumeric( "3.1415" ) +$.isNumeric( +10 ) +$.isNumeric( 0144 ) +​ +// false (non-numeric) +$.isNumeric( "-0x42" ) +$.isNumeric( "7.2acdgs" ) +$.isNumeric( "" ) +$.isNumeric( {} ) +$.isNumeric( NaN ) +$.isNumeric( null ) +$.isNumeric( true ) +$.isNumeric( Infinity ) +$.isNumeric( undefined ) +``` + */ + isNumeric(value: any): boolean; + /** + * Check to see if an object is a plain object (created using "{}" or "new Object"). + * @param obj The object that will be checked to see if it's a plain object. + * @see \`{@link https://api.jquery.com/jQuery.isPlainObject/ }\` + * @since 1.4 + * @example ​ ````Check an object to see if it's a plain object. +```javascript +jQuery.isPlainObject({}) // true +jQuery.isPlainObject( "test" ) // false +``` + */ + isPlainObject(obj: any): boolean; + /** + * Determine whether the argument is a window. + * @param obj Object to test whether or not it is a window. + * @see \`{@link https://api.jquery.com/jQuery.isWindow/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3629 }\`. + * + * **Cause**: This method returns `true` if its argument is thought to be a `window` element. It was created for internal use and is not a reliable way of detecting `window` for public needs. + * + * **Solution**: Remove any use of `jQuery.isWindow()` from code. If it is truly needed it can be replaced with a check for `obj != null && obj === obj.window` which was the test used inside this method. + * @example ​ ````Finds out if the parameter is a window. +```html + + + + + jQuery.isWindow demo + + + +​ +Is 'window' a window? +​ + +​ + + +``` + */ + isWindow(obj: any): obj is Window; + /** + * Check to see if a DOM node is within an XML document (or is an XML document). + * @param node The DOM node that will be checked to see if it's in an XML document. + * @see \`{@link https://api.jquery.com/jQuery.isXMLDoc/ }\` + * @since 1.1.4 + * @example ​ ````Check an object to see if it's in an XML document. +```javascript +jQuery.isXMLDoc( document ) // false +jQuery.isXMLDoc( document.body ) // false +``` + */ + isXMLDoc(node: Node): boolean; + /** + * Convert an array-like object into a true JavaScript array. + * @param obj Any object to turn into a native Array. + * @see \`{@link https://api.jquery.com/jQuery.makeArray/ }\` + * @since 1.2 + * @example ​ ````Turn a collection of HTMLElements into an Array of them. +```html + + + + + jQuery.makeArray demo + + + + +​ +
      First
      +
      Second
      +
      Third
      +
      Fourth
      +​ + +​ + + +``` + * @example ​ ````Turn a jQuery object into an array +```javascript +var obj = $( "li" ); +var arr = $.makeArray( obj ); +``` + */ + makeArray(obj: ArrayLike): T[]; + /** + * Translate all items in an array or object to new array of items. + * @param array The Array to translate. + * @param callback The function to process each item against. The first argument to the function is the array item, the + * second argument is the index in array The function can return any value. A returned array will be + * flattened into the resulting array. Within the function, this refers to the global (window) object. + * @see \`{@link https://api.jquery.com/jQuery.map/ }\` + * @since 1.0 + * @example ​ ````Use $.map() to change the values of an array. +```html + + + + + jQuery.map demo + + + + +​ +
      +

      + +​ + +​ + + +``` + * @example ​ ````Map the original array to a new one and add 4 to each value. +```javascript +$.map( [ 0, 1, 2 ], function( n ) { + return n + 4; +}); +``` + * @example ​ ````Map the original array to a new one, adding 1 to each value if it is bigger then zero and removing it if not. +```javascript +$.map( [ 0, 1, 2 ], function( n ) { + return n > 0 ? n + 1 : null; +}); +``` + * @example ​ ````Map the original array to a new one; each element is added with its original value and the value plus one. +```javascript +$.map( [ 0, 1, 2 ], function( n ) { + return [ n, n + 1 ]; +}); +``` + * @example ​ ````Map the original array to a new one; each element is squared. +```javascript +$.map( [ 0, 1, 2, 3 ], function( a ) { + return a * a; +}); +``` + * @example ​ ````Map the original array to a new one, removing numbers less than 50 by returning null and subtracting 45 from the rest. +```javascript +$.map( [ 0, 1, 52, 97 ], function( a ) { + return (a > 50 ? a - 45 : null); +}); +``` + * @example ​ ````Augment the resulting array by returning an array inside the function. +```javascript +var array = [ 0, 1, 52, 97 ]; +array = $.map( array, function( a, index ) { + return [ a - 45, index ]; +}); +``` + */ + map(array: T[], callback: (this: Window, elementOfArray: T, indexInArray: number) => JQuery.TypeOrArray | null | undefined): TReturn[]; + /** + * Translate all items in an array or object to new array of items. + * @param obj The Object to translate. + * @param callback The function to process each item against. The first argument to the function is the value; the + * second argument is the key of the object property. The function can return any value to add to the + * array. A returned array will be flattened into the resulting array. Within the function, this refers + * to the global (window) object. + * @see \`{@link https://api.jquery.com/jQuery.map/ }\` + * @since 1.6 + * @example ​ ````Map the original object to a new array and double each value. +```javascript +var dimensions = { width: 10, height: 15, length: 20 }; +dimensions = $.map( dimensions, function( value, index ) { + return value * 2; +}); +``` + * @example ​ ````Map an object's keys to an array. +```javascript +var dimensions = { width: 10, height: 15, length: 20 }; +var keys = $.map( dimensions, function( value, key ) { + return key; +}); +``` + */ + map(obj: T, callback: (this: Window, propertyOfObject: T[K], key: K) => JQuery.TypeOrArray | null | undefined): TReturn[]; + /** + * Merge the contents of two arrays together into the first array. + * @param first The first array-like object to merge, the elements of second added. + * @param second The second array-like object to merge into the first, unaltered. + * @see \`{@link https://api.jquery.com/jQuery.merge/ }\` + * @since 1.0 + * @example ​ ````Merges two arrays, altering the first argument. +```javascript +$.merge( [ 0, 1, 2 ], [ 2, 3, 4 ] ) +``` + * @example ​ ````Merges two arrays, altering the first argument. +```javascript +$.merge( [ 3, 2, 1 ], [ 4, 3, 2 ] ) +``` + * @example ​ ````Merges two arrays, but uses a copy, so the original isn't altered. +```javascript +var first = [ "a", "b", "c" ]; +var second = [ "d", "e", "f" ]; +$.merge( $.merge( [], first ), second ); +``` + */ + merge(first: ArrayLike, second: ArrayLike): Array; + /** + * Relinquish jQuery's control of the $ variable. + * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). + * @see \`{@link https://api.jquery.com/jQuery.noConflict/ }\` + * @since 1.0 + * @example ​ ````Map the original object that was referenced by $ back to $. +```javascript +jQuery.noConflict(); +// Do something with jQuery +jQuery( "div p" ).hide(); +// Do something with another library's $() +$( "content" ).style.display = "none"; +``` + * @example ​ ````Revert the $ alias and then create and execute a function to provide the $ as a jQuery alias inside the function's scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library. +```javascript +jQuery.noConflict(); +(function( $ ) { + $(function() { + // More code using $ as alias to jQuery + }); +})(jQuery); +​ +// Other code using $ as an alias to the other library +``` + * @example ​ ````Create a different alias instead of jQuery to use in the rest of the script. +```javascript +var j = jQuery.noConflict(); +​ +// Do something with jQuery +j( "div p" ).hide(); +​ +// Do something with another library's $() +$( "content" ).style.display = "none"; +``` + * @example ​ ````Completely move jQuery to a new namespace in another object. +```javascript +var dom = {}; +dom.query = jQuery.noConflict( true ); +``` + * @example ​ ````Load two versions of jQuery (not recommended). Then, restore jQuery's globally scoped variables to the first loaded jQuery. +```html + + + + + jQuery.noConflict demo + + + +​ +
      +

      Before $.noConflict(true)

      +
      + +​ + +​ + + +``` + */ + noConflict(removeAll?: boolean): this; + /** + * @deprecated ​ Deprecated since 3.2. + * + * **Cause**: This public but never-documented method has been deprecated as of jQuery 3.2.0. + * + * **Solution**: Replace calls such as `jQuery.nodeName( elem, "div" )` with a test such as `elem.nodeName.toLowerCase() === "div"`. + */ + nodeName(elem: Node, name: string): boolean; + /** + * An empty function. + * @see \`{@link https://api.jquery.com/jQuery.noop/ }\` + * @since 1.4 + */ + noop(): undefined; + /** + * Return a number representing the current time. + * @see \`{@link https://api.jquery.com/jQuery.now/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.3. Use \`{@link DateConstructor.now Date.now}\`. + */ + now(): number; + /** + * Create a serialized representation of an array, a plain object, or a jQuery object suitable for use in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input elements with name/value properties. + * @param obj An array, a plain object, or a jQuery object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + * @see \`{@link https://api.jquery.com/jQuery.param/ }\` + * @since 1.2 + * @since 1.4 + * @example ​ ````Serialize a key/value object. +```html + + + + + jQuery.param demo + + + + +​ +
      +​ + +​ + + +``` + * @example ​ ````Serialize a few complex objects +```html + + + + + jQuery.param demo + + + + +​​ + +​ + + +``` + */ + param(obj: any[] | JQuery.PlainObject | JQuery, traditional?: boolean): string; + /** + * Parses a string into an array of DOM nodes. + * @param data HTML string to be parsed + * @param context Document element to serve as the context in which the HTML fragment will be created + * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string + * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` + * @since 1.8 + */ + parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; + /** + * Parses a string into an array of DOM nodes. + * @param data HTML string to be parsed + * @param context_keepScripts _@param_ `context_keepScripts` + *
      + * * `context` — Document element to serve as the context in which the HTML fragment will be created
      + * * `keepScripts` — A Boolean indicating whether to include scripts passed in the HTML string + * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` + * @since 1.8 + * @example ​ ````Create an array of DOM nodes using an HTML string and insert it into a div. +```html + + + + + jQuery.parseHTML demo + + + +​ +
      +

      Content:

      +
      +​ + +​ + + +``` + */ + parseHTML(data: string, context_keepScripts?: Document | null | boolean): JQuery.Node[]; + /** + * Takes a well-formed JSON string and returns the resulting JavaScript value. + * @param json The JSON string to parse. + * @see \`{@link https://api.jquery.com/jQuery.parseJSON/ }\` + * @since 1.4.1 + * @deprecated ​ Deprecated since 3.0. Use \`{@link JSON.parse }\`. + * + * **Cause**: The `jQuery.parseJSON` method in recent jQuery is identical to the native `JSON.parse`. As of jQuery 3.0 `jQuery.parseJSON` is deprecated. + * + * **Solution**: Replace any use of `jQuery.parseJSON` with `JSON.parse`. + * @example ​ ````Parse a JSON string. +```javascript +var obj = jQuery.parseJSON( '{ "name": "John" }' ); +alert( obj.name === "John" ); +``` + */ + parseJSON(json: string): any; + /** + * Parses a string into an XML document. + * @param data a well-formed XML string to be parsed + * @see \`{@link https://api.jquery.com/jQuery.parseXML/ }\` + * @since 1.5 + * @example ​ ````Create a jQuery object using an XML string and obtain the value of the title node. +```html + + + + + jQuery.parseXML demo + + + +​ +

      +

      +​ + +​ + + +``` + */ + parseXML(data: string): XMLDocument; + /** + * Load data from the server using a HTTP POST request. + * @param url A string containing the URL to which the request is sent. + * @param data A plain object or string that is sent to the server with the request. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` + * @since 1.0 + * @example ​ ````Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). +```javascript +$.post( "test.php", { func: "getNameAndTime" }, function( data ) { + console.log( data.name ); // John + console.log( data.time ); // 2pm +}, "json"); +``` + */ + post(url: string, + data: JQuery.PlainObject | string, + success: JQuery.jqXHR.DoneCallback | null, + dataType?: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * @param url A string containing the URL to which the request is sent. + * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but + * can be null in that case. + * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` + * @since 1.0 + */ + post(url: string, + success: JQuery.jqXHR.DoneCallback | null, + dataType: string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * @param url A string containing the URL to which the request is sent. + * @param success_data _@param_ `success_data` + *
      + * * `success` — A callback function that is executed if the request succeeds. Required if `dataType` is provided, + * but can be `null` in that case.
      + * * `data` — A plain object or string that is sent to the server with the request. + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` + * @since 1.0 + * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). +```javascript +$.post( "test.php", { name: "John", time: "2pm" } ); +``` + * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). +```javascript +$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } ); +``` + * @example ​ ````Send form data using Ajax requests +```javascript +$.post( "test.php", $( "#testform" ).serialize() ); +``` + * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). +```javascript +$.post( "test.php", function( data ) { + alert( "Data Loaded: " + data ); +}); +``` + * @example ​ ````Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). +```javascript +$.post( "test.php", { name: "John", time: "2pm" }) + .done(function( data ) { + alert( "Data Loaded: " + data ); + }); +``` + * @example ​ ````Post a form using Ajax and put results in a div +```html + + + + + jQuery.post demo + + + +​ +
      + + +
      + +
      +​ + +​ + + +``` + */ + post(url: string, + success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; + /** + * Load data from the server using a HTTP POST request. + * @param url_settings _@param_ `url_settings` + *
      + * * `url` — A string containing the URL to which the request is sent.
      + * * `settings` — A set of key/value pairs that configure the Ajax request. All properties except for `url` are optional. + * A default can be set for any option with \`{@link ajaxSetup $.ajaxSetup()}\`. See \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings jQuery.ajax( settings )}\` + * for a complete list of all settings. Type will automatically be set to `POST`. + * @see \`{@link https://api.jquery.com/jQuery.post/ }\` + * @since 1.0 + * @since 1.12 + * @since 2.2 + * @example ​ ````Request the test.php page, but ignore the return results. +```javascript +$.post( "test.php" ); +``` + */ + post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; + + // region proxy + // #region proxy + + // region (funсtion, null | undefined) + // #region (funсtion, null | undefined) + + // region 0 to 7 additional arguments + // #region 0 to 7 additional arguments + + // region 0 parameters + // #region 0 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C) => TReturn, + context: null | undefined, + a: A, b: B, c: C): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B) => TReturn, + context: null | undefined, + a: A, b: B): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A) => TReturn, + context: null | undefined, + a: A): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: () => TReturn, + context: null | undefined): () => TReturn; + + // #endregion + + // region 1 parameters + // #region 1 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T) => TReturn, + context: null | undefined, + a: A, b: B): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T) => TReturn, + context: null | undefined, + a: A): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T) => TReturn, + context: null | undefined): (t: T) => TReturn; + + // #endregion + + // region 2 parameters + // #region 2 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U) => TReturn, + context: null | undefined, + a: A): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U) => TReturn, + context: null | undefined): (t: T, u: U) => TReturn; + + // #endregion + + // region 3 parameters + // #region 3 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U, v: V) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U, v: V) => TReturn, + context: null | undefined): (t: T, u: U, v: V) => TReturn; + + // #endregion + + // region 4 parameters + // #region 4 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U, v: V, w: W) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W) => TReturn; + + // #endregion + + // region 5 parameters + // #region 5 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U, v: V, w: W, x: X) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X) => TReturn; + + // #endregion + + // region 6 parameters + // #region 6 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + + // #endregion + + // region 7+ parameters + // #region 7+ parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (a: A, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + + // #endregion + + // #endregion + + // region 8+ additional arguments + // #region 8+ additional arguments + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.9 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + */ + proxy(funсtion: (...args: any[]) => TReturn, + context: null | undefined, + ...additionalArguments: any[]): (...args: any[]) => TReturn; + + // #endregion + + // #endregion + + // region (funсtion, context) + // #region (funсtion, context) + + // region 0 to 7 additional arguments + // #region 0 to 7 additional arguments + + // region 0 parameters + // #region 0 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C) => TReturn, + context: TContext, + a: A, b: B, c: C): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B) => TReturn, + context: TContext, + a: A, b: B): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4` + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A) => TReturn, + context: TContext, + a: A): () => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext) => TReturn, + context: TContext): () => TReturn; + + // #endregion + + // region 1 parameters + // #region 1 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T) => TReturn, + context: TContext, + a: A, b: B): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T) => TReturn, + context: TContext, + a: A): (t: T) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T) => TReturn, + context: TContext): (t: T) => TReturn; + + // #endregion + + // region 2 parameters + // #region 2 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U) => TReturn, + context: TContext, + a: A): (t: T, u: U) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U) => TReturn, + context: TContext): (t: T, u: U) => TReturn; + + // #endregion + + // region 3 parameters + // #region 3 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U, v: V) => TReturn, + context: TContext, + a: A): (t: T, u: U, v: V) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U, v: V) => TReturn, + context: TContext): (t: T, u: U, v: V) => TReturn; + + // #endregion + + // region 4 parameters + // #region 4 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U, v: V, w: W) => TReturn, + context: TContext, + a: A): (t: T, u: U, v: V, w: W) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U, v: V, w: W) => TReturn, + context: TContext): (t: T, u: U, v: V, w: W) => TReturn; + + // #endregion + + // region 5 parameters + // #region 5 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext, + a: A): (t: T, u: U, v: V, w: W, x: X) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn, + context: TContext): (t: T, u: U, v: V, w: W, x: X) => TReturn; + + // #endregion + + // region 6 parameters + // #region 6 parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, + context: TContext): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; + + // #endregion + + // region 7+ parameters + // #region 7+ parameters + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @param g An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, g: G, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @param f An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, f: F, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @param e An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, e: E, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @param d An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, d: D, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @param c An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, c: C, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @param b An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, b: B, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param a An argument to be passed to the function referenced in the `function` argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, a: A, + t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext, + a: A): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, + context: TContext): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; + + // #endregion + + // #endregion + + // region 8+ additional arguments + // #region 8+ additional arguments + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param funсtion The function whose context will be changed. + * @param context The object to which the context (`this`) of the function should be set. + * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + * @example ​ ````Change the context of a function bound to the click handler, +```html + + + + + jQuery.proxy demo + + + +​ +

      +
      +​ + +​ + + +``` + */ + proxy(funсtion: (this: TContext, ...args: any[]) => TReturn, + context: TContext, + ...additionalArguments: any[]): (...args: any[]) => TReturn; + + // #endregion + + // #endregion + + // region (context, name) + // #region (context, name) + + /** + * Takes a function and returns a new one that will always have a particular context. + * @param context The object to which the context of the function should be set. + * @param name The name of the function whose context will be changed (should be a property of the context object). + * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. + * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` + * @since 1.4 + * @since 1.6 + * @deprecated ​ Deprecated since 3.3. Use \`{@link Function#bind }\`. + * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. +```html + + + + + jQuery.proxy demo + + + +​ +

      +

      +​ + +​ + + +``` + */ + proxy(context: TContext, + name: keyof TContext, + ...additionalArguments: any[]): (...args: any[]) => any; + + // #endregion + + // #endregion + + /** + * Manipulate the queue of functions to be executed on the matched element. + * @param element A DOM element where the array of queued functions is attached. + * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. + * @param newQueue The new function to add to the queue. + * An array of functions to replace the current queue contents. + * @see \`{@link https://api.jquery.com/jQuery.queue/ }\` + * @since 1.3 + * @example ​ ````Show the length of the queue. +```html + + + + + jQuery.queue demo + + + + +​ + + +
      + ​ + +​ + + +``` + * @example ​ ````Queue a custom function. +```html + + + + + jQuery.queue demo + + + + +​ +Click here... +
      +​ + +​ + + +``` + * @example ​ ````Set a queue array to delete the queue. +```html + + + + + jQuery.queue demo + + + + +​ + + +
      +​ + +​ + + +``` + */ + queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; + /** + * Handles errors thrown synchronously in functions wrapped in jQuery(). + * @param error An error thrown in the function wrapped in jQuery(). + * @see \`{@link https://api.jquery.com/jQuery.readyException/ }\` + * @since 3.1 + * @example ​ ````Pass the received error to console.error. +```javascript +jQuery.readyException = function( error ) { + console.error( error ); +}; +``` + */ + readyException(error: Error): any; + /** + * Remove a previously-stored piece of data. + * @param element A DOM element from which to remove data. + * @param name A string naming the piece of data to remove. + * @see \`{@link https://api.jquery.com/jQuery.removeData/ }\` + * @since 1.2.3 + * @example ​ ````Set a data store for 2 names then remove one of them. +```html + + + + + jQuery.removeData demo + + + + +​ +
      value1 before creation:
      +
      value1 after creation:
      +
      value1 after removal:
      +
      value2 after removal:
      +​ + +​ + + +``` + */ + removeData(element: Element | Document | Window | JQuery.PlainObject, name?: string): void; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * @param duration A string or number determining how long the animation will run. + * @param easing A string indicating which easing function to use for the transition. + * @param complete A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` + * @since 1.1 + */ + speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * @param duration A string or number determining how long the animation will run. + * @param easing_complete _@param_ `easing_complete` + *
      + * * `easing` — A string indicating which easing function to use for the transition.
      + * * `complete` — A function to call once the animation is complete, called once per matched element. + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` + * @since 1.0 + * @since 1.1 + */ + speed(duration: JQuery.Duration, + easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; + /** + * Creates an object containing a set of properties ready to be used in the definition of custom animations. + * @param duration_complete_settings _@param_ `duration_complete_settings` + *
      + * * `duration` — A string or number determining how long the animation will run.
      + * * `complete` — A function to call once the animation is complete, called once per matched element.
      + * * `settings` — + * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` + * @since 1.0 + * @since 1.1 + */ + speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; + /** + * Remove the whitespace from the beginning and end of a string. + * @param str The string to trim. + * @see \`{@link https://api.jquery.com/jQuery.trim/ }\` + * @since 1.0 + * @example ​ ````Remove the white spaces at the start and at the end of the string. +```html + + + + + jQuery.trim demo + + + +​ +
      
      +
      
      +​
      +
      +​
      +
      +
      +```
      +     * @example ​ ````Remove the white spaces at the start and at the end of the string.
      +```javascript
      +$.trim("    hello, how are you?    ");
      +```
      +     * @example ​ ````Remove the white spaces at the start and at the end of the string.
      +```javascript
      +$.trim("    hello, how are you?    ");
      +```
      +     */
      +    trim(str: string): string;
      +    /**
      +     * Determine the internal JavaScript [[Class]] of an object.
      +     * @param obj Object to get the internal JavaScript [[Class]] of.
      +     * @see \`{@link https://api.jquery.com/jQuery.type/ }\`
      +     * @since 1.4.3
      +     * @deprecated ​ Deprecated since 3.3. See \`{@link https://github.com/jquery/jquery/issues/3605 }\`.
      +     * @example ​ ````Find out if the parameter is a RegExp.
      +```html
      +
      +
      +
      +  
      +  jQuery.type demo
      +  
      +
      +
      +​
      +Is it a RegExp? 
      +​
      +
      +​
      +
      +
      +```
      +     */
      +    type(obj: any): 'array' | 'boolean' | 'date' | 'error' | 'function' | 'null' | 'number' | 'object' | 'regexp' | 'string' | 'symbol' | 'undefined';
      +    /**
      +     * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers.
      +     * @param array The Array of DOM elements.
      +     * @see \`{@link https://api.jquery.com/jQuery.unique/ }\`
      +     * @since 1.1.3
      +     * @deprecated ​ Deprecated since 3.0. Use \`{@link uniqueSort }\`.
      +     *
      +     * **Cause**: The fact that `jQuery.unique` sorted its results in DOM order was surprising to many who did not read the documentation carefully. As of jQuery 3.0 this function is being renamed to make it clear.
      +     *
      +     * **Solution**: Replace all uses of `jQuery.unique` with `jQuery.uniqueSort` which is the same function with a better name.
      +     * @example ​ ````Removes any duplicate elements from the array of divs.
      +```html
      +
      +
      +
      +  
      +  jQuery.unique demo
      +  
      +  
      +
      +
      +​
      +
      There are 6 divs in this document.
      +
      +
      +
      +
      +
      +​ + +​ + + +``` + */ + unique(array: T[]): T[]; + /** + * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on arrays of DOM elements, not strings or numbers. + * @param array The Array of DOM elements. + * @see \`{@link https://api.jquery.com/jQuery.uniqueSort/ }\` + * @since 1.12 + * @since 2.2 + * @example ​ ````Removes any duplicate elements from the array of divs. +```html + + + + + jQuery.uniqueSort demo + + + + +​ +
      There are 6 divs in this document.
      +
      +
      +
      +
      +
      +​ + +​ + + +``` + */ + uniqueSort(array: T[]): T[]; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when( + deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1, + deferredV: JQuery.Promise | JQuery.Thenable | VR1, + ): JQuery.Promise3< + TR1, TJ1, never, + UR1, UJ1, never, + VR1, VJ1, never>; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when( + deferredT: JQuery.Promise | JQuery.Thenable | TR1, + deferredU: JQuery.Promise | JQuery.Thenable | UR1, + ): JQuery.Promise2< + TR1, TJ1, never, + UR1, UJ1, never>; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when( + deferredT: JQuery.Promise3 | + JQuery.Promise2 + ): JQuery.Promise3< + TR1, TJ1, never, + TR2, TJ2, never, + TR3, TJ3, never>; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @param deferreds Zero or more Thenable objects. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; + /** + * Provides a way to execute callback functions based on zero or more Thenable objects, usually Deferred objects that represent asynchronous events. + * @param deferreds Zero or more Thenable objects. + * @see \`{@link https://api.jquery.com/jQuery.when/ }\` + * @since 1.5 + * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ).done(function( a1, a2 ) { + // a1 and a2 are arguments resolved for the page1 and page2 ajax requests, respectively. + // Each argument is an array with the following structure: [ data, statusText, jqXHR ] + var data = a1[ 0 ] + a2[ 0 ]; // a1[ 0 ] = "Whip", a2[ 0 ] = " It" + if ( /Whip It/.test( data ) ) { + alert( "We got what we came for!" ); + } +}); +``` + * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. +```javascript +$.when( $.ajax( "/page1.php" ), $.ajax( "/page2.php" ) ) + .then( myFunc, myFailure ); +``` + */ + when(...deferreds: any[]): JQuery.Promise; +} diff --git a/types/jquery/dist/jquery.slim.d.ts b/types/jquery/dist/jquery.slim.d.ts new file mode 100644 index 0000000000..bdd21a7523 --- /dev/null +++ b/types/jquery/dist/jquery.slim.d.ts @@ -0,0 +1,3 @@ +/// + +export = jQuery; diff --git a/types/jquery/index.d.ts b/types/jquery/index.d.ts index 299ba7a7d3..2d4171320b 100644 --- a/types/jquery/index.d.ts +++ b/types/jquery/index.d.ts @@ -25,62392 +25,10 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -// tslint:disable:jsdoc-format -// tslint:disable:max-line-length -// tslint:disable:no-irregular-whitespace +/// +/// +/// +/// +/// -declare module 'jquery' { - export = jQuery; -} - -declare module 'jquery/dist/jquery.slim' { - export = jQuery; -} - -declare const jQuery: JQueryStatic; -declare const $: JQueryStatic; - -// Used by JQuery.Event -type _Event = Event; - -interface JQueryStatic { - /** - * @see \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax1 }\` - * @deprecated Use \`{@link JQueryStatic.ajaxSetup }\`. - */ - ajaxSettings: JQuery.AjaxSettings; - /** - * A factory function that returns a chainable utility object with methods to register multiple - * callbacks into callback queues, invoke callback queues, and relay the success or failure state of - * any synchronous or asynchronous function. - * - * @param beforeStart A function that is called just before the constructor returns. - * @see \`{@link https://api.jquery.com/jQuery.Deferred/ }\` - * @since 1.5 - */ - Deferred: JQuery.DeferredStatic; - Event: JQuery.EventStatic; - /** - * Hook directly into jQuery to override how particular CSS properties are retrieved or set, normalize - * CSS property naming, or create custom properties. - * - * @see \`{@link https://api.jquery.com/jQuery.cssHooks/ }\` - * @since 1.4.3 - */ - // Set to HTMLElement to minimize breaks but should probably be Element. - cssHooks: JQuery.PlainObject>; - /** - * An object containing all CSS properties that may be used without a unit. The .css() method uses this - * object to see if it may append px to unitless values. - * - * @see \`{@link https://api.jquery.com/jQuery.cssNumber/ }\` - * @since 1.4.3 - */ - cssNumber: JQuery.PlainObject; - // Set to HTMLElement to minimize breaks but should probably be Element. - readonly fn: JQuery; - fx: { - /** - * The rate (in milliseconds) at which animations fire. - * - * @see \`{@link https://api.jquery.com/jQuery.fx.interval/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.0. See \`{@link https://api.jquery.com/jQuery.fx.interval/ }\`. - * @example ​ ````Cause all animations to run with less frames. -```html - - - - - jQuery.fx.interval demo - - - - -​ -

      -
      -​ - - - -``` - */ - interval: number; - /** - * Globally disable all animations. - * - * @see \`{@link https://api.jquery.com/jQuery.fx.off/ }\` - * @since 1.3 - * @example ​ ````Toggle animation on and off -```html - - - - - jQuery.fx.off demo - - - - -​ - - -
      -​ - - - -``` - */ - off: boolean; - step: JQuery.PlainObject>; - }; - /** - * A Promise-like object (or "thenable") that resolves when the document is ready. - * - * @see \`{@link https://api.jquery.com/jQuery.ready/ }\` - * @since 1.8 - * @example ​ ````Listen for document ready using jQuery.when. -```html - - - - - jQuery.ready demo - - - -​​ - - - -``` - * @example ​ ````Typical usage involving another promise, using jQuery.when. -```html - - - - - jQuery.ready demo - - - -​​ - - - -``` - */ - ready: JQuery.Thenable; - /** - * A collection of properties that represent the presence of different browser features or bugs. - * Intended for jQuery's internal use; specific properties may be removed when they are no longer - * needed internally to improve page startup performance. For your own project's feature-detection - * needs, we strongly recommend the use of an external library such as Modernizr instead of dependency - * on properties in jQuery.support. - * - * @see \`{@link https://api.jquery.com/jQuery.support/ }\` - * @since 1.3 - * @deprecated Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. - */ - support: JQuery.PlainObject; - // Set to HTMLElement to minimize breaks but should probably be Element. - valHooks: JQuery.PlainObject>; - // HACK: This is the factory function returned when importing jQuery without a DOM. Declaring it separately breaks using the type parameter on JQueryStatic. - // HACK: The discriminator parameter handles the edge case of passing a Window object to JQueryStatic. It doesn't actually exist on the factory function. - (window: Window, discriminator: boolean): JQueryStatic; - /** - * Creates DOM elements on the fly from the provided string of raw HTML. - * - * @param html A string of HTML to create on the fly. Note that this parses HTML, not XML. - * A string defining a single, standalone, HTML element (e.g.
      or
      ). - * @param ownerDocument_attributes A document in which the new elements will be created. - * An object of attributes, events, and methods to call on the newly-created element. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // tslint:disable-next-line:no-unnecessary-generics - (html: JQuery.htmlString, ownerDocument_attributes?: Document | JQuery.PlainObject): JQuery; - /** - * Accepts a string containing a CSS selector which is then used to match a set of elements. - * - * @param selector A string containing a selector expression - * @param context A DOM Element, Document, or jQuery to use as context - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // tslint:disable-next-line:no-unnecessary-generics - (selector: JQuery.Selector, context?: Element | Document | JQuery): 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 element A DOM element to wrap in a jQuery object. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // Using a unified signature is not possible due to a TypeScript 2.4 bug (DefinitelyTyped#27810) - // tslint:disable-next-line:unified-signatures - (element: T): 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. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // 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; - /** - * 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. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - (selection: JQuery): JQuery; - /** - * Binds a function to be executed when the DOM has finished loading. - * - * @param callback The function to execute when the DOM is ready. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // tslint:disable-next-line:no-unnecessary-generics unified-signatures - (callback: ((this: Document, $: JQueryStatic) => void)): 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 object A plain object to wrap in a jQuery object. - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.0 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - (object: T): JQuery; - /** - * Returns an empty jQuery set. - * - * @see \`{@link https://api.jquery.com/jQuery/ }\` - * @since 1.4 - * @example ​ ````Find all p elements that are children of a div element and apply a border to them. -```html - - - - - jQuery demo - - - -​ -

      one

      -

      two

      -

      three

      -​ - - - -``` - * @example ​ ````Find all inputs of type radio within the first form in the document. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Find all div elements within an XML document from an Ajax response. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Set the background color of the page to black. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Hide all the input elements within a form. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create a div element (and all of its contents) dynamically and append it to the body element. Internally, an element is created and its innerHTML property set to the given markup. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Create some DOM elements. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Execute the function when the DOM is ready to be used. -```html - - - - - jQuery demo - - - -​​ - - - -``` - * @example ​ ````Use both the shortcut for $(document).ready() and the argument to write failsafe jQuery code using the $ alias, without relying on the global alias. -```html - - - - - jQuery demo - - - -​​ - - - -``` - */ - // tslint:disable-next-line:no-unnecessary-generics - (): JQuery; - /** - * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. - * - * @param flags An optional list of space-separated flags that change how the callback list behaves. - * @see \`{@link https://api.jquery.com/jQuery.Callbacks/ }\` - * @since 1.7 - */ - // tslint:disable-next-line:ban-types no-unnecessary-generics - Callbacks(flags?: string): JQuery.Callbacks; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param url A string containing the URL to which the request is sent. - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can - * be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) below for a complete list of all settings. - * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` - * @since 1.5 - * @example ​ ````Save some data to the server and notify the user once it's complete. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Retrieve the latest version of an HTML page. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Send an xml document as data to the server. By setting the processData - option to false, the automatic conversion of data to strings is prevented. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Load and execute a JavaScript file. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - */ - ajax(url: string, settings?: JQuery.AjaxSettings): JQuery.jqXHR; - /** - * Perform an asynchronous HTTP (Ajax) request. - * - * @param settings A set of key/value pairs that configure the Ajax request. All settings are optional. A default can - * be set for any option with $.ajaxSetup(). - * @see \`{@link https://api.jquery.com/jQuery.ajax/ }\` - * @since 1.0 - * @example ​ ````Save some data to the server and notify the user once it's complete. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Retrieve the latest version of an HTML page. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Send an xml document as data to the server. By setting the processData - option to false, the automatic conversion of data to strings is prevented. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Send an id as data to the server, save some data to the server, and notify the user once it's complete. If the request fails, alert the user. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - * @example ​ ````Load and execute a JavaScript file. -```html - - - - - jQuery.ajax demo - - - -​​ - - - -``` - */ - ajax(settings?: JQuery.AjaxSettings): JQuery.jqXHR; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they - * are processed by $.ajax(). - * - * @param dataTypes An optional string containing one or more space-separated dataTypes - * @param handler A handler to set default values for future Ajax requests. - * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` - * @since 1.5 - */ - ajaxPrefilter(dataTypes: string, - handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; - /** - * Handle custom Ajax options or modify existing options before each request is sent and before they - * are processed by $.ajax(). - * - * @param handler A handler to set default values for future Ajax requests. - * @see \`{@link https://api.jquery.com/jQuery.ajaxPrefilter/ }\` - * @since 1.5 - */ - ajaxPrefilter(handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => string | void): void; - /** - * Set default values for future Ajax requests. Its use is not recommended. - * - * @param options A set of key/value pairs that configure the default Ajax request. All options are optional. - * @see \`{@link https://api.jquery.com/jQuery.ajaxSetup/ }\` - * @since 1.1 - * @example ​ ````Sets the defaults for Ajax requests to the url "/xmlhttp/", disables global handlers and uses POST instead of GET. The following Ajax requests then sends some data without having to set anything else. -```html - - - - - jQuery.ajaxSetup demo - - - -​​ - - - -``` - */ - ajaxSetup(options: JQuery.AjaxSettings): JQuery.AjaxSettings; - /** - * Creates an object that handles the actual transmission of Ajax data. - * - * @param dataType A string identifying the data type to use - * @param handler A handler to return the new transport object to use with the data type provided in the first argument. - * @see \`{@link https://api.jquery.com/jQuery.ajaxTransport/ }\` - * @since 1.5 - */ - ajaxTransport(dataType: string, - handler: (options: JQuery.AjaxSettings, originalOptions: JQuery.AjaxSettings, jqXHR: JQuery.jqXHR) => JQuery.Transport | void): void; - /** - * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3384 }\`. - */ - camelCase(value: string): string; - /** - * Check to see if a DOM element is a descendant of another DOM element. - * - * @param container The DOM element that may contain the other element. - * @param contained The DOM element that may be contained by (a descendant of) the other element. - * @see \`{@link https://api.jquery.com/jQuery.contains/ }\` - * @since 1.4 - * @example ​ ````Check if an element is a descendant of another. -```html - - - - - jQuery.contains demo - - - -​​ - - - -``` - */ - contains(container: Element, contained: Element): boolean; - css(elem: Element, name: string): any; - /** - * Store arbitrary data associated with the specified element. Returns the value that was set. - * - * @param element The DOM element to associate with the data. - * @param key A string naming the piece of data to set. - * @param value The new data value; this can be any Javascript type except `undefined`. - * @see \`{@link https://api.jquery.com/jQuery.data/ }\` - * @since 1.2.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - jQuery.data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - jQuery.data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(element: Element, key: string, value: T): T; - /** - * Returns value at named data store for the element, as set by `jQuery.data(element, name, value)`, or - * the full data store for the element. - * - * @param element The DOM element to query for the data. - * @param key Name of the data stored. - * @param value `undefined` is not recognized as a data value. Calls such as `jQuery.data( el, "name", undefined )` - * will return the corresponding data for "name", and is therefore the same as `jQuery.data( el, "name" )` - * @see \`{@link https://api.jquery.com/jQuery.data/ }\` - * @since 1.2.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - jQuery.data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - jQuery.data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - // `unified-signatures` is disabled so that behavior when passing `undefined` to `value` can be documented. Unifying the signatures - // results in potential confusion for users from an unexpected parameter. - // tslint:disable-next-line:unified-signatures - data(element: Element, key: string, value: undefined): any; - /** - * Returns value at named data store for the element, as set by `jQuery.data(element, name, value)`, or - * the full data store for the element. - * - * @param element The DOM element to query for the data. - * @param key Name of the data stored. - * @see \`{@link https://api.jquery.com/jQuery.data/ }\` - * @since 1.2.3 - * @since 1.4 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - jQuery.data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - jQuery.data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(element: Element, key?: string): any; - /** - * Execute the next function on the queue for the matched element. - * - * @param element A DOM element from which to remove and execute a queued function. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see \`{@link https://api.jquery.com/jQuery.dequeue/ }\` - * @since 1.3 - * @example ​ ````Use jQuery.dequeue() to end a custom queue function which allows the queue to keep going. -```html - - - - - jQuery.dequeue demo - - - - -​ - -
      -​ - - - -``` - */ - dequeue(element: Element, queueName?: string): void; - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. - * Arrays and array-like objects with a length property (such as a function's arguments object) are - * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param array The array to iterate over. - * @param callback The function that will be executed on every object. - * @see \`{@link https://api.jquery.com/jQuery.each/ }\` - * @since 1.0 - * @example ​ ````Iterates through the array displaying each number as both a word and numeral -```html - - - - - jQuery.each demo - - - - -​ -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Iterates over items in an array, accessing both the current item and its index. -```html - - - - - jQuery.each demo - - - -​​ - - - -``` - * @example ​ ````Iterates over the properties in an object, accessing both the current item and its key. -```html - - - - - jQuery.each demo - - - -​​ - - - -``` - */ - each(array: ArrayLike, callback: (this: T, indexInArray: number, value: T) => false | any): ArrayLike; - /** - * A generic iterator function, which can be used to seamlessly iterate over both objects and arrays. - * Arrays and array-like objects with a length property (such as a function's arguments object) are - * iterated by numeric index, from 0 to length-1. Other objects are iterated via their named properties. - * - * @param obj The object to iterate over. - * @param callback The function that will be executed on every object. - * @see \`{@link https://api.jquery.com/jQuery.each/ }\` - * @since 1.0 - * @example ​ ````Iterates through the array displaying each number as both a word and numeral -```html - - - - - jQuery.each demo - - - - -​ -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Iterates over items in an array, accessing both the current item and its index. -```html - - - - - jQuery.each demo - - - -​​ - - - -``` - * @example ​ ````Iterates over the properties in an object, accessing both the current item and its key. -```html - - - - - jQuery.each demo - - - -​​ - - - -``` - */ - each(obj: T, callback: (this: T[K], propertyName: K, valueOfProperty: T[K]) => false | any): T; - /** - * Takes a string and throws an exception containing it. - * - * @param message The message to send out. - * @see \`{@link https://api.jquery.com/jQuery.error/ }\` - * @since 1.4.1 - * @example ​ ````Override jQuery.error for display in Firebug. -```html - - - - - jQuery.error demo - - - -​​ - - - -``` - */ - error(message: string): any; - /** - * Escapes any character that has a special meaning in a CSS selector. - * - * @param selector A string containing a selector expression to escape. - * @see \`{@link https://api.jquery.com/jQuery.escapeSelector/ }\` - * @since 3.0 - * @example ​ ````Escape an ID containing a hash. -```html - - - - - jQuery.escapeSelector demo - - - -​​ - - - -``` - * @example ​ ````Select all the elements having a class name of .box inside a div. -```html - - - - - jQuery.escapeSelector demo - - - -​​ - - - -``` - */ - escapeSelector(selector: JQuery.Selector): JQuery.Selector; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @param object5 An object containing additional properties to merge in. - * @param object6 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @param object5 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U, object2: V, object3: W): T & U & V & W; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U, object2: V): T & U & V; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: T, object1: U): T & U; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param deep If true, the merge becomes recursive (aka. deep copy). Passing false for this argument is not supported. - * @param target The object to extend. It will receive the new properties. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.1.4 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(deep: true, target: any, object1: any, ...objectN: any[]): any; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @param object5 An object containing additional properties to merge in. - * @param object6 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y, object6: Z): T & U & V & W & X & Y & Z; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @param object5 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X, object5: Y): T & U & V & W & X & Y; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @param object4 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U, object2: V, object3: W, object4: X): T & U & V & W & X; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @param object3 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U, object2: V, object3: W): T & U & V & W; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param object2 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U, object2: V): T & U & V; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: T, object1: U): T & U; - /** - * Merge the contents of two or more objects together into the first object. - * - * @param target An object that will receive the new properties if additional objects are passed in or that will - * extend the jQuery namespace if it is the sole argument. - * @param object1 An object containing additional properties to merge in. - * @param objectN Additional objects containing properties to merge in. - * @see \`{@link https://api.jquery.com/jQuery.extend/ }\` - * @since 1.0 - * @example ​ ````Merge two objects, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge two objects recursively, modifying the first. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - * @example ​ ````Merge defaults and options, without modifying the defaults. This is a common plugin development pattern. -```html - - - - - jQuery.extend demo - - - -​ -
      -​ - - - -``` - */ - extend(target: any, object1: any, ...objectN: any[]): any; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see \`{@link https://api.jquery.com/jQuery.get/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ```` Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - */ - get(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback | null, - dataType?: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see \`{@link https://api.jquery.com/jQuery.get/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ```` Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - */ - get(url: string, - success: JQuery.jqXHR.DoneCallback | null, - dataType: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * you can use null or jQuery.noop as a placeholder. - * A plain object or string that is sent to the server with the request. - * @see \`{@link https://api.jquery.com/jQuery.get/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ```` Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - */ - get(url: string, - success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP GET request. - * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. The type option will automatically be set to GET. - * @see \`{@link https://api.jquery.com/jQuery.get/ }\` - * @since 1.0 - * @since 1.12 - * @since 2.2 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.cgi with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - * @example ​ ```` Get the test.php page contents, which has been returned in json format (<?php echo json_encode( array( "name"=>"John","time"=>"2pm" ) ); ?>), and add it to the page. -```html - - - - - jQuery.get demo - - - -​​ - - - -``` - */ - get(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. - * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` - * @since 1.0 - * @example ​ ````Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API. -```html - - - - - jQuery.getJSON demo - - - - -​ -
      -​ - - - -``` - * @example ​ ````Load the JSON data from test.js and access a name from the returned JSON data. -```html - - - - - jQuery.getJSON demo - - - -​​ - - - -``` - * @example ​ ````Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. - If an error occurs, log an error message instead. -```html - - - - - jQuery.getJSON demo - - - -​​ - - - -``` - */ - getJSON(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; - /** - * Load JSON-encoded data from the server using a GET HTTP request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. - * A plain object or string that is sent to the server with the request. - * @see \`{@link https://api.jquery.com/jQuery.getJSON/ }\` - * @since 1.0 - * @example ​ ````Loads the four most recent pictures of Mount Rainier from the Flickr JSONP API. -```html - - - - - jQuery.getJSON demo - - - - -​ -
      -​ - - - -``` - * @example ​ ````Load the JSON data from test.js and access a name from the returned JSON data. -```html - - - - - jQuery.getJSON demo - - - -​​ - - - -``` - * @example ​ ````Load the JSON data from test.js, passing along additional data, and access a name from the returned JSON data. - If an error occurs, log an error message instead. -```html - - - - - jQuery.getJSON demo - - - -​​ - - - -``` - */ - getJSON(url: string, - success_data?: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load a JavaScript file from the server using a GET HTTP request, then execute it. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. - * @see \`{@link https://api.jquery.com/jQuery.getScript/ }\` - * @since 1.0 - * @example ​ ````Define a $.cachedScript() method that allows fetching a cached script: -```html - - - - - jQuery.getScript demo - - - -​​ - - - -``` - * @example ​ ````Load the official jQuery Color Animation plugin dynamically and bind some color animations to occur once the new functionality is loaded. -```html - - - - - jQuery.getScript demo - - - - -​ - -
      -​ - - - -``` - */ - getScript(url: string, - success?: JQuery.jqXHR.DoneCallback): JQuery.jqXHR; - /** - * Execute some JavaScript code globally. - * - * @param code The JavaScript code to execute. - * @see \`{@link https://api.jquery.com/jQuery.globalEval/ }\` - * @since 1.0.4 - * @example ​ ````Execute a script in the global context. -```html - - - - - jQuery.globalEval demo - - - -​​ - - - -``` - */ - globalEval(code: string): void; - /** - * Finds the elements of an array which satisfy a filter function. The original array is not affected. - * - * @param array The array-like object to search through. - * @param fn The function to process each item against. The first argument to the function is the item, and the - * second argument is the index. The function should return a Boolean value. this will be the global window object. - * @param invert If "invert" is false, or not provided, then the function returns an array consisting of all elements - * for which "callback" returns true. If "invert" is true, then the function returns an array - * consisting of all elements for which "callback" returns false. - * @see \`{@link https://api.jquery.com/jQuery.grep/ }\` - * @since 1.0 - * @example ​ ````Filters the original array of numbers leaving that are not 5 and have an index greater than 4. Then it removes all 9s. -```html - - - - - jQuery.grep demo - - - - -​ -
      -

      - -​ - - - -``` - * @example ​ ````Filter an array of numbers to include only numbers bigger then zero. -```html - - - - - jQuery.grep demo - - - -​​ - - - -``` - * @example ​ ````Filter an array of numbers to include numbers that are not bigger than zero. -```html - - - - - jQuery.grep demo - - - -​​ - - - -``` - */ - grep(array: ArrayLike, - fn: (elementOfArray: T, indexInArray: number) => boolean, - invert?: boolean): T[]; - /** - * Determine whether an element has any jQuery data associated with it. - * - * @param element A DOM element to be checked for data. - * @see \`{@link https://api.jquery.com/jQuery.hasData/ }\` - * @since 1.5 - * @example ​ ````Set data on an element and see the results of hasData. -```html - - - - - jQuery.hasData demo - - - -​ -

      Results:

      -​ - - - -``` - */ - hasData(element: Element): boolean; - /** - * Holds or releases the execution of jQuery's ready event. - * - * @param hold Indicates whether the ready hold is being requested or released - * @see \`{@link https://api.jquery.com/jQuery.holdReady/ }\` - * @since 1.6 - * @deprecated Deprecated since 3.2. See \`{@link https://github.com/jquery/jquery/issues/3288 }\`. - * @example ​ ````Delay the ready event until a custom plugin has loaded. -```html - - - - - jQuery.holdReady demo - - - -​​ - - - -``` - */ - holdReady(hold: boolean): void; - /** - * Modify and filter HTML strings passed through jQuery manipulation methods. - * - * @param html The HTML string on which to operate. - * @see \`{@link https://api.jquery.com/jQuery.htmlPrefilter/ }\` - * @since 1.12/2.2 - */ - htmlPrefilter(html: JQuery.htmlString): JQuery.htmlString; - /** - * Search for a specified value within an array and return its index (or -1 if not found). - * - * @param value The value to search for. - * @param array An array through which to search. - * @param fromIndex The index of the array at which to begin the search. The default is 0, which will search the whole array. - * @see \`{@link https://api.jquery.com/jQuery.inArray/ }\` - * @since 1.2 - * @example ​ ````Report the index of some elements in the array. -```html - - - - - jQuery.inArray demo - - - - -​ -
      "John" found at
      -
      4 found at
      -
      "Karl" not found, so
      -
      "Pete" is in the array, but not at or after index 2, so
      -​ - - - -``` - */ - inArray(value: T, array: T[], fromIndex?: number): number; - /** - * Determine whether the argument is an array. - * - * @param obj Object to test whether or not it is an array. - * @see \`{@link https://api.jquery.com/jQuery.isArray/ }\` - * @since 1.3 - * @deprecated Deprecated since 3.2. Use \`{@link Array.isArray }\`. - * @example ​ ````Finds out if the parameter is an array. -```html - - - - - jQuery.isArray demo - - - -​ -Is [] an Array? -​ - - - -``` - */ - isArray(obj: any): obj is any[]; - /** - * Check to see if an object is empty (contains no enumerable properties). - * - * @param obj The object that will be checked to see if it's empty. - * @see \`{@link https://api.jquery.com/jQuery.isEmptyObject/ }\` - * @since 1.4 - * @example ​ ````Check an object to see if it's empty. -```html - - - - - jQuery.isEmptyObject demo - - - -​​ - - - -``` - */ - isEmptyObject(obj: any): boolean; - /** - * Determine if the argument passed is a JavaScript function object. - * - * @param obj Object to test whether or not it is a function. - * @see \`{@link https://api.jquery.com/jQuery.isFunction/ }\` - * @since 1.2 - * @deprecated Deprecated since 3.3. Use `typeof x === "function"`. - * @example ​ ````Test a few parameter examples. -```html - - - - - jQuery.isFunction demo - - - - -​ -
      jQuery.isFunction( objs[ 0 ] ) =
      -
      jQuery.isFunction( objs[ 1 ] ) =
      -
      jQuery.isFunction( objs[ 2 ] ) =
      -
      jQuery.isFunction( objs[ 3 ] ) =
      -
      jQuery.isFunction( objs[ 4 ] ) =
      -​ - - - -``` - * @example ​ ````Finds out if the parameter is a function. -```html - - - - - jQuery.isFunction demo - - - -​​ - - - -``` - */ - // tslint:disable-next-line:ban-types - isFunction(obj: any): obj is Function; - /** - * Determines whether its argument represents a JavaScript number. - * - * @param value The value to be tested. - * @see \`{@link https://api.jquery.com/jQuery.isNumeric/ }\` - * @since 1.7 - * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/2960 }\`. - * @example ​ ````Sample return values of $.isNumeric with various inputs. -```html - - - - - jQuery.isNumeric demo - - - -​​ - - - -``` - */ - isNumeric(value: any): boolean; - /** - * Check to see if an object is a plain object (created using "{}" or "new Object"). - * - * @param obj The object that will be checked to see if it's a plain object. - * @see \`{@link https://api.jquery.com/jQuery.isPlainObject/ }\` - * @since 1.4 - * @example ​ ````Check an object to see if it's a plain object. -```html - - - - - jQuery.isPlainObject demo - - - -​​ - - - -``` - */ - isPlainObject(obj: any): boolean; - /** - * Determine whether the argument is a window. - * - * @param obj Object to test whether or not it is a window. - * @see \`{@link https://api.jquery.com/jQuery.isWindow/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Internal. See \`{@link https://github.com/jquery/jquery/issues/3629 }\`. - * @example ​ ````Finds out if the parameter is a window. -```html - - - - - jQuery.isWindow demo - - - -​ -Is 'window' a window? -​ - - - -``` - */ - isWindow(obj: any): obj is Window; - /** - * Check to see if a DOM node is within an XML document (or is an XML document). - * - * @param node The DOM node that will be checked to see if it's in an XML document. - * @see \`{@link https://api.jquery.com/jQuery.isXMLDoc/ }\` - * @since 1.1.4 - * @example ​ ````Check an object to see if it's in an XML document. -```html - - - - - jQuery.isXMLDoc demo - - - -​​ - - - -``` - */ - isXMLDoc(node: Node): boolean; - /** - * Convert an array-like object into a true JavaScript array. - * - * @param obj Any object to turn into a native Array. - * @see \`{@link https://api.jquery.com/jQuery.makeArray/ }\` - * @since 1.2 - * @example ​ ````Turn a collection of HTMLElements into an Array of them. -```html - - - - - jQuery.makeArray demo - - - - -​ -
      First
      -
      Second
      -
      Third
      -
      Fourth
      -​ - - - -``` - * @example ​ ````Turn a jQuery object into an array -```html - - - - - jQuery.makeArray demo - - - -​​ - - - -``` - */ - makeArray(obj: ArrayLike): T[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param array The Array to translate. - * @param callback The function to process each item against. The first argument to the function is the array item, the - * second argument is the index in array The function can return any value. A returned array will be - * flattened into the resulting array. Within the function, this refers to the global (window) object. - * @see \`{@link https://api.jquery.com/jQuery.map/ }\` - * @since 1.0 - * @example ​ ````Use $.map() to change the values of an array. -```html - - - - - jQuery.map demo - - - - -​ -
      -

      - -​ - - - -``` - * @example ​ ````Map the original array to a new one and add 4 to each value. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one, adding 1 to each value if it is bigger then zero and removing it if not. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one; each element is added with its original value and the value plus one. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original object to a new array and double each value. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map an object's keys to an array. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one; each element is squared. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one, removing numbers less than 50 by returning null and subtracting 45 from the rest. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Augment the resulting array by returning an array inside the function. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - */ - map(array: T[], callback: (this: Window, elementOfArray: T, indexInArray: number) => JQuery.TypeOrArray | null | undefined): TReturn[]; - /** - * Translate all items in an array or object to new array of items. - * - * @param obj The Object to translate. - * @param callback The function to process each item against. The first argument to the function is the value; the - * second argument is the key of the object property. The function can return any value to add to the - * array. A returned array will be flattened into the resulting array. Within the function, this refers - * to the global (window) object. - * @see \`{@link https://api.jquery.com/jQuery.map/ }\` - * @since 1.6 - * @example ​ ````Use $.map() to change the values of an array. -```html - - - - - jQuery.map demo - - - - -​ -
      -

      - -​ - - - -``` - * @example ​ ````Map the original array to a new one and add 4 to each value. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one, adding 1 to each value if it is bigger then zero and removing it if not. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one; each element is added with its original value and the value plus one. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original object to a new array and double each value. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map an object's keys to an array. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one; each element is squared. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Map the original array to a new one, removing numbers less than 50 by returning null and subtracting 45 from the rest. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - * @example ​ ````Augment the resulting array by returning an array inside the function. -```html - - - - - jQuery.map demo - - - -​​ - - - -``` - */ - map(obj: T, callback: (this: Window, propertyOfObject: T[K], key: K) => JQuery.TypeOrArray | null | undefined): TReturn[]; - /** - * Merge the contents of two arrays together into the first array. - * - * @param first The first array-like object to merge, the elements of second added. - * @param second The second array-like object to merge into the first, unaltered. - * @see \`{@link https://api.jquery.com/jQuery.merge/ }\` - * @since 1.0 - * @example ​ ````Merges two arrays, altering the first argument. -```html - - - - - jQuery.merge demo - - - -​​ - - - -``` - * @example ​ ````Merges two arrays, altering the first argument. -```html - - - - - jQuery.merge demo - - - -​​ - - - -``` - * @example ​ ````Merges two arrays, but uses a copy, so the original isn't altered. -```html - - - - - jQuery.merge demo - - - -​​ - - - -``` - */ - merge(first: ArrayLike, second: ArrayLike): Array; - /** - * Relinquish jQuery's control of the $ variable. - * - * @param removeAll A Boolean indicating whether to remove all jQuery variables from the global scope (including jQuery itself). - * @see \`{@link https://api.jquery.com/jQuery.noConflict/ }\` - * @since 1.0 - * @example ​ ````Map the original object that was referenced by $ back to $. -```html - - - - - jQuery.noConflict demo - - - -​​ - - - -``` - * @example ​ ````Revert the $ alias and then create and execute a function to provide the $ as a jQuery alias inside the function's scope. Inside the function the original $ object is not available. This works well for most plugins that don't rely on any other library. -```html - - - - - jQuery.noConflict demo - - - -​​ - - - -``` - * @example ​ ````Create a different alias instead of jQuery to use in the rest of the script. -```html - - - - - jQuery.noConflict demo - - - -​​ - - - -``` - * @example ​ ````Completely move jQuery to a new namespace in another object. -```html - - - - - jQuery.noConflict demo - - - -​​ - - - -``` - * @example ​ ````Load two versions of jQuery (not recommended). Then, restore jQuery's globally scoped variables to the first loaded jQuery. -```html - - - - - jQuery.noConflict demo - - - -​ -
      -

      Before $.noConflict(true)

      -
      - -​ - - - -``` - */ - noConflict(removeAll?: boolean): this; - /** - * An empty function. - * - * @see \`{@link https://api.jquery.com/jQuery.noop/ }\` - * @since 1.4 - */ - noop(): undefined; - /** - * Return a number representing the current time. - * - * @see \`{@link https://api.jquery.com/jQuery.now/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link Date.now }\`. - */ - now(): number; - /** - * Create a serialized representation of an array, a plain object, or a jQuery object suitable for use - * in a URL query string or Ajax request. In case a jQuery object is passed, it should contain input - * elements with name/value properties. - * - * @param obj An array, a plain object, or a jQuery object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - * @see \`{@link https://api.jquery.com/jQuery.param/ }\` - * @since 1.2 - * @since 1.4 - * @example ​ ````Serialize a key/value object. -```html - - - - - jQuery.param demo - - - - -​ -
      -​ - - - -``` - * @example ​ ````Serialize a few complex objects -```html - - - - - jQuery.param demo - - - - -​​ - - - -``` - */ - param(obj: any[] | JQuery.PlainObject | JQuery, traditional?: boolean): string; - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context Document element to serve as the context in which the HTML fragment will be created - * @param keepScripts A Boolean indicating whether to include scripts passed in the HTML string - * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` - * @since 1.8 - * @example ​ ````Create an array of DOM nodes using an HTML string and insert it into a div. -```html - - - - - jQuery.parseHTML demo - - - -​ -
      -

      Content:

      -
      -​ - - - -``` - */ - parseHTML(data: string, context: Document | null | undefined, keepScripts: boolean): JQuery.Node[]; - /** - * Parses a string into an array of DOM nodes. - * - * @param data HTML string to be parsed - * @param context_keepScripts Document element to serve as the context in which the HTML fragment will be created - * A Boolean indicating whether to include scripts passed in the HTML string - * @see \`{@link https://api.jquery.com/jQuery.parseHTML/ }\` - * @since 1.8 - * @example ​ ````Create an array of DOM nodes using an HTML string and insert it into a div. -```html - - - - - jQuery.parseHTML demo - - - -​ -
      -

      Content:

      -
      -​ - - - -``` - */ - parseHTML(data: string, context_keepScripts?: Document | null | boolean): JQuery.Node[]; - /** - * Takes a well-formed JSON string and returns the resulting JavaScript value. - * - * @param json The JSON string to parse. - * @see \`{@link https://api.jquery.com/jQuery.parseJSON/ }\` - * @since 1.4.1 - * @deprecated Deprecated since 3.0. Use \`{@link JSON.parse }\`. - * @example ​ ````Parse a JSON string. -```html - - - - - jQuery.parseJSON demo - - - -​​ - - - -``` - */ - parseJSON(json: string): any; - /** - * Parses a string into an XML document. - * - * @param data a well-formed XML string to be parsed - * @see \`{@link https://api.jquery.com/jQuery.parseXML/ }\` - * @since 1.5 - * @example ​ ````Create a jQuery object using an XML string and obtain the value of the title node. -```html - - - - - jQuery.parseXML demo - - - -​ -

      -

      -​ - - - -``` - */ - parseXML(data: string): XMLDocument; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see \`{@link https://api.jquery.com/jQuery.post/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Send form data using Ajax requests -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post a form using Ajax and put results in a div -```html - - - - - jQuery.post demo - - - -​ -
      - - -
      - -
      -​ - - - -``` - */ - post(url: string, - data: JQuery.PlainObject | string, - success: JQuery.jqXHR.DoneCallback | null, - dataType?: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * @param dataType The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html). - * @see \`{@link https://api.jquery.com/jQuery.post/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Send form data using Ajax requests -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post a form using Ajax and put results in a div -```html - - - - - jQuery.post demo - - - -​ -
      - - -
      - -
      -​ - - - -``` - */ - post(url: string, - success: JQuery.jqXHR.DoneCallback | null, - dataType: string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url A string containing the URL to which the request is sent. - * @param success_data A callback function that is executed if the request succeeds. Required if dataType is provided, but - * can be null in that case. - * A plain object or string that is sent to the server with the request. - * @see \`{@link https://api.jquery.com/jQuery.post/ }\` - * @since 1.0 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Send form data using Ajax requests -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post a form using Ajax and put results in a div -```html - - - - - jQuery.post demo - - - -​ -
      - - -
      - -
      -​ - - - -``` - */ - post(url: string, - success_data: JQuery.jqXHR.DoneCallback | JQuery.PlainObject | string): JQuery.jqXHR; - /** - * Load data from the server using a HTTP POST request. - * - * @param url_settings A string containing the URL to which the request is sent. - * A set of key/value pairs that configure the Ajax request. All properties except for url are - * optional. A default can be set for any option with $.ajaxSetup(). See jQuery.ajax( settings ) for a - * complete list of all settings. Type will automatically be set to POST. - * @see \`{@link https://api.jquery.com/jQuery.post/ }\` - * @since 1.0 - * @since 1.12 - * @since 2.2 - * @example ​ ````Request the test.php page, but ignore the return results. -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Request the test.php page and send some additional data along (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Pass arrays of data to the server (while still ignoring the return results). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Send form data using Ajax requests -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Alert the results from requesting test.php with an additional payload of data (HTML or XML, depending on what was returned). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post to the test.php page and get content which has been returned in json format (<?php echo json_encode(array("name"=>"John","time"=>"2pm")); ?>). -```html - - - - - jQuery.post demo - - - -​​ - - - -``` - * @example ​ ````Post a form using Ajax and put results in a div -```html - - - - - jQuery.post demo - - - -​ -
      - - -
      - -
      -​ - - - -``` - */ - post(url_settings?: string | JQuery.UrlAjaxSettings): JQuery.jqXHR; - - // region proxy - // #region proxy - - // region (fn, null | undefined) - // #region (fn, null | undefined) - - // region 0 to 7 additional arguments - // #region 0 to 7 additional arguments - - // region 0 parameters - // #region 0 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C) => TReturn, - context: null | undefined, - a: A, b: B, c: C): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B) => TReturn, - context: null | undefined, - a: A, b: B): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4` - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A) => TReturn, - context: null | undefined, - a: A): () => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: () => TReturn, - context: null | undefined): () => TReturn; - - // #endregion - - // region 1 parameters - // #region 1 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T) => TReturn, - context: null | undefined, - a: A, b: B): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T) => TReturn, - context: null | undefined, - a: A): (t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T) => TReturn, - context: null | undefined): (t: T) => TReturn; - - // #endregion - - // region 2 parameters - // #region 2 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U) => TReturn, - context: null | undefined, - a: A): (t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U) => TReturn, - context: null | undefined): (t: T, u: U) => TReturn; - - // #endregion - - // region 3 parameters - // #region 3 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V) => TReturn, - context: null | undefined, - a: A): (t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V) => TReturn, - context: null | undefined): (t: T, u: U, v: V) => TReturn; - - // #endregion - - // region 4 parameters - // #region 4 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined, - a: A): (t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W) => TReturn, - context: null | undefined): (t: T, u: U, v: V, w: W) => TReturn; - - // #endregion - - // region 5 parameters - // #region 5 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined, - a: A): (t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X) => TReturn, - context: null | undefined): (t: T, u: U, v: V, w: W, x: X) => TReturn; - - // #endregion - - // region 6 parameters - // #region 6 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined, - a: A): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - - // #endregion - - // region 7+ parameters - // #region 7+ parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E, f: F): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D, e: E): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B, c: C, d: D): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B, c: C): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A, b: B): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined, - a: A): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: null | undefined): (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - - // #endregion - - // #endregion - - // region 8+ additional arguments - // #region 8+ additional arguments - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.9 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (...args: any[]) => TReturn, - context: null | undefined, - ...additionalArguments: any[]): (...args: any[]) => TReturn; - - // #endregion - - // #endregion - - // region (fn, context) - // #region (fn, context) - - // region 0 to 7 additional arguments - // #region 0 to 7 additional arguments - - // region 0 parameters - // #region 0 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B) => TReturn, - context: TContext, - a: A, b: B): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4` - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A) => TReturn, - context: TContext, - a: A): (this: TContext) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: () => TReturn, - context: TContext): (this: TContext) => TReturn; - - // #endregion - - // region 1 parameters - // #region 1 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T) => TReturn, - context: TContext, - a: A): (this: TContext, t: T) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T) => TReturn, - context: TContext): (this: TContext, t: T) => TReturn; - - // #endregion - - // region 2 parameters - // #region 2 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U) => TReturn, - context: TContext): (this: TContext, t: T, u: U) => TReturn; - - // #endregion - - // region 3 parameters - // #region 3 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U, v: V) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V) => TReturn, - context: TContext): (this: TContext, t: T, u: U, v: V) => TReturn; - - // #endregion - - // region 4 parameters - // #region 4 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W) => TReturn, - context: TContext): (this: TContext, t: T, u: U, v: V, w: W) => TReturn; - - // #endregion - - // region 5 parameters - // #region 5 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X) => TReturn, - context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X) => TReturn; - - // #endregion - - // region 6 parameters - // #region 6 parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn, - context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y) => TReturn; - - // #endregion - - // region 7+ parameters - // #region 7+ parameters - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, g: G, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F, g: G): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, f: F, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E, f: F): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, e: E, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D, e: E): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, d: D, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B, c: C, d: D): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, c: C, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B, c: C): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, b: B, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A, b: B): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (a: A, - t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext, - a: A): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn, - context: TContext): (this: TContext, t: T, u: U, v: V, w: W, x: X, y: Y, z: Z, ...args: any[]) => TReturn; - - // #endregion - - // #endregion - - // region 8+ additional arguments - // #region 8+ additional arguments - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param fn The function whose context will be changed. - * @param context The object to which the context (`this`) of the function should be set. - * @param additionalArguments Any number of arguments to be passed to the function referenced in the function argument. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(fn: (...args: any[]) => TReturn, - context: TContext, - ...additionalArguments: any[]): (this: TContext, ...args: any[]) => TReturn; - - // #endregion - - // #endregion - - // region (context, name) - // #region (context, name) - - /** - * Takes a function and returns a new one that will always have a particular context. - * - * @param context The object to which the context of the function should be set. - * @param name The name of the function whose context will be changed (should be a property of the context object). - * @param additionalArguments Any number of arguments to be passed to the function named in the name argument. - * @see \`{@link https://api.jquery.com/jQuery.proxy/ }\` - * @since 1.4 - * @since 1.6 - * @deprecated Deprecated since 3.3. Use \`{@link Function.bind }\`. - * @example ​ ````Change the context of functions bound to a click handler using the "function, context" signature. Unbind the first handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - * @example ​ ````Enforce the context of the function using the "context, function name" signature. Unbind the handler after first click. -```html - - - - - jQuery.proxy demo - - - -​ -

      -

      -​ - - - -``` - * @example ​ ````Change the context of a function bound to the click handler, -```html - - - - - jQuery.proxy demo - - - -​ -

      -
      -​ - - - -``` - */ - proxy(context: TContext, - name: keyof TContext, - ...additionalArguments: any[]): (this: TContext, ...args: any[]) => any; - - // #endregion - - // #endregion - - /** - * Manipulate the queue of functions to be executed on the matched element. - * - * @param element A DOM element where the array of queued functions is attached. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue The new function to add to the queue. - * An array of functions to replace the current queue contents. - * @see \`{@link https://api.jquery.com/jQuery.queue/ }\` - * @since 1.3 - * @example ​ ````Show the length of the queue. -```html - - - - - jQuery.queue demo - - - - -​ - - -
      - ​ - - - -``` - * @example ​ ````Queue a custom function. -```html - - - - - jQuery.queue demo - - - - -​ -Click here... -
      -​ - - - -``` - * @example ​ ````Set a queue array to delete the queue. -```html - - - - - jQuery.queue demo - - - - -​ - - -
      -​ - - - -``` - */ - queue(element: T, queueName?: string, newQueue?: JQuery.TypeOrArray>): JQuery.Queue; - /** - * Handles errors thrown synchronously in functions wrapped in jQuery(). - * - * @param error An error thrown in the function wrapped in jQuery(). - * @see \`{@link https://api.jquery.com/jQuery.readyException/ }\` - * @since 3.1 - * @example ​ ````Pass the received error to console.error. -```html - - - - - jQuery.readyException demo - - - -​​ - - - -``` - */ - readyException(error: Error): any; - /** - * Remove a previously-stored piece of data. - * - * @param element A DOM element from which to remove data. - * @param name A string naming the piece of data to remove. - * @see \`{@link https://api.jquery.com/jQuery.removeData/ }\` - * @since 1.2.3 - * @example ​ ````Set a data store for 2 names then remove one of them. -```html - - - - - jQuery.removeData demo - - - - -​ -
      value1 before creation:
      -
      value1 after creation:
      -
      value1 after removal:
      -
      value2 after removal:
      -​ - - - -``` - */ - removeData(element: Element, name?: string): void; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` - * @since 1.1 - */ - speed(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): JQuery.EffectsOptions; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` - * @since 1.0 - * @since 1.1 - */ - speed(duration: JQuery.Duration, - easing_complete: string | ((this: TElement) => void)): JQuery.EffectsOptions; - /** - * Creates an object containing a set of properties ready to be used in the definition of custom animations. - * - * @param duration_complete_settings A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/jQuery.speed/ }\` - * @since 1.0 - * @since 1.1 - */ - speed(duration_complete_settings?: JQuery.Duration | ((this: TElement) => void) | JQuery.SpeedSettings): JQuery.EffectsOptions; - /** - * Remove the whitespace from the beginning and end of a string. - * - * @param str The string to trim. - * @see \`{@link https://api.jquery.com/jQuery.trim/ }\` - * @since 1.0 - * @example ​ ````Remove the white spaces at the start and at the end of the string. -```html - - - - - jQuery.trim demo - - - -​ -
      
      -
      
      -​
      -
      -
      -
      -```
      -     * @example ​ ````Remove the white spaces at the start and at the end of the string.
      -```html
      -
      -
      -
      -  
      -  jQuery.trim demo
      -  
      -
      -
      -​​
      -
      -
      -
      -```
      -     */
      -    trim(str: string): string;
      -    /**
      -     * Determine the internal JavaScript [[Class]] of an object.
      -     *
      -     * @param obj Object to get the internal JavaScript [[Class]] of.
      -     * @see \`{@link https://api.jquery.com/jQuery.type/ }\`
      -     * @since 1.4.3
      -     * @deprecated Deprecated since 3.3. See \`{@link https://github.com/jquery/jquery/issues/3605 }`.
      -     * @example ​ ````Find out if the parameter is a RegExp.
      -```html
      -
      -
      -
      -  
      -  jQuery.type demo
      -  
      -
      -
      -​
      -Is it a RegExp? 
      -​
      -
      -
      -
      -```
      -     */
      -    type(obj: any): 'array' | 'boolean' | 'date' | 'error' | 'function' | 'null' | 'number' | 'object' | 'regexp' | 'string' | 'symbol' | 'undefined';
      -    /**
      -     * @description Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on
      -     * arrays of DOM elements, not strings or numbers.
      -     *
      -     * @param array The Array of DOM elements.
      -     * @see \`{@link https://api.jquery.com/jQuery.unique/ }\`
      -     * @since 1.1.3
      -     * @deprecated Deprecated since 3.0. Use \`{@link JQueryStatic.uniqueSort }`.
      -     * @example ​ ````Removes any duplicate elements from the array of divs.
      -```html
      -
      -
      -
      -  
      -  jQuery.unique demo
      -  
      -  
      -
      -
      -​
      -
      There are 6 divs in this document.
      -
      -
      -
      -
      -
      -​ - - - -``` - */ - unique(array: T[]): T[]; - /** - * Sorts an array of DOM elements, in place, with the duplicates removed. Note that this only works on - * arrays of DOM elements, not strings or numbers. - * - * @param array The Array of DOM elements. - * @see \`{@link https://api.jquery.com/jQuery.uniqueSort/ }\` - * @since 1.12 - * @since 2.2 - * @example ​ ````Removes any duplicate elements from the array of divs. -```html - - - - - jQuery.uniqueSort demo - - - - -​ -
      There are 6 divs in this document.
      -
      -
      -
      -
      -
      -​ - - - -``` - */ - uniqueSort(array: T[]): T[]; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when( - deferredT: JQuery.Promise | JQuery.Thenable | TR1, // tslint:disable-line:use-default-type-parameter - deferredU: JQuery.Promise | JQuery.Thenable | UR1, // tslint:disable-line:use-default-type-parameter - deferredV: JQuery.Promise | JQuery.Thenable | VR1): JQuery.Promise3; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when( - deferredT: JQuery.Promise | JQuery.Thenable | TR1, // tslint:disable-line:use-default-type-parameter - deferredU: JQuery.Promise | JQuery.Thenable | UR1): JQuery.Promise2; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when( - deferredT: JQuery.Promise3 | - JQuery.Promise2): JQuery.Promise3; - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when(deferred: JQuery.Promise | JQuery.Thenable | TR1): JQuery.Promise; // tslint:disable-line:use-default-type-parameter - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @param deferreds Zero or more Thenable objects. - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when(...deferreds: Array | JQuery.Thenable | TR1>): JQuery.Promise; // tslint:disable-line:use-default-type-parameter - /** - * Provides a way to execute callback functions based on zero or more Thenable objects, usually - * Deferred objects that represent asynchronous events. - * - * @param deferreds Zero or more Thenable objects. - * @see \`{@link https://api.jquery.com/jQuery.when/ }\` - * @since 1.5 - * @example ​ ````Execute a function after two Ajax requests are successful. (See the jQuery.ajax() documentation for a complete description of success and error cases for an ajax request). -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - * @example ​ ````Execute the function myFunc when both ajax requests are successful, or myFailure if either one has an error. -```html - - - - - jQuery.when demo - - - -​​ - - - -``` - */ - when(...deferreds: any[]): JQuery.Promise; -} - -interface JQuery extends Iterable { - /** - * A string containing the jQuery version number. - * - * @see \`{@link https://api.jquery.com/jquery-2/#jquery1 }\` - * @since 1.0 - * @example ​ ````Determine if an object is a jQuery object -```html - - - - - jquery demo - - - -​​ - - - -``` - * @example ​ ````Get the current version of jQuery running on the page -```html - - - - - jquery demo - - - -​​ - - - -``` - */ - jquery: string; - /** - * The number of elements in the jQuery object. - * - * @see \`{@link https://api.jquery.com/length/ }\` - * @since 1.0 - * @example ​ ````Count the divs. Click to add more. -```html - - - - - length demo - - - - -​ -
      ​ - - - -``` - */ - length: number; - /** - * Create a new jQuery object with elements added to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * @param context The point in the document at which the selector should begin matching; similar to the context - * argument of the $(selector, context) method. - * @see \`{@link https://api.jquery.com/add/ }\` - * @since 1.4 - * @example ​ ````Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow. -```html - - - - - add demo - - - - -​ -
      -
      -
      -
      -
      -
      -​ -

      Added this... (notice no border)

      -​ - - - -``` - * @example ​ ````Adds more elements, matched by the given expression, to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - * @example ​ ````Adds more elements, created on the fly, to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -​ - - - -``` - * @example ​ ````Adds one or more Elements to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - * @example ​ ````Demonstrates how to add (or push) elements to an existing collection -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - */ - add(selector: JQuery.Selector, context: Element): this; - /** - * Create a new jQuery object with elements added to the set of matched elements. - * - * @param selector A string representing a selector expression to find additional elements to add to the set of matched elements. - * One or more elements to add to the set of matched elements. - * An HTML fragment to add to the set of matched elements. - * An existing jQuery object to add to the set of matched elements. - * @see \`{@link https://api.jquery.com/add/ }\` - * @since 1.0 - * @since 1.3.2 - * @example ​ ````Finds all divs and makes a border. Then adds all paragraphs to the jQuery object to set their backgrounds yellow. -```html - - - - - add demo - - - - -​ -
      -
      -
      -
      -
      -
      -​ -

      Added this... (notice no border)

      -​ - - - -``` - * @example ​ ````Adds more elements, matched by the given expression, to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - * @example ​ ````Adds more elements, created on the fly, to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -​ - - - -``` - * @example ​ ````Adds one or more Elements to the set of matched elements. -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - * @example ​ ````Demonstrates how to add (or push) elements to an existing collection -```html - - - - - add demo - - - -​ -

      Hello

      -Hello Again -​ - - - -``` - */ - add(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery.htmlString | JQuery): this; - /** - * Add the previous set of elements on the stack to the current set, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match the current set of elements against. - * @see \`{@link https://api.jquery.com/addBack/ }\` - * @since 1.8 - * @example ​ ````The .addBack() method causes the previous set of DOM elements in the traversal stack to be added to the current set. In the first example, the top stack contains the set resulting from .find("p"). In the second example, .addBack() adds the previous set of elements on the stack — in this case $("div.after-addback") — to the current set, selecting both the div and its enclosed paragraphs. -```html - - - - - addBack demo - - - - -​ -
      -

      Before addBack()

      -
      -

      First Paragraph

      -

      Second Paragraph

      -
      -
      -
      -

      After addBack()

      -
      -

      First Paragraph

      -

      Second Paragraph

      -
      -
      -​ - - - -``` - */ - addBack(selector?: JQuery.Selector): this; - /** - * Adds the specified class(es) to each element in the set of matched elements. - * - * @param className One or more space-separated classes to be added to the class attribute of each matched element. - * An array of classes to be added to the class attribute of each matched element. - * A function returning one or more space-separated class names to be added to the existing class - * name(s). Receives the index position of the element in the set and the existing class name(s) as - * arguments. Within the function, this refers to the current element in the set. - * @see \`{@link https://api.jquery.com/addClass/ }\` - * @since 1.0 - * @since 1.4 - * @since 3.3 - * @example ​ ````Add the class "selected" to the matched elements. -```html - - - - - addClass demo - - - - -​ -

      Hello

      -

      and

      -

      Goodbye

      -​ - - - -``` - * @example ​ ````Add the classes "selected" and "highlight" to the matched elements. -```html - - - - - addClass demo - - - - -​ -

      Hello

      -

      and

      -

      Goodbye

      -​ - - - -``` - * @example ​ ````Pass in a function to .addClass() to add the "green" class to a div that already has a "red" class. -```html - - - - - addClass demo - - - - -​ -
      This div should be white
      -
      This div will be green because it now has the "green" and "red" classes. - It would be red if the addClass function failed.
      -
      This div should be white
      -

      There are zero green divs

      -​ - - - -``` - */ - addClass(className: JQuery.TypeOrArray | ((this: TElement, index: number, currentClassName: string) => string)): this; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or - * jQuery objects to insert after each element in the set of matched elements. - * @see \`{@link https://api.jquery.com/after/ }\` - * @since 1.0 - * @example ​ ````Inserts some HTML after all paragraphs. -```html - - - - - after demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Inserts a DOM element after all paragraphs. -```html - - - - - after demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs. -```html - - - - - after demo - - - - -​ -Hello -

      I would like to say:

      -​ - - - -``` - */ - after(...contents: Array>>): this; - /** - * Insert content, specified by the parameter, after each element in the set of matched elements. - * - * @param fn A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert - * after each element in the set of matched elements. Receives the index position of the element in the - * set and the old HTML value of the element as arguments. Within the function, this refers to the - * current element in the set. - * @see \`{@link https://api.jquery.com/after/ }\` - * @since 1.4 - * @since 1.10 - * @example ​ ````Inserts some HTML after all paragraphs. -```html - - - - - after demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Inserts a DOM element after all paragraphs. -```html - - - - - after demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) after all paragraphs. -```html - - - - - after demo - - - - -​ -Hello -

      I would like to say:

      -​ - - - -``` - */ - after(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; - /** - * Register a handler to be called when Ajax requests complete. This is an AjaxEvent. - * - * @param handler The function to be invoked. - * @see \`{@link https://api.jquery.com/ajaxComplete/ }\` - * @since 1.0 - * @example ​ ````Show a message when an Ajax request completes. -```html - - - - - ajaxComplete demo - - - -​​ - - - -``` - */ - ajaxComplete(handler: (this: Document, event: JQuery.Event, 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. - * @see \`{@link https://api.jquery.com/ajaxError/ }\` - * @since 1.0 - * @example ​ ````Show a message when an Ajax request fails. -```html - - - - - ajaxError demo - - - -​​ - - - -``` - */ - ajaxError(handler: (this: Document, event: JQuery.Event, 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. - * @see \`{@link https://api.jquery.com/ajaxSend/ }\` - * @since 1.0 - * @example ​ ````Show a message before an Ajax request is sent. -```html - - - - - ajaxSend demo - - - -​​ - - - -``` - */ - ajaxSend(handler: (this: Document, event: JQuery.Event, 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. - * @see \`{@link https://api.jquery.com/ajaxStart/ }\` - * @since 1.0 - * @example ​ ````Show a loading message whenever an Ajax request starts (and none is already active). -```html - - - - - ajaxStart demo - - - -​​ - - - -``` - */ - ajaxStart(handler: (this: Document) => void | false): this; - /** - * Register a handler to be called when all Ajax requests have completed. This is an Ajax Event. - * - * @param handler The function to be invoked. - * @see \`{@link https://api.jquery.com/ajaxStop/ }\` - * @since 1.0 - * @example ​ ````Hide a loading message after all the Ajax requests have stopped. -```html - - - - - ajaxStop demo - - - -​​ - - - -``` - */ - ajaxStop(handler: (this: Document) => void | false): this; - /** - * Attach a function to be executed whenever an Ajax request completes successfully. This is an Ajax Event. - * - * @param handler The function to be invoked. - * @see \`{@link https://api.jquery.com/ajaxSuccess/ }\` - * @since 1.0 - * @example ​ ````Show a message when an Ajax request completes successfully. -```html - - - - - ajaxSuccess demo - - - -​​ - - - -``` - */ - ajaxSuccess(handler: (this: Document, event: JQuery.Event, 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. - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/animate/ }\` - * @since 1.0 - * @example ​ ````Click the button to animate the div with a number of different properties. -```html - - - - - animate demo - - - - -​ - -
      Hello!
      -​ - - - -``` - * @example ​ ````Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. -```html - - - - - animate demo - - - - -​ - - -
      -​ - - - -``` - * @example ​ ````The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. - -The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed. -```html - - - - - animate demo - - - - -​ - - - - -
      Block1
      -
      Block2
      -​ - - - -``` - * @example ​ ````Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. -```html - - - - - animate demo - - - - -​ -

      -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. -```html - - - - - animate demo - - - -​​ - - - -``` - */ - animate(properties: JQuery.PlainObject, - duration: JQuery.Duration, - easing: string, - complete?: (this: TElement) => void): 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. - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/animate/ }\` - * @since 1.0 - * @example ​ ````Click the button to animate the div with a number of different properties. -```html - - - - - animate demo - - - - -​ - -
      Hello!
      -​ - - - -``` - * @example ​ ````Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. -```html - - - - - animate demo - - - - -​ - - -
      -​ - - - -``` - * @example ​ ````The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. - -The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed. -```html - - - - - animate demo - - - - -​ - - - - -
      Block1
      -
      Block2
      -​ - - - -``` - * @example ​ ````Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. -```html - - - - - animate demo - - - - -​ -

      -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. -```html - - - - - animate demo - - - -​​ - - - -``` - */ - animate(properties: JQuery.PlainObject, - duration_easing: JQuery.Duration | string, - complete?: (this: TElement) => void): 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. - * @param options A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/animate/ }\` - * @since 1.0 - * @example ​ ````Click the button to animate the div with a number of different properties. -```html - - - - - animate demo - - - - -​ - -
      Hello!
      -​ - - - -``` - * @example ​ ````Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. -```html - - - - - animate demo - - - - -​ - - -
      -​ - - - -``` - * @example ​ ````The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. - -The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed. -```html - - - - - animate demo - - - - -​ - - - - -
      Block1
      -
      Block2
      -​ - - - -``` - * @example ​ ````Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. -```html - - - - - animate demo - - - - -​ -

      -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. -```html - - - - - animate demo - - - -​​ - - - -``` - */ - animate(properties: JQuery.PlainObject, - options: JQuery.EffectsOptions): 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. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/animate/ }\` - * @since 1.0 - * @example ​ ````Click the button to animate the div with a number of different properties. -```html - - - - - animate demo - - - - -​ - -
      Hello!
      -​ - - - -``` - * @example ​ ````Animates a div's left property with a relative value. Click several times on the buttons to see the relative animations queued up. -```html - - - - - animate demo - - - - -​ - - -
      -​ - - - -``` - * @example ​ ````The first button shows how an unqueued animation works. It expands the div out to 90% width while the font-size is increasing. Once the font-size change is complete, the border animation will begin. - -The second button starts a traditional chained animation, where each animation will start once the previous animation on the element has completed. -```html - - - - - animate demo - - - - -​ - - - - -
      Block1
      -
      Block2
      -​ - - - -``` - * @example ​ ````Animates the first div's left property and synchronizes the remaining divs, using the step function to set their left properties at each stage of the animation. -```html - - - - - animate demo - - - - -​ -

      -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Animate all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs to a left style of 50 and opacity of 1 (opaque, visible), completing the animation within 500 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate the left and opacity style properties of all paragraphs; run the animation outside the queue, so that it will automatically start without waiting for its turn. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````An example of using an 'easing' function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. Note, this code will do nothing unless the paragraph element is hidden. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animates all paragraphs to toggle both height and opacity, completing the animation within 600 milliseconds. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Use an easing function to provide a different style of animation. This will only work if you have a plugin that provides this easing function. -```html - - - - - animate demo - - - -​​ - - - -``` - * @example ​ ````Animate all paragraphs and execute a callback function when the animation is complete. The first argument is an object of CSS properties, the second specifies that the animation should take 1000 milliseconds to complete, the third states the easing type, and the fourth argument is an anonymous callback function. -```html - - - - - animate demo - - - -​​ - - - -``` - */ - animate(properties: JQuery.PlainObject, - complete?: (this: TElement) => void): this; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or - * jQuery objects to insert at the end of each element in the set of matched elements. - * @see \`{@link https://api.jquery.com/append/ }\` - * @since 1.0 - * @example ​ ````Appends some HTML to all paragraphs. -```html - - - - - append demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Appends an Element to all paragraphs. -```html - - - - - append demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. -```html - - - - - append demo - - - - -​ -Hello world!!! -

      I would like to say:

      -​ - - - -``` - */ - append(...contents: Array>>): this; - /** - * Insert content, specified by the parameter, to the end of each element in the set of matched elements. - * - * @param fn A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at - * the end of each element in the set of matched elements. Receives the index position of the element - * in the set and the old HTML value of the element as arguments. Within the function, this refers to - * the current element in the set. - * @see \`{@link https://api.jquery.com/append/ }\` - * @since 1.4 - * @example ​ ````Appends some HTML to all paragraphs. -```html - - - - - append demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Appends an Element to all paragraphs. -```html - - - - - append demo - - - - -​ -

      I would like to say:

      -​ - - - -``` - * @example ​ ````Appends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. -```html - - - - - append demo - - - - -​ -Hello world!!! -

      I would like to say:

      -​ - - - -``` - */ - append(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; - /** - * Insert every element in the set of matched elements to the end of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements - * will be inserted at the end of the element(s) specified by this parameter. - * @see \`{@link https://api.jquery.com/appendTo/ }\` - * @since 1.0 - * @example ​ ````Append all spans to the element with the ID "foo" (Check append() documentation for more examples) -```html - - - - - appendTo demo - - - - -​ -I have nothing more to say... -​ -
      FOO!
      -​ - - - -``` - */ - appendTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributeName The name of the attribute to set. - * @param value A value to set for the attribute. If null, the specified attribute will be removed (as in .removeAttr()). - * A function returning the value to set. this is the current element. Receives the index position of - * the element in the set and the old attribute value as arguments. - * @see \`{@link https://api.jquery.com/attr/ }\` - * @since 1.0 - * @since 1.1 - * @example ​ ````Display the checked attribute and property of a checkbox as it changes. -```html - - - - - attr demo - - - - -​ - - -

      -​ - - - -``` - * @example ​ ````Find the title attribute of the first <em> in the page. -```html - - - - - attr demo - - - - -​ -

      Once there was a large dinosaur...

      -​ -The title of the emphasis is:
      -​ - - - -``` - * @example ​ ````Set some attributes for all <img>s in the page. -```html - - - - - attr demo - - - - -​ - - - -​ -
      Attribute of Ajax
      -​ - - - -``` - * @example ​ ````Set the id for divs based on the position in the page. -```html - - - - - attr demo - - - - -​ -
      Zero-th
      -
      First
      -
      Second
      -​ - - - -``` - * @example ​ ````Set the src attribute from title attribute on the image. -```html - - - - - attr demo - - - -​ - -​ - - - -``` - */ - attr(attributeName: string, - value: string | number | null | ((this: TElement, index: number, attr: string) => string | number | void | undefined)): this; - /** - * Set one or more attributes for the set of matched elements. - * - * @param attributes An object of attribute-value pairs to set. - * @see \`{@link https://api.jquery.com/attr/ }\` - * @since 1.0 - * @example ​ ````Display the checked attribute and property of a checkbox as it changes. -```html - - - - - attr demo - - - - -​ - - -

      -​ - - - -``` - * @example ​ ````Find the title attribute of the first <em> in the page. -```html - - - - - attr demo - - - - -​ -

      Once there was a large dinosaur...

      -​ -The title of the emphasis is:
      -​ - - - -``` - * @example ​ ````Set some attributes for all <img>s in the page. -```html - - - - - attr demo - - - - -​ - - - -​ -
      Attribute of Ajax
      -​ - - - -``` - * @example ​ ````Set the id for divs based on the position in the page. -```html - - - - - attr demo - - - - -​ -
      Zero-th
      -
      First
      -
      Second
      -​ - - - -``` - * @example ​ ````Set the src attribute from title attribute on the image. -```html - - - - - attr demo - - - -​ - -​ - - - -``` - */ - attr(attributes: JQuery.PlainObject): this; - /** - * Get the value of an attribute for the first element in the set of matched elements. - * - * @param attributeName The name of the attribute to get. - * @see \`{@link https://api.jquery.com/attr/ }\` - * @since 1.0 - * @example ​ ````Display the checked attribute and property of a checkbox as it changes. -```html - - - - - attr demo - - - - -​ - - -

      -​ - - - -``` - * @example ​ ````Find the title attribute of the first <em> in the page. -```html - - - - - attr demo - - - - -​ -

      Once there was a large dinosaur...

      -​ -The title of the emphasis is:
      -​ - - - -``` - * @example ​ ````Set some attributes for all <img>s in the page. -```html - - - - - attr demo - - - - -​ - - - -​ -
      Attribute of Ajax
      -​ - - - -``` - * @example ​ ````Set the id for divs based on the position in the page. -```html - - - - - attr demo - - - - -​ -
      Zero-th
      -
      First
      -
      Second
      -​ - - - -``` - * @example ​ ````Set the src attribute from title attribute on the image. -```html - - - - - attr demo - - - -​ - -​ - - - -``` - */ - attr(attributeName: string): string | undefined; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or - * jQuery objects to insert before each element in the set of matched elements. - * @see \`{@link https://api.jquery.com/before/ }\` - * @since 1.0 - * @example ​ ````Inserts some HTML before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      -​ - - - -``` - * @example ​ ````Inserts a DOM element before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      -​ - - - -``` - * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      Hello -​ - - - -``` - */ - before(...contents: Array>>): this; - /** - * Insert content, specified by the parameter, before each element in the set of matched elements. - * - * @param fn A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert - * before each element in the set of matched elements. Receives the index position of the element in - * the set and the old HTML value of the element as arguments. Within the function, this refers to the - * current element in the set. - * @see \`{@link https://api.jquery.com/before/ }\` - * @since 1.4 - * @since 1.10 - * @example ​ ````Inserts some HTML before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      -​ - - - -``` - * @example ​ ````Inserts a DOM element before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      -​ - - - -``` - * @example ​ ````Inserts a jQuery object (similar to an Array of DOM Elements) before all paragraphs. -```html - - - - - before demo - - - - -​ -

      is what I said...

      Hello -​ - - - -``` - */ - before(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; - // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 - /** - * 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. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/bind/ }\` - * @since 1.0 - * @since 1.4.3 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe. -```html - - - - - bind demo - - - - -​ -

      Click or double click here.

      - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````You can pass some extra data before the event handler: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel a default action and prevent it from bubbling up by returning false: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using the .preventDefault() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Stop an event from bubbling without preventing the default action by using the .stopPropagation() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Bind custom events. -```html - - - - - bind demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - * @example ​ ````Bind multiple events simultaneously. -```html - - - - - bind demo - - - -​​ - - - -``` - */ - bind(eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @param handler A function to execute each time the event is triggered. - * Setting the second argument to false will attach a function that prevents the default action from - * occurring and stops the event from bubbling. - * @see \`{@link https://api.jquery.com/bind/ }\` - * @since 1.0 - * @since 1.4.3 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe. -```html - - - - - bind demo - - - - -​ -

      Click or double click here.

      - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````You can pass some extra data before the event handler: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel a default action and prevent it from bubbling up by returning false: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using the .preventDefault() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Stop an event from bubbling without preventing the default action by using the .stopPropagation() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Bind custom events. -```html - - - - - bind demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - * @example ​ ````Bind multiple events simultaneously. -```html - - - - - bind demo - - - -​​ - - - -``` - */ - bind(eventType: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @see \`{@link https://api.jquery.com/bind/ }\` - * @since 1.4 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Handle click and double-click for the paragraph. Note: the coordinates are window relative, so in this case relative to the demo iframe. -```html - - - - - bind demo - - - - -​ -

      Click or double click here.

      - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````You can pass some extra data before the event handler: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel a default action and prevent it from bubbling up by returning false: -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using the .preventDefault() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Stop an event from bubbling without preventing the default action by using the .stopPropagation() method. -```html - - - - - bind demo - - - -​​ - - - -``` - * @example ​ ````Bind custom events. -```html - - - - - bind demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - * @example ​ ````Bind multiple events simultaneously. -```html - - - - - bind demo - - - -​​ - - - -``` - */ - bind(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/blur/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To trigger the blur event on all paragraphs: -```html - - - - - blur demo - - - -​​ - - - -``` - */ - blur(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/blur/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To trigger the blur event on all paragraphs: -```html - - - - - blur demo - - - -​​ - - - -``` - */ - blur(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/change/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw. -```html - - - - - change demo - - - - -​ - -
      -​ - - - -``` - * @example ​ ````To add a validity test to all text input elements: -```html - - - - - change demo - - - -​​ - - - -``` - */ - change(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/change/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Attaches a change event to the select that gets the text for each selected option and writes them in the div. It then triggers the event for the initial text draw. -```html - - - - - change demo - - - - -​ - -
      -​ - - - -``` - * @example ​ ````To add a validity test to all text input elements: -```html - - - - - change demo - - - -​​ - - - -``` - */ - change(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @see \`{@link https://api.jquery.com/children/ }\` - * @since 1.0 - * @example ​ ````Find all children of the clicked element. -```html - - - - - children demo - - - - -​ -
      -
      -

      This is the way we - write the demo,

      -
      -​ -
      - write the demo, demo, -
      -​ -
      - This the way we write the demo so - in -
      -​ -

      - the morning. - Found 0 children in TAG. -

      -
      -​ - - - -``` - * @example ​ ````Find all children of each div. -```html - - - - - children demo - - - - -​ -

      Hello (this is a paragraph)

      -​ -
      Hello Again (this span is a child of the a div)
      -

      And Again (in another paragraph)

      -​ -
      And One Last Time (most text directly in a div)
      -​ - - - -``` - * @example ​ ````Find all children with a class "selected" of each div. -```html - - - - - children demo - - - - -​ -
      - Hello -

      Hello Again

      -
      And Again
      -

      And One Last Time

      -
      -​ - - - -``` - */ - children(selector?: JQuery.Selector): this; - /** - * Remove from the queue all items that have not yet been run. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see \`{@link https://api.jquery.com/clearQueue/ }\` - * @since 1.4 - * @example ​ ````Empty the queue. -```html - - - - - clearQueue demo - - - - -​ - - -
      -​ - - - -``` - */ - clearQueue(queueName?: string): this; - /** - * Bind an event handler to the "click" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/click/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Hide paragraphs on a page when they are clicked: -```html - - - - - click demo - - - - -​ -

      First Paragraph

      -

      Second Paragraph

      -

      Yet one more Paragraph

      -​ - - - -``` - * @example ​ ````Trigger the click event on all of the paragraphs on the page: -```html - - - - - click demo - - - -​​ - - - -``` - */ - click(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/click/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Hide paragraphs on a page when they are clicked: -```html - - - - - click demo - - - - -​ -

      First Paragraph

      -

      Second Paragraph

      -

      Yet one more Paragraph

      -​ - - - -``` - * @example ​ ````Trigger the click event on all of the paragraphs on the page: -```html - - - - - click demo - - - -​​ - - - -``` - */ - click(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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 - * default value is false. *In jQuery 1.5.0 the default value was incorrectly true; it was changed back - * to false in 1.5.1 and up. - * @param deepWithDataAndEvents A Boolean indicating whether event handlers and data for all children of the cloned element should - * be copied. By default its value matches the first argument's value (which defaults to false). - * @see \`{@link https://api.jquery.com/clone/ }\` - * @since 1.0 - * @since 1.5 - * @example ​ ````Clones all b elements (and selects the clones) and prepends them to all paragraphs. -```html - - - - - clone demo - - - -​ -Hello

      , how are you?

      -​ - - - -``` - */ - clone(withDataAndEvents?: boolean, deepWithDataAndEvents?: boolean): this; - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * @param context A DOM element within which a matching element may be found. - * @see \`{@link https://api.jquery.com/closest/ }\` - * @since 1.4 - * @example ​ ````Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked. -```html - - - - - closest demo - - - - -​ -
        -
      • Click me!
      • -
      • You can also Click me!
      • -
      -​ - - - -``` - * @example ​ ````Pass a jQuery object to closest. The closest list element toggles a yellow background when it or its descendent is clicked. -```html - - - - - closest demo - - - - -​ -
        -
      • Click me!
      • -
      • You can also Click me!
      • -
      -​ - - - -``` - */ - closest(selector: JQuery.Selector, context: Element): this; - /** - * For each element in the set, get the first element that matches the selector by testing the element - * itself and traversing up through its ancestors in the DOM tree. - * - * @param selector A string containing a selector expression to match elements against. - * A jQuery object to match elements against. - * An element to match elements against. - * @see \`{@link https://api.jquery.com/closest/ }\` - * @since 1.3 - * @since 1.6 - * @example ​ ````Show how event delegation can be done with closest. The closest list element toggles a yellow background when it or its descendent is clicked. -```html - - - - - closest demo - - - - -​ -
        -
      • Click me!
      • -
      • You can also Click me!
      • -
      -​ - - - -``` - * @example ​ ````Pass a jQuery object to closest. The closest list element toggles a yellow background when it or its descendent is clicked. -```html - - - - - closest demo - - - - -​ -
        -
      • Click me!
      • -
      • You can also Click me!
      • -
      -​ - - - -``` - */ - closest(selector: JQuery.Selector | Element | JQuery): this; - /** - * Get the children of each element in the set of matched elements, including text and comment nodes. - * - * @see \`{@link https://api.jquery.com/contents/ }\` - * @since 1.2 - * @example ​ ````Find all the text nodes inside a paragraph and wrap them with a bold tag. -```html - - - - - contents demo - - - -​ -

      Hello John, how are you doing?

      -​ - - - -``` - * @example ​ ````Change the background color of links inside of an iframe. -```html - - - - - contents demo - - - -​ - -​ - - - -``` - */ - 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/contextmenu/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page: -```html - - - - - contextmenu demo - - - -​​ - - - -``` - * @example ​ ````Right click to toggle background color. -```html - - - - - contextmenu demo - - - - -​ -
      -Right click the block -​ - - - -``` - */ - contextmenu(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/contextmenu/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To show a "Hello World!" alert box when the contextmenu event is triggered on a paragraph on the page: -```html - - - - - contextmenu demo - - - -​​ - - - -``` - * @example ​ ````Right click to toggle background color. -```html - - - - - contextmenu demo - - - - -​ -
      -Right click the block -​ - - - -``` - */ - contextmenu(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param propertyName A CSS property name. - * @param value A value to set for the property. - * A function returning the value to set. this is the current element. Receives the index position of - * the element in the set and the old value as arguments. - * @see \`{@link https://api.jquery.com/css/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Get the background color of a clicked div. -```html - - - - - css demo - - - - -​ -  -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Get the width, height, text color, and background color of a clicked div. -```html - - - - - css demo - - - - -​ -

       

      -
      1
      -
      2
      -
      3
      -
      4
      -​ - - - -``` - * @example ​ ````Change the color of any paragraph to red on mouseover event. -```html - - - - - css demo - - - - -​ -

      Just roll the mouse over me.

      -​ -

      Or me to see a color change.

      -​ - - - -``` - * @example ​ ````Increase the width of #box by 200 pixels the first time it is clicked. -```html - - - - - css demo - - - - -​ -
      Click me to grow
      -​ - - - -``` - * @example ​ ````Highlight a clicked word in the paragraph. -```html - - - - - css demo - - - - -​ -

      - Once upon a time there was a man - who lived in a pizza parlor. This - man just loved pizza and ate it all - the time. He went on to be the - happiest man in the world. The end. -

      -​ - - - -``` - * @example ​ ````Change the font weight and background color on mouseenter and mouseleave. -```html - - - - - css demo - - - - -​ -

      Move the mouse over a paragraph.

      -

      Like this one or the one above.

      -​ - - - -``` - * @example ​ ````Increase the size of a div when you click it. -```html - - - - - css demo - - - - -​ -
      click
      -
      click
      -​ - - - -``` - */ - css(propertyName: string, - value: string | number | ((this: TElement, index: number, value: string) => string | number | void | undefined)): this; - /** - * Set one or more CSS properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - * @see \`{@link https://api.jquery.com/css/ }\` - * @since 1.0 - * @example ​ ````Get the background color of a clicked div. -```html - - - - - css demo - - - - -​ -  -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Get the width, height, text color, and background color of a clicked div. -```html - - - - - css demo - - - - -​ -

       

      -
      1
      -
      2
      -
      3
      -
      4
      -​ - - - -``` - * @example ​ ````Change the color of any paragraph to red on mouseover event. -```html - - - - - css demo - - - - -​ -

      Just roll the mouse over me.

      -​ -

      Or me to see a color change.

      -​ - - - -``` - * @example ​ ````Increase the width of #box by 200 pixels the first time it is clicked. -```html - - - - - css demo - - - - -​ -
      Click me to grow
      -​ - - - -``` - * @example ​ ````Highlight a clicked word in the paragraph. -```html - - - - - css demo - - - - -​ -

      - Once upon a time there was a man - who lived in a pizza parlor. This - man just loved pizza and ate it all - the time. He went on to be the - happiest man in the world. The end. -

      -​ - - - -``` - * @example ​ ````Change the font weight and background color on mouseenter and mouseleave. -```html - - - - - css demo - - - - -​ -

      Move the mouse over a paragraph.

      -

      Like this one or the one above.

      -​ - - - -``` - * @example ​ ````Increase the size of a div when you click it. -```html - - - - - css demo - - - - -​ -
      click
      -
      click
      -​ - - - -``` - */ - css(properties: JQuery.PlainObject string | number | void | undefined)>): this; - /** - * Get the computed style properties for the first element in the set of matched elements. - * - * @param propertyName A CSS property. - * An array of one or more CSS properties. - * @see \`{@link https://api.jquery.com/css/ }\` - * @since 1.0 - * @example ​ ````Get the background color of a clicked div. -```html - - - - - css demo - - - - -​ -  -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Get the width, height, text color, and background color of a clicked div. -```html - - - - - css demo - - - - -​ -

       

      -
      1
      -
      2
      -
      3
      -
      4
      -​ - - - -``` - * @example ​ ````Change the color of any paragraph to red on mouseover event. -```html - - - - - css demo - - - - -​ -

      Just roll the mouse over me.

      -​ -

      Or me to see a color change.

      -​ - - - -``` - * @example ​ ````Increase the width of #box by 200 pixels the first time it is clicked. -```html - - - - - css demo - - - - -​ -
      Click me to grow
      -​ - - - -``` - * @example ​ ````Highlight a clicked word in the paragraph. -```html - - - - - css demo - - - - -​ -

      - Once upon a time there was a man - who lived in a pizza parlor. This - man just loved pizza and ate it all - the time. He went on to be the - happiest man in the world. The end. -

      -​ - - - -``` - * @example ​ ````Change the font weight and background color on mouseenter and mouseleave. -```html - - - - - css demo - - - - -​ -

      Move the mouse over a paragraph.

      -

      Like this one or the one above.

      -​ - - - -``` - * @example ​ ````Increase the size of a div when you click it. -```html - - - - - css demo - - - - -​ -
      click
      -
      click
      -​ - - - -``` - */ - css(propertyName: string): string; - /** - * Get the computed style properties for the first element in the set of matched elements. - * - * @param propertyNames An array of one or more CSS properties. - * @see \`{@link https://api.jquery.com/css/ }\` - * @since 1.9 - * @example ​ ````Get the background color of a clicked div. -```html - - - - - css demo - - - - -​ -  -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Get the width, height, text color, and background color of a clicked div. -```html - - - - - css demo - - - - -​ -

       

      -
      1
      -
      2
      -
      3
      -
      4
      -​ - - - -``` - * @example ​ ````Change the color of any paragraph to red on mouseover event. -```html - - - - - css demo - - - - -​ -

      Just roll the mouse over me.

      -​ -

      Or me to see a color change.

      -​ - - - -``` - * @example ​ ````Increase the width of #box by 200 pixels the first time it is clicked. -```html - - - - - css demo - - - - -​ -
      Click me to grow
      -​ - - - -``` - * @example ​ ````Highlight a clicked word in the paragraph. -```html - - - - - css demo - - - - -​ -

      - Once upon a time there was a man - who lived in a pizza parlor. This - man just loved pizza and ate it all - the time. He went on to be the - happiest man in the world. The end. -

      -​ - - - -``` - * @example ​ ````Change the font weight and background color on mouseenter and mouseleave. -```html - - - - - css demo - - - - -​ -

      Move the mouse over a paragraph.

      -

      Like this one or the one above.

      -​ - - - -``` - * @example ​ ````Increase the size of a div when you click it. -```html - - - - - css demo - - - - -​ -
      click
      -
      click
      -​ - - - -``` - */ - css(propertyNames: string[]): JQuery.PlainObject; - /** - * Store arbitrary data associated with the matched elements. - * - * @param key A string naming the piece of data to set. - * @param value The new data value; this can be any Javascript type except `undefined`. - * @see \`{@link https://api.jquery.com/data/ }\` - * @since 1.2.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(key: string, value: string | number | boolean | symbol | object | null): this; - /** - * Store arbitrary data associated with the matched elements. - * - * @param obj An object of key-value pairs of data to update. - * @see \`{@link https://api.jquery.com/data/ }\` - * @since 1.4.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(obj: JQuery.PlainObject): this; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by - * data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - * @param value `undefined` is not recognized as a data value. Calls such as `.data( "name", undefined )` - * will return the jQuery object that it was called on, allowing for chaining. - * @see \`{@link https://api.jquery.com/data/ }\` - * @since 1.2.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - // `unified-signatures` is disabled so that behavior when passing `undefined` to `value` can be documented. Unifying the signatures - // results in potential confusion for users from an unexpected parameter. - // tslint:disable-next-line:unified-signatures - data(key: string, value: undefined): any; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by - * data(name, value) or by an HTML5 data-* attribute. - * - * @param key Name of the data stored. - * @see \`{@link https://api.jquery.com/data/ }\` - * @since 1.2.3 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(key: string): any; - /** - * Return the value at the named data store for the first element in the jQuery collection, as set by - * data(name, value) or by an HTML5 data-* attribute. - * - * @see \`{@link https://api.jquery.com/data/ }\` - * @since 1.4 - * @example ​ ````Store then retrieve a value from the div element. -```html - - - - - data demo - - - - -​ -
      - The values stored were - - and - -
      -​ - - - -``` - * @example ​ ````Get the data named "blah" stored at for an element. -```html - - - - - data demo - - - - -​ -
      A div
      - - - - -

      The "blah" value of this div is ?

      -​ - - - -``` - */ - data(): JQuery.PlainObject; - /** - * Bind an event handler to the "dblclick" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/dblclick/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To bind a "Hello World!" alert box to the dblclick event on every paragraph on the page: -```html - - - - - dblclick demo - - - -​​ - - - -``` - * @example ​ ````Double click to toggle background color. -```html - - - - - dblclick demo - - - - -​ -
      -Double click the block -​ - - - -``` - */ - dblclick(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/dblclick/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To bind a "Hello World!" alert box to the dblclick event on every paragraph on the page: -```html - - - - - dblclick demo - - - -​​ - - - -``` - * @example ​ ````Double click to toggle background color. -```html - - - - - dblclick demo - - - - -​ -
      -Double click the block -​ - - - -``` - */ - dblclick(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see \`{@link https://api.jquery.com/delay/ }\` - * @since 1.4 - * @example ​ ````Animate the hiding and showing of two divs, delaying the first before showing it. -```html - - - - - delay demo - - - - -​ -

      -
      -
      -​ - - - -``` - */ - delay(duration: JQuery.Duration, queueName?: string): 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. - * @param eventType A string containing one or more space-separated JavaScript event types, such as "click" or - * "keydown," or custom event names. - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/delegate/ }\` - * @since 1.4.2 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones. -```html - - - - - delegate demo - - - - -​ -

      Click me!

      -​ - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel a default action and prevent it from bubbling up, return false: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel only the default action by using the preventDefault method. -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````Can bind custom events too. -```html - - - - - delegate demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - */ - delegate(selector: JQuery.Selector, - eventType: string, - eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @param eventType A string containing one or more space-separated JavaScript event types, such as "click" or - * "keydown," or custom event names. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/delegate/ }\` - * @since 1.4.2 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones. -```html - - - - - delegate demo - - - - -​ -

      Click me!

      -​ - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel a default action and prevent it from bubbling up, return false: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel only the default action by using the preventDefault method. -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````Can bind custom events too. -```html - - - - - delegate demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - */ - delegate(selector: JQuery.Selector, - eventType: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param events A plain object of one or more event types and functions to execute for them. - * @see \`{@link https://api.jquery.com/delegate/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.on }\`. - * @example ​ ````Click a paragraph to add another. Note that .delegate() attaches a click event handler to all paragraphs - even new ones. -```html - - - - - delegate demo - - - - -​ -

      Click me!

      -​ - -​ - - - -``` - * @example ​ ````To display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel a default action and prevent it from bubbling up, return false: -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````To cancel only the default action by using the preventDefault method. -```html - - - - - delegate demo - - - -​​ - - - -``` - * @example ​ ````Can bind custom events too. -```html - - - - - delegate demo - - - - -​ -

      Has an attached custom event.

      - - -​ - - - -``` - */ - delegate(selector: JQuery.Selector, - events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): 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. - * @see \`{@link https://api.jquery.com/dequeue/ }\` - * @since 1.2 - * @example ​ ````Use dequeue to end a custom queue function which allows the queue to keep going. -```html - - - - - dequeue demo - - - - -​ - -
      -​ - - - -``` - */ - dequeue(queueName?: string): this; - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - * @see \`{@link https://api.jquery.com/detach/ }\` - * @since 1.4 - * @example ​ ````Detach all paragraphs from the DOM -```html - - - - - detach demo - - - - -​ -

      Hello

      -how are -

      you?

      - -​ - - - -``` - */ - detach(selector?: JQuery.Selector): this; - /** - * Iterate over a jQuery object, executing a function for each matched element. - * - * @param fn A function to execute for each matched element. - * @see \`{@link https://api.jquery.com/each/ }\` - * @since 1.0 - * @example ​ ````Iterate over three divs and sets their color property. -```html - - - - - each demo - - - - -​ -
      Click here
      -
      to iterate through
      -
      these divs.
      -​ - - - -``` - * @example ​ ````To access a jQuery object instead of the regular DOM element, use $( this ). For example: -```html - - - - - each demo - - - - -​ -To do list: (click here to change) -
        -
      • Eat
      • -
      • Sleep
      • -
      • Be merry
      • -
      -​ - - - -``` - * @example ​ ````Use return false to break out of each() loops early. -```html - - - - - each demo - - - - -​ - - -
      -
      -
      -
      -
      Stop here
      -
      -
      -
      -​ - - - -``` - */ - each(fn: (this: TElement, index: number, element: TElement) => void | false): this; - /** - * Remove all child nodes of the set of matched elements from the DOM. - * - * @see \`{@link https://api.jquery.com/empty/ }\` - * @since 1.0 - * @example ​ ````Removes all child nodes (including text nodes) from all paragraphs -```html - - - - - empty demo - - - - -​ -

      - Hello, Person and person. -

      -​ - -​ - - - -``` - */ - empty(): this; - /** - * End the most recent filtering operation in the current chain and return the set of matched elements - * to its previous state. - * - * @see \`{@link https://api.jquery.com/end/ }\` - * @since 1.0 - * @example ​ ````Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. -```html - - - - - end demo - - - - -​ -

      - Hi there how are you doing? -

      -​ -

      - This span is one of - several spans in this - sentence. -

      -​ -
      - Tags in jQuery object initially: -
      -​ -
      - Tags in jQuery object after find: -
      -​ -
      - Tags in jQuery object after end: -
      -​ - - - -``` - * @example ​ ````Selects all paragraphs, finds span elements inside these, and reverts the selection back to the paragraphs. -```html - - - - - end demo - - - - -​ -

      Hello, how are you?

      -​ - - - -``` - */ - end(): this; - /** - * Reduce the set of matched elements to the one at the specified index. - * - * @param index An integer indicating the 0-based position of the element. - * An integer indicating the position of the element, counting backwards from the last element in the set. - * @see \`{@link https://api.jquery.com/eq/ }\` - * @since 1.1.2 - * @since 1.4 - * @example ​ ````Turn the div with index 2 blue by adding an appropriate class. -```html - - - - - eq demo - - - - -​ -
      -
      -
      -
      -
      -
      -​ - - - -``` - */ - eq(index: number): this; - /** - * Merge the contents of an object onto the jQuery prototype to provide new jQuery instance methods. - * - * @param obj An object to merge onto the jQuery prototype. - * @see \`{@link https://api.jquery.com/jQuery.fn.extend/ }\` - * @since 1.0 - * @example ​ ````Add two methods to the jQuery prototype ($.fn) object and then use one of them. -```html - - - - - jQuery.fn.extend demo - - - - -​ - - -​ - - - -``` - */ - extend(obj: object): this; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeIn/ }\` - * @since 1.4.3 - * @example ​ ````Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds. -```html - - - - - fadeIn demo - - - - -​ -Click here... -
      -
      -
      -​ - - - -``` - * @example ​ ````Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top. -```html - - - - - fadeIn demo - - - - -​ -

      - Let it be known that the party of the first part - and the party of the second part are henceforth - and hereto directed to assess the allegations - for factual correctness... (click!) -

      CENSORED!
      -

      -​ - - - -``` - */ - fadeIn(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeIn/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds. -```html - - - - - fadeIn demo - - - - -​ -Click here... -
      -
      -
      -​ - - - -``` - * @example ​ ````Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top. -```html - - - - - fadeIn demo - - - - -​ -

      - Let it be known that the party of the first part - and the party of the second part are henceforth - and hereto directed to assess the allegations - for factual correctness... (click!) -

      CENSORED!
      -

      -​ - - - -``` - */ - fadeIn(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Display the matched elements by fading them to opaque. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/fadeIn/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates hidden divs to fade in one by one, completing each animation within 600 milliseconds. -```html - - - - - fadeIn demo - - - - -​ -Click here... -
      -
      -
      -​ - - - -``` - * @example ​ ````Fades a red block in over the text. Once the animation is done, it quickly fades in more text on top. -```html - - - - - fadeIn demo - - - - -​ -

      - Let it be known that the party of the first part - and the party of the second part are henceforth - and hereto directed to assess the allegations - for factual correctness... (click!) -

      CENSORED!
      -

      -​ - - - -``` - */ - fadeIn(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeOut/ }\` - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to fade out, completing the animation within 600 milliseconds. -```html - - - - - fadeOut demo - - - - -​ -

      - If you click on this paragraph - you'll see it just fade away. -

      -​ - - - -``` - * @example ​ ````Fades out spans in one section that you click on. -```html - - - - - fadeOut demo - - - - -​ -

      Find the modifiers -

      -

      - If you really want to go outside - in the cold then make sure to wear - your warm jacket given to you by - your favorite teacher. -

      -​ - - - -``` - * @example ​ ````Fades out two divs, one with a "linear" easing and one with the default, "swing," easing. -```html - - - - - fadeOut demo - - - - -​ - - -​ -
      -​ -
      linear
      -
      swing
      -​ - - - -``` - */ - fadeOut(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeOut/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to fade out, completing the animation within 600 milliseconds. -```html - - - - - fadeOut demo - - - - -​ -

      - If you click on this paragraph - you'll see it just fade away. -

      -​ - - - -``` - * @example ​ ````Fades out spans in one section that you click on. -```html - - - - - fadeOut demo - - - - -​ -

      Find the modifiers -

      -

      - If you really want to go outside - in the cold then make sure to wear - your warm jacket given to you by - your favorite teacher. -

      -​ - - - -``` - * @example ​ ````Fades out two divs, one with a "linear" easing and one with the default, "swing," easing. -```html - - - - - fadeOut demo - - - - -​ - - -​ -
      -​ -
      linear
      -
      swing
      -​ - - - -``` - */ - fadeOut(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Hide the matched elements by fading them to transparent. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/fadeOut/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to fade out, completing the animation within 600 milliseconds. -```html - - - - - fadeOut demo - - - - -​ -

      - If you click on this paragraph - you'll see it just fade away. -

      -​ - - - -``` - * @example ​ ````Fades out spans in one section that you click on. -```html - - - - - fadeOut demo - - - - -​ -

      Find the modifiers -

      -

      - If you really want to go outside - in the cold then make sure to wear - your warm jacket given to you by - your favorite teacher. -

      -​ - - - -``` - * @example ​ ````Fades out two divs, one with a "linear" easing and one with the default, "swing," easing. -```html - - - - - fadeOut demo - - - - -​ - - -​ -
      -​ -
      linear
      -
      swing
      -​ - - - -``` - */ - fadeOut(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeTo/ }\` - * @since 1.4.3 - * @example ​ ````Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds. -```html - - - - - fadeTo demo - - - -​ -

      -Click this paragraph to see it fade. -

      -​ -

      -Compare to this one that won't fade. -

      -​ - - - -``` - * @example ​ ````Fade div to a random opacity on each click, completing the animation within 200 milliseconds. -```html - - - - - fadeTo demo - - - - -​ -

      And this is the library that John built...

      -​ -
      -
      -
      -​ - - - -``` - * @example ​ ````Find the right answer! The fade will take 250 milliseconds and change various styles when it completes. -```html - - - - - fadeTo demo - - - - -​ -

      Wrong

      -
      -

      Wrong

      -
      -

      Right!

      -
      -​ - - - -``` - */ - fadeTo(duration: JQuery.Duration, opacity: number, easing: string, complete?: (this: TElement) => void): this; - /** - * Adjust the opacity of the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param opacity A number between 0 and 1 denoting the target opacity. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeTo/ }\` - * @since 1.0 - * @example ​ ````Animates first paragraph to fade to an opacity of 0.33 (33%, about one third visible), completing the animation within 600 milliseconds. -```html - - - - - fadeTo demo - - - -​ -

      -Click this paragraph to see it fade. -

      -​ -

      -Compare to this one that won't fade. -

      -​ - - - -``` - * @example ​ ````Fade div to a random opacity on each click, completing the animation within 200 milliseconds. -```html - - - - - fadeTo demo - - - - -​ -

      And this is the library that John built...

      -​ -
      -
      -
      -​ - - - -``` - * @example ​ ````Find the right answer! The fade will take 250 milliseconds and change various styles when it completes. -```html - - - - - fadeTo demo - - - - -​ -

      Wrong

      -
      -

      Wrong

      -
      -

      Right!

      -
      -​ - - - -``` - */ - fadeTo(duration: JQuery.Duration, opacity: number, complete?: (this: TElement) => void): this; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeToggle/ }\` - * @since 1.4.4 - * @example ​ ````Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. -```html - - - - - fadeToggle demo - - - -​ - - -

      This paragraph has a slow, linear fade.

      -

      This paragraph has a fast animation.

      -
      -​ - - - -``` - */ - fadeToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/fadeToggle/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. -```html - - - - - fadeToggle demo - - - -​ - - -

      This paragraph has a slow, linear fade.

      -

      This paragraph has a fast animation.

      -
      -​ - - - -``` - */ - fadeToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Display or hide the matched elements by animating their opacity. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/fadeToggle/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Fades first paragraph in or out, completing the animation within 600 milliseconds and using a linear easing. Fades last paragraph in or out for 200 milliseconds, inserting a "finished" message upon completion. -```html - - - - - fadeToggle demo - - - -​ - - -

      This paragraph has a slow, linear fade.

      -

      This paragraph has a fast animation.

      -
      -​ - - - -``` - */ - fadeToggle(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Reduce the set of matched elements to those that match the selector or pass the function's test. - * - * @param selector A string containing a selector expression to match the current set of elements against. - * One or more DOM elements to match the current set of elements against. - * An existing jQuery object to match the current set of elements against. - * A function used as a test for each element in the set. this is the current DOM element. - * @see \`{@link https://api.jquery.com/filter/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Change the color of all divs; then add a border to those with a "middle" class. -```html - - - - - filter demo - - - - -​ -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Change the color of all divs; then add a border to the second one (index == 1) and the div with an id of "fourth." -```html - - - - - filter demo - - - - -​ -
      -
      -
      -
      -
      -
      -​ - - - -``` - * @example ​ ````Select all divs and filter the selection with a DOM element, keeping only the one with an id of "unique". -```html - - - - - filter demo - - - -​​ - - - -``` - * @example ​ ````Select all divs and filter the selection with a jQuery object, keeping only the one with an id of "unique". -```html - - - - - filter demo - - - -​​ - - - -``` - */ - filter(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): this; - /** - * Get the descendants of each element in the current set of matched elements, filtered by a selector, - * jQuery object, or element. - * - * @param selector A string containing a selector expression to match elements against. - * An element or a jQuery object to match elements against. - * @see \`{@link https://api.jquery.com/find/ }\` - * @since 1.0 - * @since 1.6 - * @example ​ ````Starts with all paragraphs and searches for descendant span elements, same as $( "p span" ) -```html - - - - - find demo - - - -​ -

      Hello, how are you?

      -

      Me? I'm good.

      -​ - - - -``` - * @example ​ ````A selection using a jQuery collection of all span tags. Only spans within p tags are changed to red while others are left blue. -```html - - - - - find demo - - - - -​ -

      Hello, how are you?

      -

      Me? I'm good.

      -
      Did you eat yet?
      -​ - - - -``` - * @example ​ ````Add spans around each word then add a hover and italicize words with the letter t. -```html - - - - - find demo - - - - -​ -

      - When the day is short - find that which matters to you - or stop believing -

      -​ - - - -``` - */ - find(selector: JQuery.Selector | Element | JQuery): this; - /** - * Stop the currently-running animation, remove all queued animations, and complete all animations for - * the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @see \`{@link https://api.jquery.com/finish/ }\` - * @since 1.9 - * @example ​ ````Click the Go button once to start the animation, and then click the other buttons to see how they affect the current and queued animations. -```html - - - - - finish demo - - - - -​ -
      -
      - -
      - - -
      - - -
      - - -
      - -
      - -
      -​ - - - -``` - */ - finish(queue?: string): this; - /** - * Reduce the set of matched elements to the first in the set. - * - * @see \`{@link https://api.jquery.com/first/ }\` - * @since 1.4 - * @example ​ ````Highlight the first span in a paragraph. -```html - - - - - first demo - - - - -​ -

      - Look: - This is some text in a paragraph. - This is a note about it. -

      -​ - - - -``` - */ - first(): this; - /** - * Bind an event handler to the "focus" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/focus/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Fire focus. -```html - - - - - focus demo - - - - -​ -

      focus fire

      -

      focus fire

      -​ - - - -``` - * @example ​ ````To stop people from writing in text input boxes, try: -```html - - - - - focus demo - - - -​​ - - - -``` - * @example ​ ````To focus on a login input box with id 'login' on page startup, try: -```html - - - - - focus demo - - - -​​ - - - -``` - */ - focus(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/focus/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Fire focus. -```html - - - - - focus demo - - - - -​ -

      focus fire

      -

      focus fire

      -​ - - - -``` - * @example ​ ````To stop people from writing in text input boxes, try: -```html - - - - - focus demo - - - -​​ - - - -``` - * @example ​ ````To focus on a login input box with id 'login' on page startup, try: -```html - - - - - focus demo - - - -​​ - - - -``` - */ - focus(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Bind an event handler to the "focusin" event. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/focusin/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Watch for a focus to occur within the paragraphs on the page. -```html - - - - - focusin demo - - - - -​ -

      focusin fire

      -

      focusin fire

      -​ - - - -``` - */ - focusin(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; - /** - * Bind an event handler to the "focusin" event. - * - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/focusin/ }\` - * @since 1.4 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Watch for a focus to occur within the paragraphs on the page. -```html - - - - - focusin demo - - - - -​ -

      focusin fire

      -

      focusin fire

      -​ - - - -``` - */ - focusin(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/focusout/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Watch for a loss of focus to occur inside paragraphs and note the difference between the focusout count and the blur count. (The blur count does not change because those events do not bubble.) -```html - - - - - focusout demo - - - - -​ -
      -

      -
      - -

      -

      - -

      -
      -
      focusout fire
      -
      blur fire
      -​ - - - -``` - */ - focusout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): this; - /** - * Bind an event handler to the "focusout" JavaScript event. - * - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/focusout/ }\` - * @since 1.4 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Watch for a loss of focus to occur inside paragraphs and note the difference between the focusout count and the blur count. (The blur count does not change because those events do not bubble.) -```html - - - - - focusout demo - - - - -​ -
      -

      -
      - -

      -

      - -

      -
      -
      focusout fire
      -
      blur fire
      -​ - - - -``` - */ - focusout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Retrieve one of the elements matched by the jQuery object. - * - * @param index A zero-based integer indicating which element to retrieve. - * @see \`{@link https://api.jquery.com/get/ }\` - * @since 1.0 - * @example ​ ````Display the tag name of the click element. -```html - - - - - get demo - - - - -​ -  -

      In this paragraph is an important section

      -
      -​ - - - -``` - * @example ​ ````Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. -```html - - - - - get demo - - - - -​ -Reversed - -​ -
      One
      -
      Two
      -
      Three
      -​ - - - -``` - */ - get(index: number): TElement; - /** - * Retrieve the elements matched by the jQuery object. - * - * @see \`{@link https://api.jquery.com/get/ }\` - * @since 1.0 - * @example ​ ````Display the tag name of the click element. -```html - - - - - get demo - - - - -​ -  -

      In this paragraph is an important section

      -
      -​ - - - -``` - * @example ​ ````Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. -```html - - - - - get demo - - - - -​ -Reversed - -​ -
      One
      -
      Two
      -
      Three
      -​ - - - -``` - */ - get(): TElement[]; - /** - * Reduce the set of matched elements to those that have a descendant that matches the selector or DOM element. - * - * @param selector A string containing a selector expression to match elements against. - * A DOM element to match elements against. - * @see \`{@link https://api.jquery.com/has/ }\` - * @since 1.4 - * @example ​ ````Check if an element is inside another. -```html - - - - - has demo - - - - -​ -
      • Does the UL contain an LI?
      -​ - - - -``` - */ - has(selector: string | Element): this; - /** - * Determine whether any of the matched elements are assigned the given class. - * - * @param className The class name to search for. - * @see \`{@link https://api.jquery.com/hasClass/ }\` - * @since 1.2 - * @example ​ ````Looks for the paragraph that contains 'selected' as a class. -```html - - - - - hasClass demo - - - - -​ -

      This paragraph is black and is the first paragraph.

      -

      This paragraph is red and is the second paragraph.

      -
      First paragraph has selected class:
      -
      Second paragraph has selected class:
      -
      At least one paragraph has selected class:
      -​ - - - -``` - */ - hasClass(className: string): boolean; - /** - * Set the CSS height of every matched element. - * - * @param value An integer representing the number of pixels, or an integer with an optional unit of measure - * appended (as a string). - * A function returning the height to set. Receives the index position of the element in the set and - * the old height as arguments. Within the function, this refers to the current element in the set. - * @see \`{@link https://api.jquery.com/height/ }\` - * @since 1.0 - * @since 1.4.1 - * @example ​ ````Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. -```html - - - - - height demo - - - - -​ - - - -​ -
       
      -

      - Sample paragraph to test height -

      -​ - - - -``` - * @example ​ ````To set the height of each div on click to 30px plus a color change. -```html - - - - - height demo - - - - -​ -
      -
      -
      -
      -
      -​ - - - -``` - */ - height(value: string | number | ((this: TElement, index: number, height: number) => string | number)): this; - /** - * Get the current computed height for the first element in the set of matched elements. - * - * @see \`{@link https://api.jquery.com/height/ }\` - * @since 1.0 - * @example ​ ````Show various heights. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. -```html - - - - - height demo - - - - -​ - - - -​ -
       
      -

      - Sample paragraph to test height -

      -​ - - - -``` - * @example ​ ````To set the height of each div on click to 30px plus a color change. -```html - - - - - height demo - - - - -​ -
      -
      -
      -
      -
      -​ - - - -``` - */ - height(): number | undefined; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/hide/ }\` - * @since 1.4.3 - * @example ​ ````Hides all paragraphs then the link on click. -```html - - - - - hide demo - - - -​ -

      Hello

      -Click to hide me too -

      Here is another paragraph

      -​ - - - -``` - * @example ​ ````Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds. -```html - - - - - hide demo - - - - -​ - -

      Hiya

      -

      Such interesting text, eh?

      -​ - - - -``` - * @example ​ ````Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one. -```html - - - - - hide demo - - - - -​ - - -
      - Once upon a - time there were - three programmers... -
      -​ - - - -``` - * @example ​ ````Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time. -```html - - - - - hide demo - - - - -​ -
      -​ - - - -``` - */ - hide(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; - /** - * Hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/hide/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Hides all paragraphs then the link on click. -```html - - - - - hide demo - - - -​ -

      Hello

      -Click to hide me too -

      Here is another paragraph

      -​ - - - -``` - * @example ​ ````Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds. -```html - - - - - hide demo - - - - -​ - -

      Hiya

      -

      Such interesting text, eh?

      -​ - - - -``` - * @example ​ ````Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one. -```html - - - - - hide demo - - - - -​ - - -
      - Once upon a - time there were - three programmers... -
      -​ - - - -``` - * @example ​ ````Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time. -```html - - - - - hide demo - - - - -​ -
      -​ - - - -``` - */ - hide(duration: JQuery.Duration, easing_complete: string | ((this: TElement) => void)): this; - /** - * Hide the matched elements. - * - * @param duration_complete_options A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/hide/ }\` - * @since 1.0 - * @example ​ ````Hides all paragraphs then the link on click. -```html - - - - - hide demo - - - -​ -

      Hello

      -Click to hide me too -

      Here is another paragraph

      -​ - - - -``` - * @example ​ ````Animates all shown paragraphs to hide slowly, completing the animation within 600 milliseconds. -```html - - - - - hide demo - - - - -​ - -

      Hiya

      -

      Such interesting text, eh?

      -​ - - - -``` - * @example ​ ````Animates all spans (words in this case) to hide fastly, completing each animation within 200 milliseconds. Once each animation is done, it starts the next one. -```html - - - - - hide demo - - - - -​ - - -
      - Once upon a - time there were - three programmers... -
      -​ - - - -``` - * @example ​ ````Hides the divs when clicked over 2 seconds, then removes the div element when its hidden. Try clicking on more than one box at a time. -```html - - - - - hide demo - - - - -​ -
      -​ - - - -``` - */ - 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. - * @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 - * @example ​ ````To add a special style to list items that are being hovered over, try: -```html - - - - - hover demo - - - - -​ -
        -
      • Milk
      • -
      • Bread
      • -
      • Chips
      • -
      • Socks
      • -
      -​ - - - -``` - * @example ​ ````To add a special style to table cells that are being hovered over, try: -```html - - - - - hover demo - - - -​​ - - - -``` - * @example ​ ````To unbind the above example use: -```html - - - - - hover demo - - - -​​ - - - -``` - * @example ​ ````Slide the next sibling LI up or down on hover, and toggle a class. -```html - - - - - hover demo - - - - -​ -
        -
      • Milk
      • -
      • White
      • -
      • Carrots
      • -
      • Orange
      • -
      • Broccoli
      • -
      • Green
      • -
      -​ - - - -``` - */ - // 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; - /** - * Set the HTML contents of each element in the set of matched elements. - * - * @param htmlString A string of HTML to set as the content of each matched element. - * A function returning the HTML content to set. Receives the index position of the element in the set - * and the old HTML value as arguments. jQuery empties the element before calling the function; use the - * oldhtml argument to reference the previous content. Within the function, this refers to the current element in the set. - * @see \`{@link https://api.jquery.com/html/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Click a paragraph to convert it from html to text. -```html - - - - - html demo - - - - -​ -

      - Click to change the html -

      -

      - to a text node. -

      -

      - This does nothing. -

      -​ - - - -``` - * @example ​ ````Add some html to each div. -```html - - - - - html demo - - - - -​ -Hello -
      -
      -
      -​ - - - -``` - * @example ​ ````Add some html to each div then immediately do further manipulations to the inserted html. -```html - - - - - html demo - - - - -​ -
      -
      -
      -​ - - - -``` - */ - html(htmlString: JQuery.htmlString | ((this: TElement, index: number, oldhtml: JQuery.htmlString) => JQuery.htmlString)): this; - /** - * Get the HTML contents of the first element in the set of matched elements. - * - * @see \`{@link https://api.jquery.com/html/ }\` - * @since 1.0 - * @example ​ ````Click a paragraph to convert it from html to text. -```html - - - - - html demo - - - - -​ -

      - Click to change the html -

      -

      - to a text node. -

      -

      - This does nothing. -

      -​ - - - -``` - * @example ​ ````Add some html to each div. -```html - - - - - html demo - - - - -​ -Hello -
      -
      -
      -​ - - - -``` - * @example ​ ````Add some html to each div then immediately do further manipulations to the inserted html. -```html - - - - - html demo - - - - -​ -
      -
      -
      -​ - - - -``` - */ - html(): string; - /** - * Search for a given element from among the matched elements. - * - * @param element The DOM element or first element within the jQuery object to look for. - * A selector representing a jQuery collection in which to look for an element. - * @see \`{@link https://api.jquery.com/index/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````On click, returns the index (zero-based) of that div in the page. -```html - - - - - index demo - - - - -​ -Click a div! -
      First div
      -
      Second div
      -
      Third div
      -​ - - - -``` - * @example ​ ````Returns the index for the element with ID bar. -```html - - - - - index demo - - - - -​ -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      -
      -​ - - - -``` - * @example ​ ````Returns the index for the first item in the jQuery collection. -```html - - - - - index demo - - - - -​ -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      -
      -​ - - - -``` - * @example ​ ````Returns the index for the element with ID bar in relation to all <li> elements. -```html - - - - - index demo - - - - -​ -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      -
      -​ - - - -``` - * @example ​ ````Returns the index for the element with ID bar in relation to its siblings. -```html - - - - - index demo - - - - -​ -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      -
      -​ - - - -``` - * @example ​ ````Returns -1, as there is no element with ID foobar. -```html - - - - - index demo - - - - -​ -
        -
      • foo
      • -
      • bar
      • -
      • baz
      • -
      -
      -​ - - - -``` - */ - index(element?: JQuery.Selector | Element | JQuery): number; - /** - * Set the CSS inner height of each element in the set of matched elements. - * - * @param value A number representing the number of pixels, or a number along with an optional unit of measure - * appended (as a string). - * A function returning the inner height (including padding but not border) to set. Receives the index - * position of the element in the set and the old inner height as arguments. Within the function, this - * refers to the current element in the set. - * @see \`{@link https://api.jquery.com/innerHeight/ }\` - * @since 1.8.0 - * @example ​ ````Get the innerHeight of a paragraph. -```html - - - - - innerHeight demo - - - - -​ -

      Hello

      -

      -​ - - - -``` - * @example ​ ````Change the inner height of each div the first time it is clicked (and change its color). -```html - - - - - innerHeight demo - - - - -​ -
      d
      -
      d
      -
      d
      -
      d
      -
      d
      -​ - - - -``` - */ - innerHeight(value: string | number | ((this: TElement, index: number, height: number) => string | number)): this; - /** - * Get the current computed height for the first element in the set of matched elements, including - * padding but not border. - * - * @see \`{@link https://api.jquery.com/innerHeight/ }\` - * @since 1.2.6 - * @example ​ ````Get the innerHeight of a paragraph. -```html - - - - - innerHeight demo - - - - -​ -

      Hello

      -

      -​ - - - -``` - * @example ​ ````Change the inner height of each div the first time it is clicked (and change its color). -```html - - - - - innerHeight demo - - - - -​ -
      d
      -
      d
      -
      d
      -
      d
      -
      d
      -​ - - - -``` - */ - innerHeight(): number | undefined; - /** - * Set the CSS inner width of each element in the set of matched elements. - * - * @param value A number representing the number of pixels, or a number along with an optional unit of measure - * appended (as a string). - * A function returning the inner width (including padding but not border) to set. Receives the index - * position of the element in the set and the old inner width as arguments. Within the function, this - * refers to the current element in the set. - * @see \`{@link https://api.jquery.com/innerWidth/ }\` - * @since 1.8.0 - * @example ​ ````Get the innerWidth of a paragraph. -```html - - - - - innerWidth demo - - - - -​ -

      Hello

      -

      -​ - - - -``` - * @example ​ ````Change the inner width of each div the first time it is clicked (and change its color). -```html - - - - - innerWidth demo - - - - -​ -
      d
      -
      d
      -
      d
      -
      d
      -
      d
      -​ - - - -``` - */ - innerWidth(value: string | number | ((this: TElement, index: number, width: number) => string | number)): this; - /** - * Get the current computed inner width for the first element in the set of matched elements, including - * padding but not border. - * - * @see \`{@link https://api.jquery.com/innerWidth/ }\` - * @since 1.2.6 - * @example ​ ````Get the innerWidth of a paragraph. -```html - - - - - innerWidth demo - - - - -​ -

      Hello

      -

      -​ - - - -``` - * @example ​ ````Change the inner width of each div the first time it is clicked (and change its color). -```html - - - - - innerWidth demo - - - - -​ -
      d
      -
      d
      -
      d
      -
      d
      -
      d
      -​ - - - -``` - */ - innerWidth(): number | undefined; - /** - * Insert every element in the set of matched elements after the target. - * - * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements - * will be inserted after the element(s) specified by this parameter. - * @see \`{@link https://api.jquery.com/insertAfter/ }\` - * @since 1.0 - * @example ​ ````Insert all paragraphs after an element with id of "foo". Same as $( "#foo" ).after( "p" ) -```html - - - - - insertAfter demo - - - - -​ -

      is what I said...

      -
      FOO!
      -​ - - - -``` - */ - insertAfter(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; - /** - * Insert every element in the set of matched elements before the target. - * - * @param target A selector, element, array of elements, HTML string, or jQuery object; the matched set of elements - * will be inserted before the element(s) specified by this parameter. - * @see \`{@link https://api.jquery.com/insertBefore/ }\` - * @since 1.0 - * @example ​ ````Insert all paragraphs before an element with id of "foo". Same as $( "#foo" ).before( "p" ) -```html - - - - - insertBefore demo - - - - -​ -
      FOO!
      -

      I would like to say:

      -​ - - - -``` - */ - insertBefore(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; - /** - * Check the current matched set of elements against a selector, element, or jQuery object and return - * true if at least one of these elements matches the given arguments. - * - * @param selector A string containing a selector expression to match elements against. - * A function used as a test for every element in the set. It accepts two arguments, index, which is - * the element's index in the jQuery collection, and element, which is the DOM element. Within the - * function, this refers to the current DOM element. - * An existing jQuery object to match the current set of elements against. - * One or more elements to match the current set of elements against. - * @see \`{@link https://api.jquery.com/is/ }\` - * @since 1.0 - * @since 1.6 - * @example ​ ````Shows a few ways is() can be used inside an event handler. -```html - - - - - is demo - - - - -​ -
      -
      -
      -
      -

      Peter
      -
      -

       

      -​ - - - -``` - * @example ​ ````Returns true, because the parent of the input is a form element. -```html - - - - - is demo - - - - -​ -
      - -
      -
      -​ - - - -``` - * @example ​ ````Returns false, because the parent of the input is a p element. -```html - - - - - is demo - - - - -​ -
      -

      -
      -
      -​ - - - -``` - * @example ​ ````Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. -```html - - - - - is demo - - - - -​ -
        -
      • Chrome
      • -
      • Safari
      • -
      • Firefox
      • -
      • Opera
      • -
      -​ - - - -``` - * @example ​ ````An alternate way to achieve the above example using an element rather than a jQuery object. Checks against an existing collection of alternating list elements. Blue, alternating list elements slide up while others turn red. -```html - - - - - is demo - - - - -​ -
        -
      • Chrome
      • -
      • Safari
      • -
      • Firefox
      • -
      • Opera
      • -
      -​ - - - -``` - */ - is(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): boolean; - /** - * Bind an event handler to the "keydown" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/keydown/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object for the keydown handler when a key is pressed in the input. -```html - - - - - keydown demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keydown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/keydown/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object for the keydown handler when a key is pressed in the input. -```html - - - - - keydown demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keydown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/keypress/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (https://api.jquery.com/resources/events.js) for the event object's output. -```html - - - - - keypress demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keypress(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/keypress/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object when a key is pressed in the input. Note: This demo relies on a simple $.print() plugin (https://api.jquery.com/resources/events.js) for the event object's output. -```html - - - - - keypress demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keypress(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/keyup/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object for the keyup handler (using a simple $.print plugin) when a key is released in the input. -```html - - - - - keyup demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keyup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/keyup/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the event object for the keyup handler (using a simple $.print plugin) when a key is released in the input. -```html - - - - - keyup demo - - - - -​ -
      -
      - - -
      -
      - - -​ - - - -``` - */ - keyup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Reduce the set of matched elements to the final one in the set. - * - * @see \`{@link https://api.jquery.com/last/ }\` - * @since 1.4 - * @example ​ ````Highlight the last span in a paragraph. -```html - - - - - last demo - - - - -​ -

      Look: This is some text in a paragraph. This is a note about it.

      -​ - - - -``` - */ - last(): this; - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param data A plain object or string that is sent to the server with the request. - * @param complete A callback function that is executed when the request completes. - * @see \`{@link https://api.jquery.com/load/ }\` - * @since 1.0 - * @example ​ ````Load another page's list items into an ordered list. -```html - - - - - load demo - - - - -​ -Projects: -
        -​ - - - -``` - * @example ​ ````Display a notice if the Ajax request encounters an error. -```html - - - - - load demo - - - - -​ -Successful Response (should be blank): -
        -Error Response: -
        -​ - - - -``` - * @example ​ ````Load the feeds.html file into the div with the ID of feeds. -```html - - - - - load demo - - - -​​ - - - -``` - * @example ​ ````pass arrays of data to the server. -```html - - - - - load demo - - - -​​ - - - -``` - * @example ​ ````Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding. -```html - - - - - load demo - - - -​​ - - - -``` - */ - load(url: string, - data: string | JQuery.PlainObject, - complete: (this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void): this; - /** - * Load data from the server and place the returned HTML into the matched element. - * - * @param url A string containing the URL to which the request is sent. - * @param complete_data A callback function that is executed when the request completes. - * A plain object or string that is sent to the server with the request. - * @see \`{@link https://api.jquery.com/load/ }\` - * @since 1.0 - * @example ​ ````Load another page's list items into an ordered list. -```html - - - - - load demo - - - - -​ -Projects: -
          -​ - - - -``` - * @example ​ ````Display a notice if the Ajax request encounters an error. -```html - - - - - load demo - - - - -​ -Successful Response (should be blank): -
          -Error Response: -
          -​ - - - -``` - * @example ​ ````Load the feeds.html file into the div with the ID of feeds. -```html - - - - - load demo - - - -​​ - - - -``` - * @example ​ ````pass arrays of data to the server. -```html - - - - - load demo - - - -​​ - - - -``` - * @example ​ ````Same as above, but will POST the additional parameters to the server and a callback that is executed when the server is finished responding. -```html - - - - - load demo - - - -​​ - - - -``` - */ - load(url: string, - complete_data?: ((this: TElement, responseText: string, textStatus: JQuery.Ajax.TextStatus, jqXHR: JQuery.jqXHR) => void) | string | JQuery.PlainObject): this; - /** - * Pass each element in the current matched set through a function, producing a new jQuery object - * containing the return values. - * - * @param callback A function object that will be invoked for each element in the current set. - * @see \`{@link https://api.jquery.com/map/ }\` - * @since 1.2 - * @example ​ ````Build a list of all the values within a form. -```html - - - - - map demo - - - - -​ -

          Values:

          -
          - - - -
          -​ - - - -``` - * @example ​ ````A contrived example to show some functionality. -```html - - - - - map demo - - - - -​ -
            -
          • First
          • -
          • Second
          • -
          • Third
          • -
          • Fourth
          • -
          • Fifth
          • -
          -
            -
          -​ - - - -``` - * @example ​ ````Equalize the heights of the divs. -```html - - - - - map demo - - - - -​ - -
          -
          -
          -​ - - - -``` - */ - map(callback: (this: TElement, index: number, domElement: TElement) => JQuery.TypeOrArray | null | undefined): JQuery; - /** - * Bind an event handler to the "mousedown" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mousedown/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseup and mousedown event triggering. -```html - - - - - mousedown demo - - - -​ -

          Press mouse and release here.

          -​ - - - -``` - */ - mousedown(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mousedown/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseup and mousedown event triggering. -```html - - - - - mousedown demo - - - -​ -

          Press mouse and release here.

          -​ - - - -``` - */ - mousedown(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mouseenter/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseenter and mouseout event triggering. - mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. -```html - - - - - mouseenter demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseenter(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mouseenter/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseenter and mouseout event triggering. - mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. -```html - - - - - mouseenter demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseenter(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mouseleave/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show number of times mouseout and mouseleave events are triggered. mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element. -```html - - - - - mouseleave demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseleave(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mouseleave/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show number of times mouseout and mouseleave events are triggered. mouseout fires when the pointer moves out of child element as well, while mouseleave fires only when the pointer moves out of the bound element. -```html - - - - - mouseleave demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseleave(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mousemove/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe. -```html - - - - - mousemove demo - - - - -​ -

          - Move the mouse over the div. -   -

          -
          -​ - - - -``` - */ - mousemove(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mousemove/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the mouse coordinates when the mouse is moved over the yellow div. Coordinates are relative to the window, which in this case is the iframe. -```html - - - - - mousemove demo - - - - -​ -

          - Move the mouse over the div. -   -

          -
          -​ - - - -``` - */ - mousemove(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mouseout/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the number of times mouseout and mouseleave events are triggered. - mouseout fires when the pointer moves out of the child element as well, while mouseleave fires only when the pointer moves out of the bound element. -```html - - - - - mouseout demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseout(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mouseout/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the number of times mouseout and mouseleave events are triggered. - mouseout fires when the pointer moves out of the child element as well, while mouseleave fires only when the pointer moves out of the bound element. -```html - - - - - mouseout demo - - - - -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ -
          -

          move your mouse

          -

          move your mouse

          0

          -

          0

          -
          -​ - - - -``` - */ - mouseout(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mouseover/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the number of times mouseover and mouseenter events are triggered. -mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. -```html - - - - - mouseover demo - - - - -​ -
          - move your mouse -
          -
          -
          -​ -
          - move your mouse -
          -
          -
          -​ - - - -``` - */ - mouseover(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mouseover/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show the number of times mouseover and mouseenter events are triggered. -mouseover fires when the pointer moves into the child element as well, while mouseenter fires only when the pointer moves into the bound element. -```html - - - - - mouseover demo - - - - -​ -
          - move your mouse -
          -
          -
          -​ -
          - move your mouse -
          -
          -
          -​ - - - -``` - */ - mouseover(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/mouseup/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseup and mousedown event triggering. -```html - - - - - mouseup demo - - - -​ -

          Press mouse and release here.

          -​ - - - -``` - */ - mouseup(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/mouseup/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````Show texts when mouseup and mousedown event triggering. -```html - - - - - mouseup demo - - - -​ -

          Press mouse and release here.

          -​ - - - -``` - */ - mouseup(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @see \`{@link https://api.jquery.com/next/ }\` - * @since 1.0 - * @example ​ ````Find the very next sibling of each disabled button and change its text "this button is disabled". -```html - - - - - next demo - - - - -​ -
          -
          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Find the very next sibling of each paragraph. Keep only the ones with a class "selected". -```html - - - - - next demo - - - -​ -

          Hello

          -

          Hello Again

          -
          And Again
          -​ - - - -``` - */ - next(selector?: JQuery.Selector): this; - /** - * Get all following siblings 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. - * @see \`{@link https://api.jquery.com/nextAll/ }\` - * @since 1.2 - * @example ​ ````Locate all the divs after the first and give them a class. -```html - - - - - nextAll demo - - - - -​ -
          first
          -
          sibling
          child
          -
          sibling
          -
          sibling
          ​ - - - -``` - * @example ​ ````Locate all the paragraphs after the second child in the body and give them a class. -```html - - - - - nextAll demo - - - - -​ -

          p

          -
          div
          -

          p

          -

          p

          -
          div
          -

          p

          -
          div
          -​ - - - -``` - */ - nextAll(selector?: string): this; - /** - * Get all following siblings of each element up to but not including the element matched by the - * selector, DOM node, or jQuery object passed. - * - * @param selector A string containing a selector expression to indicate where to stop matching following sibling elements. - * A DOM node or jQuery object indicating where to stop matching following sibling elements. - * @param filter A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/nextUntil/ }\` - * @since 1.4 - * @since 1.6 - * @example ​ ````Find the siblings that follow <dt id="term-2"> up to the next <dt> and give them a red background color. Also, find <dd> siblings that follow <dt id="term-1"> up to <dt id="term-3"> and give them a green text color. -```html - - - - - nextUntil demo - - - -​ -
          -
          term 1
          -
          definition 1-a
          -
          definition 1-b
          -
          definition 1-c
          -
          definition 1-d
          -
          term 2
          -
          definition 2-a
          -
          definition 2-b
          -
          definition 2-c
          -
          term 3
          -
          definition 3-a
          -
          definition 3-b
          -
          -​ - - - -``` - */ - nextUntil(selector?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; - /** - * Remove elements from the set of matched elements. - * - * @param selector A string containing a selector expression, a DOM element, or an array of elements to match against the set. - * A function used as a test for each element in the set. It accepts two arguments, index, which is the - * element's index in the jQuery collection, and element, which is the DOM element. Within the - * function, this refers to the current DOM element. - * An existing jQuery object to match the current set of elements against. - * @see \`{@link https://api.jquery.com/not/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Adds a border to divs that are not green or blue. -```html - - - - - not demo - - - - -​ -
          -
          -
          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Removes the element with the ID "selected" from the set of all paragraphs. -```html - - - - - not demo - - - -​​ - - - -``` - * @example ​ ````Removes the element with the ID "selected" from the set of all paragraphs. -```html - - - - - not demo - - - -​​ - - - -``` - * @example ​ ````Removes all elements that match "div p.selected" from the total set of all paragraphs. -```html - - - - - not demo - - - -​​ - - - -``` - */ - not(selector: JQuery.Selector | JQuery.TypeOrArray | JQuery | ((this: TElement, index: number, element: TElement) => boolean)): this; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as - * "click", "keydown.myPlugin", or ".myPlugin". - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/off/ }\` - * @since 1.7 - * @example ​ ````Add and remove event handlers on the colored button. -```html - - - - - off demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````Remove all event handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove all delegated click handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove just one previously bound handler by passing it as the third argument: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Unbind all delegated event handlers by their namespace: -```html - - - - - off demo - - - -​​ - - - -``` - */ - off(events: string, selector: JQuery.Selector, handler: JQuery.EventHandlerBase> | false): this; - /** - * Remove an event handler. - * - * @param events One or more space-separated event types and optional namespaces, or just namespaces, such as - * "click", "keydown.myPlugin", or ".myPlugin". - * @param selector_handler A selector which should match the one originally passed to .on() when attaching event handlers. - * A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/off/ }\` - * @since 1.7 - * @example ​ ````Add and remove event handlers on the colored button. -```html - - - - - off demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````Remove all event handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove all delegated click handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove just one previously bound handler by passing it as the third argument: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Unbind all delegated event handlers by their namespace: -```html - - - - - off demo - - - -​​ - - - -``` - */ - off(events: string, selector_handler?: JQuery.Selector | JQuery.EventHandlerBase> | false): this; - /** - * Remove an event handler. - * - * @param events An object where the string keys represent one or more space-separated event types and optional - * namespaces, and the values represent handler functions previously attached for the event(s). - * @param selector A selector which should match the one originally passed to .on() when attaching event handlers. - * @see \`{@link https://api.jquery.com/off/ }\` - * @since 1.7 - * @example ​ ````Add and remove event handlers on the colored button. -```html - - - - - off demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````Remove all event handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove all delegated click handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove just one previously bound handler by passing it as the third argument: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Unbind all delegated event handlers by their namespace: -```html - - - - - off demo - - - -​​ - - - -``` - */ - off(events: JQuery.PlainObject> | false>, selector?: JQuery.Selector): this; - /** - * Remove an event handler. - * - * @param event A jQuery.Event object. - * @see \`{@link https://api.jquery.com/off/ }\` - * @since 1.7 - * @example ​ ````Add and remove event handlers on the colored button. -```html - - - - - off demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````Remove all event handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove all delegated click handlers from all paragraphs: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Remove just one previously bound handler by passing it as the third argument: -```html - - - - - off demo - - - -​​ - - - -``` - * @example ​ ````Unbind all delegated event handlers by their namespace: -```html - - - - - off demo - - - -​​ - - - -``` - */ - off(event?: JQuery.Event): this; - /** - * Set the current coordinates of every element in the set of matched elements, relative to the document. - * - * @param coordinates An object containing the properties top and left, which are numbers indicating the new top and left - * coordinates for the elements. - * A function to return the coordinates to set. Receives the index of the element in the collection as - * the first argument and the current coordinates as the second argument. The function should return an - * object with the new top and left properties. - * @see \`{@link https://api.jquery.com/offset/ }\` - * @since 1.4 - * @example ​ ````Access the offset of the second paragraph: -```html - - - - - offset demo - - - - -​ -

          Hello

          2nd Paragraph

          -​ - - - -``` - * @example ​ ````Click to see the offset. -```html - - - - - offset demo - - - - -​ -
          Click an element.
          -

          - This is the best way to find an offset. -

          -
          -
          -​ - - - -``` - * @example ​ ````Set the offset of the second paragraph: -```html - - - - - offset demo - - - - -​ -

          Hello

          2nd Paragraph

          -​ - - - -``` - */ - offset(coordinates: JQuery.CoordinatesPartial | ((this: TElement, index: number, coords: JQuery.Coordinates) => JQuery.CoordinatesPartial)): this; - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the document. - * - * @see \`{@link https://api.jquery.com/offset/ }\` - * @since 1.2 - * @example ​ ````Access the offset of the second paragraph: -```html - - - - - offset demo - - - - -​ -

          Hello

          2nd Paragraph

          -​ - - - -``` - * @example ​ ````Click to see the offset. -```html - - - - - offset demo - - - - -​ -
          Click an element.
          -

          - This is the best way to find an offset. -

          -
          -
          -​ - - - -``` - * @example ​ ````Set the offset of the second paragraph: -```html - - - - - offset demo - - - - -​ -

          Hello

          2nd Paragraph

          -​ - - - -``` - */ - offset(): JQuery.Coordinates | undefined; - /** - * Get the closest ancestor element that is positioned. - * - * @see \`{@link https://api.jquery.com/offsetParent/ }\` - * @since 1.2.6 - * @example ​ ````Find the offsetParent of item "A." -```html - - - - - offsetParent demo - - - -​ -
            -
          • I
          • -
          • II -
              -
            • A
            • -
            • B -
                -
              • 1
              • -
              • 2
              • -
              • 3
              • -
              -
            • -
            • C
            • -
            -
          • -
          • III
          • -
          -​ - - - -``` - */ - offsetParent(): 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 ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - selector: JQuery.Selector | null, - 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 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 ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - selector: JQuery.Selector | null, - data: any, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures - /** - * 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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 handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - selector: JQuery.Selector, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures - /** - * 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 ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - 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 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - data: any, // tslint:disable-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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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 handler A function to execute when the event is triggered. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: string, - handler: ((event: JQueryEventObject) => void)): this; // tslint:disable-line:unified-signatures - /** - * 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 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - 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. - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector): this; // tslint:disable-line:unified-signatures - /** - * 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 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 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - 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). - * @see \`{@link https://api.jquery.com/on/ }\` - * @since 1.7 - * @example ​ ````Display a paragraph's text in an alert when it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler, which is specified here by name: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a form submit action and prevent the event from bubbling up by returning false: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel only the default action by using .preventDefault(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Stop submit events from bubbling without preventing form submit, using .stopPropagation(). -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Pass data to the event handler using the second argument to .trigger() -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Use the the second argument of .trigger() to pass an array of data to the event handler -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach and trigger custom (non-browser) events. -```html - - - - - on demo - - - - -​ -

          Has an attached custom event.

          - - -​ - - - -``` - * @example ​ ````Attach multiple event handlers simultaneously using a plain object. -```html - - - - - on demo - - - - -​ -
          test div
          -​ - - - -``` - * @example ​ ````Click any paragraph to add another after it. Note that .on() allows a click event on any paragraph--even new ones--since the event is handled by the ever-present body element after it bubbles to there. -```html - - - - - on demo - - - - -​ -

          Click me!

          - -​ - - - -``` - * @example ​ ````Display each paragraph's text in an alert box whenever it is clicked: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Cancel a link's default action using the .preventDefault() method: -```html - - - - - on demo - - - -​​ - - - -``` - * @example ​ ````Attach multiple events—one on mouseenter and one on mouseleave to the same element: -```html - - - - - on demo - - - -​​ - - - -``` - */ - on(events: JQuery.PlainObject | JQuery.EventHandlerBase> | 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". - * @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 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: string, - selector: JQuery.Selector | null, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. - * @see \`{@link https://api.jquery.com/one/ }\` - * @since 1.7 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: string, - selector: JQuery.Selector, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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". - * @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 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: string, - data: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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 handler A function to execute when the event is triggered. The value false is also allowed as a shorthand - * for a function that simply does return false. - * @see \`{@link https://api.jquery.com/one/ }\` - * @since 1.7 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: string, - handler: JQuery.EventHandler | JQuery.EventHandlerBase> | 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 - * 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 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector | null, - 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. - * @see \`{@link https://api.jquery.com/one/ }\` - * @since 1.7 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - selector: JQuery.Selector): this; // tslint:disable-line:unified-signatures - /** - * 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 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 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>, - 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). - * @see \`{@link https://api.jquery.com/one/ }\` - * @since 1.7 - * @example ​ ````Tie a one-time click to each div. -```html - - - - - one demo - - - - -​ -
          -
          -
          -
          -
          -

          Click a green square...

          -​ - - - -``` - * @example ​ ````To display the text of all paragraphs in an alert box the first time each of them is clicked: -```html - - - - - one demo - - - -​​ - - - -``` - * @example ​ ````Event handlers will trigger once per element per event type -```html - - - - - one demo - - - -​ -
          0
          -
          Hover/click me
          -​ - - - -``` - */ - one(events: JQuery.PlainObject | JQuery.EventHandlerBase> | false>): this; - /** - * Set the CSS outer height of each element in the set of matched elements. - * - * @param value A number representing the number of pixels, or a number along with an optional unit of measure - * appended (as a string). - * @see \`{@link https://api.jquery.com/outerHeight/ }\` - * @since 1.8.0 - * @example ​ ````Get the outerHeight of a paragraph. -```html - - - - - outerHeight demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Change the outer height of each div the first time it is clicked (and change its color). -```html - - - - - outerHeight demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - outerHeight(value: string | number | ((this: TElement, index: number, height: number) => string | number)): this; - /** - * Get the current computed outer height (including padding, border, and optionally margin) for the - * first element in the set of matched elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - * @see \`{@link https://api.jquery.com/outerHeight/ }\` - * @since 1.2.6 - * @example ​ ````Get the outerHeight of a paragraph. -```html - - - - - outerHeight demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Change the outer height of each div the first time it is clicked (and change its color). -```html - - - - - outerHeight demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - outerHeight(includeMargin?: boolean): number | undefined; - /** - * Set the CSS outer width of each element in the set of matched elements. - * - * @param value A number representing the number of pixels, or a number along with an optional unit of measure - * appended (as a string). - * A function returning the outer width to set. Receives the index position of the element in the set - * and the old outer width as arguments. Within the function, this refers to the current element in the set. - * @see \`{@link https://api.jquery.com/outerWidth/ }\` - * @since 1.8.0 - * @example ​ ````Get the outerWidth of a paragraph. -```html - - - - - outerWidth demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Change the outer width of each div the first time it is clicked (and change its color). -```html - - - - - outerWidth demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - outerWidth(value: string | number | ((this: TElement, index: number, width: number) => string | number)): this; - /** - * Get the current computed outer width (including padding, border, and optionally margin) for the - * first element in the set of matched elements. - * - * @param includeMargin A Boolean indicating whether to include the element's margin in the calculation. - * @see \`{@link https://api.jquery.com/outerWidth/ }\` - * @since 1.2.6 - * @example ​ ````Get the outerWidth of a paragraph. -```html - - - - - outerWidth demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Change the outer width of each div the first time it is clicked (and change its color). -```html - - - - - outerWidth demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - outerWidth(includeMargin?: boolean): number | undefined; - /** - * Get the parent of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/parent/ }\` - * @since 1.0 - * @example ​ ````Shows the parent of each element as (parent > child). Check the View Source to see the raw html. -```html - - - - - parent demo - - - - -​ -
          div, - span, - b -
          -​ -

          p, - span, - em - -

          -​ -
          div, - strong, - span, - em, - b, - - - b -
          -​ - - - -``` - * @example ​ ````Find the parent element of each paragraph with a class "selected". -```html - - - - - parent demo - - - -​ -

          Hello

          -

          Hello Again

          -​ - - - -``` - */ - parent(selector?: JQuery.Selector): this; - /** - * Get the ancestors of each element in the current set of matched elements, optionally filtered by a selector. - * - * @param selector A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/parents/ }\` - * @since 1.0 - * @example ​ ````Find all parent elements of each b. -```html - - - - - parents demo - - - - -​ -
          -

          - - My parents are: - -

          -
          -​ - - - -``` - * @example ​ ````Click to find all unique div parent elements of each span. -```html - - - - - parents demo - - - - -​ -

          -

          -
          Hello
          - Hello Again -
          -
          - And Hello Again -
          -

          - Click Hellos to toggle their parents. -​ - - - -``` - */ - parents(selector?: JQuery.Selector): this; - /** - * Get the ancestors of each element in the current set of matched elements, up to but not including - * the element matched by the selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching ancestor elements. - * A DOM node or jQuery object indicating where to stop matching ancestor elements. - * @param filter A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/parentsUntil/ }\` - * @since 1.4 - * @since 1.6 - * @example ​ ````Find the ancestors of <li class="item-a"> up to <ul class="level-1"> and give them a red background color. Also, find ancestors of <li class="item-2"> that have a class of "yes" up to <ul class="level-1"> and give them a green border. -```html - - - - - parentsUntil demo - - - -​ -
            -
          • I
          • -
          • II -
              -
            • A
            • -
            • B -
                -
              • 1
              • -
              • 2
              • -
              • 3
              • -
              -
            • -
            • C
            • -
            -
          • -
          • III
          • -
          -​ - - - -``` - */ - parentsUntil(selector?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; - /** - * Get the current coordinates of the first element in the set of matched elements, relative to the offset parent. - * - * @see \`{@link https://api.jquery.com/position/ }\` - * @since 1.2 - * @example ​ ````Access the position of the second paragraph: -```html - - - - - position demo - - - - -​ -
          -

          Hello

          -
          -

          -​ - - - -``` - */ - position(): JQuery.Coordinates; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * @param contents One or more additional DOM elements, text nodes, arrays of elements and text nodes, HTML strings, or - * jQuery objects to insert at the beginning of each element in the set of matched elements. - * @see \`{@link https://api.jquery.com/prepend/ }\` - * @since 1.0 - * @example ​ ````Prepends some HTML to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          there, friend!

          -

          amigo!

          -​ - - - -``` - * @example ​ ````Prepends a DOM Element to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          is what I'd say

          -

          is what I said

          -​ - - - -``` - * @example ​ ````Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          is what was said.

          Hello -​ - - - -``` - */ - prepend(...contents: Array>>): this; - /** - * Insert content, specified by the parameter, to the beginning of each element in the set of matched elements. - * - * @param fn A function that returns an HTML string, DOM element(s), text node(s), or jQuery object to insert at - * the beginning of each element in the set of matched elements. Receives the index position of the - * element in the set and the old HTML value of the element as arguments. Within the function, this - * refers to the current element in the set. - * @see \`{@link https://api.jquery.com/prepend/ }\` - * @since 1.4 - * @example ​ ````Prepends some HTML to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          there, friend!

          -

          amigo!

          -​ - - - -``` - * @example ​ ````Prepends a DOM Element to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          is what I'd say

          -

          is what I said

          -​ - - - -``` - * @example ​ ````Prepends a jQuery object (similar to an Array of DOM Elements) to all paragraphs. -```html - - - - - prepend demo - - - - -​ -

          is what was said.

          Hello -​ - - - -``` - */ - prepend(fn: (this: TElement, index: number, html: string) => JQuery.htmlString | JQuery.TypeOrArray>): this; - /** - * Insert every element in the set of matched elements to the beginning of the target. - * - * @param target A selector, element, HTML string, array of elements, or jQuery object; the matched set of elements - * will be inserted at the beginning of the element(s) specified by this parameter. - * @see \`{@link https://api.jquery.com/prependTo/ }\` - * @since 1.0 - * @example ​ ````Prepend all spans to the element with the ID "foo" (Check .prepend() documentation for more examples) -```html - - - - - prependTo demo - - - - -​ -
          FOO!
          -I have something to say... -​ - - - -``` - */ - prependTo(target: JQuery.Selector | JQuery.htmlString | JQuery.TypeOrArray | JQuery): this; - /** - * Get the immediately preceding sibling of each element in the set of matched elements. If a selector - * is provided, it retrieves the previous sibling only if it matches that selector. - * - * @param selector A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/prev/ }\` - * @since 1.0 - * @example ​ ````Find the very previous sibling of each div. -```html - - - - - prev demo - - - - -​ -
          -
          -
          has child
          -
          -
          -
          -
          -
          -

          -​ - - - -``` - * @example ​ ````For each paragraph, find the very previous sibling that has a class "selected". -```html - - - - - prev demo - - - -​ -
          Hello
          -

          Hello Again

          -

          And Again

          -​ - - - -``` - */ - prev(selector?: JQuery.Selector): this; - /** - * Get all preceding siblings 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. - * @see \`{@link https://api.jquery.com/prevAll/ }\` - * @since 1.2 - * @example ​ ````Locate all the divs preceding the last div and give them a class. -```html - - - - - prevAll demo - - - - -​ -
          -
          -
          -
          -​ - - - -``` - */ - prevAll(selector?: JQuery.Selector): this; - /** - * Get all preceding siblings of each element up to but not including the element matched by the - * selector, DOM node, or jQuery object. - * - * @param selector A string containing a selector expression to indicate where to stop matching preceding sibling elements. - * A DOM node or jQuery object indicating where to stop matching preceding sibling elements. - * @param filter A string containing a selector expression to match elements against. - * @see \`{@link https://api.jquery.com/prevUntil/ }\` - * @since 1.4 - * @since 1.6 - * @example ​ ````Find the siblings that precede <dt id="term-2"> up to the preceding <dt> and give them a red background color. Also, find previous <dd> siblings of <dt id="term-3"> up to <dt id="term-1"> and give them a green text color. -```html - - - - - prevUntil demo - - - -​ -
          -
          term 1
          -
          definition 1-a
          -
          definition 1-b
          -
          definition 1-c
          -
          definition 1-d
          -​ -
          term 2
          -
          definition 2-a
          -
          definition 2-b
          -
          definition 2-c
          -​ -
          term 3
          -
          definition 3-a
          -
          definition 3-b
          -
          -​ - - - -``` - */ - prevUntil(selector?: JQuery.Selector | Element | JQuery, filter?: JQuery.Selector): this; - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, - * queued or not, have finished. - * - * @param type The type of queue that needs to be observed. - * @param target Object onto which the promise methods have to be attached - * @see \`{@link https://api.jquery.com/promise/ }\` - * @since 1.6 - * @example ​ ````Using .promise() on a collection with no active animation returns a resolved Promise: -```html - - - - - promise demo - - - -​​ - - - -``` - * @example ​ ````Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - */ - promise(type: string, target: T): T & JQuery.Promise; - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, - * queued or not, have finished. - * - * @param target Object onto which the promise methods have to be attached - * @see \`{@link https://api.jquery.com/promise/ }\` - * @since 1.6 - * @example ​ ````Using .promise() on a collection with no active animation returns a resolved Promise: -```html - - - - - promise demo - - - -​​ - - - -``` - * @example ​ ````Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - */ - promise(target: T): T & JQuery.Promise; - /** - * Return a Promise object to observe when all actions of a certain type bound to the collection, - * queued or not, have finished. - * - * @param type The type of queue that needs to be observed. - * @see \`{@link https://api.jquery.com/promise/ }\` - * @since 1.6 - * @example ​ ````Using .promise() on a collection with no active animation returns a resolved Promise: -```html - - - - - promise demo - - - -​​ - - - -``` - * @example ​ ````Resolve the returned Promise when all animations have ended (including those initiated in the animation callback or added later on): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Resolve the returned Promise using a $.when() statement (the .promise() method makes it possible to do this with jQuery collections): -```html - - - - - promise demo - - - - -​ - -

          Ready...

          -
          -
          -
          -
          -​ - - - -``` - */ - promise(type?: string): JQuery.Promise; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A function returning the value to set. Receives the index position of the element in the set and the - * old property value as arguments. Within the function, the keyword this refers to the current element. - * @see \`{@link https://api.jquery.com/prop/ }\` - * @since 1.6 - * @example ​ ````Display the checked property and attribute of a checkbox as it changes. -```html - - - - - prop demo - - - - -​ - - -

          -​ - - - -``` - * @example ​ ````Disable all checkboxes on the page. -```html - - - - - prop demo - - - - -​ - - - - -​ - - - -``` - */ - prop(propertyName: string, value: (this: TElement, index: number, oldPropertyValue: any) => any): this; - /** - * Set one or more properties for the set of matched elements. - * - * @param propertyName The name of the property to set. - * @param value A value to set for the property. - * @see \`{@link https://api.jquery.com/prop/ }\` - * @since 1.6 - * @example ​ ````Display the checked property and attribute of a checkbox as it changes. -```html - - - - - prop demo - - - - -​ - - -

          -​ - - - -``` - * @example ​ ````Disable all checkboxes on the page. -```html - - - - - prop demo - - - - -​ - - - - -​ - - - -``` - */ - prop(propertyName: string, value: any): this; // tslint:disable-line:unified-signatures - /** - * Set one or more properties for the set of matched elements. - * - * @param properties An object of property-value pairs to set. - * @see \`{@link https://api.jquery.com/prop/ }\` - * @since 1.6 - * @example ​ ````Display the checked property and attribute of a checkbox as it changes. -```html - - - - - prop demo - - - - -​ - - -

          -​ - - - -``` - * @example ​ ````Disable all checkboxes on the page. -```html - - - - - prop demo - - - - -​ - - - - -​ - - - -``` - */ - prop(properties: JQuery.PlainObject): this; - /** - * Get the value of a property for the first element in the set of matched elements. - * - * @param propertyName The name of the property to get. - * @see \`{@link https://api.jquery.com/prop/ }\` - * @since 1.6 - * @example ​ ````Display the checked property and attribute of a checkbox as it changes. -```html - - - - - prop demo - - - - -​ - - -

          -​ - - - -``` - * @example ​ ````Disable all checkboxes on the page. -```html - - - - - prop demo - - - - -​ - - - - -​ - - - -``` - */ - prop(propertyName: string): any | undefined; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @param name The name of a jQuery method that generated the array of elements. - * @param args The arguments that were passed in to the jQuery method (for serialization). - * @see \`{@link https://api.jquery.com/pushStack/ }\` - * @since 1.3 - * @example ​ ````Add some elements onto the jQuery stack, then pop back off again. -```html - - - - - pushStack demo - - - -​​ - - - -``` - */ - pushStack(elements: ArrayLike, name: string, args: any[]): this; - /** - * Add a collection of DOM elements onto the jQuery stack. - * - * @param elements An array of elements to push onto the stack and make into a new jQuery object. - * @see \`{@link https://api.jquery.com/pushStack/ }\` - * @since 1.0 - * @example ​ ````Add some elements onto the jQuery stack, then pop back off again. -```html - - - - - pushStack demo - - - -​​ - - - -``` - */ - pushStack(elements: ArrayLike): this; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. - * An array of functions to replace the current queue contents. - * @see \`{@link https://api.jquery.com/queue/ }\` - * @since 1.2 - * @example ​ ````Show the length of the queue. -```html - - - - - queue demo - - - - -​ -

          The queue length is:

          -
          -​ - - - -``` - * @example ​ ````Queue a custom function. -```html - - - - - queue demo - - - - -​ -Click here... -
          -​ - - - -``` - * @example ​ ````Set a queue array to delete the queue. -```html - - - - - queue demo - - - - -​ - - -
          -​ - - - -``` - */ - queue(queueName: string, newQueue: JQuery.TypeOrArray>): this; - /** - * Manipulate the queue of functions to be executed, once for each matched element. - * - * @param newQueue The new function to add to the queue, with a function to call that will dequeue the next item. - * An array of functions to replace the current queue contents. - * @see \`{@link https://api.jquery.com/queue/ }\` - * @since 1.2 - * @example ​ ````Show the length of the queue. -```html - - - - - queue demo - - - - -​ -

          The queue length is:

          -
          -​ - - - -``` - * @example ​ ````Queue a custom function. -```html - - - - - queue demo - - - - -​ -Click here... -
          -​ - - - -``` - * @example ​ ````Set a queue array to delete the queue. -```html - - - - - queue demo - - - - -​ - - -
          -​ - - - -``` - */ - queue(newQueue: JQuery.TypeOrArray>): this; - /** - * Show the queue of functions to be executed on the matched elements. - * - * @param queueName A string containing the name of the queue. Defaults to fx, the standard effects queue. - * @see \`{@link https://api.jquery.com/queue/ }\` - * @since 1.2 - * @example ​ ````Show the length of the queue. -```html - - - - - queue demo - - - - -​ -

          The queue length is:

          -
          -​ - - - -``` - * @example ​ ````Queue a custom function. -```html - - - - - queue demo - - - - -​ -Click here... -
          -​ - - - -``` - * @example ​ ````Set a queue array to delete the queue. -```html - - - - - queue demo - - - - -​ - - -
          -​ - - - -``` - */ - queue(queueName?: string): JQuery.Queue; - /** - * Specify a function to execute when the DOM is fully loaded. - * - * @param handler A function to execute after the DOM is ready. - * @see \`{@link https://api.jquery.com/ready/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.0. Use `jQuery(function() { })`. - * @example ​ ````Display a message when the DOM is loaded. -```html - - - - - ready demo - - - - - -​ -

          Not loaded yet.

          - - - -``` - */ - ready(handler: ($: JQueryStatic) => void): this; - /** - * Remove the set of matched elements from the DOM. - * - * @param selector A selector expression that filters the set of matched elements to be removed. - * @see \`{@link https://api.jquery.com/remove/ }\` - * @since 1.0 - * @example ​ ````Removes all paragraphs from the DOM -```html - - - - - remove demo - - - - -​ -

          Hello

          -how are -

          you?

          - -​ - - - -``` - * @example ​ ````Removes all paragraphs that contain "Hello" from the DOM. Analogous to doing $("p").filter(":contains('Hello')").remove(). -```html - - - - - remove demo - - - - -​ -

          Hello

          -how are -

          you?

          - -​ - - - -``` - */ - remove(selector?: string): this; - /** - * Remove an attribute from each element in the set of matched elements. - * - * @param attributeName An attribute to remove; as of version 1.7, it can be a space-separated list of attributes. - * @see \`{@link https://api.jquery.com/removeAttr/ }\` - * @since 1.0 - * @example ​ ````Clicking the button changes the title of the input next to it. Move the mouse pointer over the text input to see the effect of adding and removing the title attribute. -```html - - - - - removeAttr demo - - - -​ - - -
          -​ - - - -``` - */ - removeAttr(attributeName: string): this; - /** - * Remove a single class, multiple classes, or all classes from each element in the set of matched elements. - * - * @param className One or more space-separated classes to be removed from the class attribute of each matched element. - * An array of classes to be removed from the class attribute of each matched element. - * A function returning one or more space-separated class names to be removed. Receives the index - * position of the element in the set and the old class value as arguments. - * @see \`{@link https://api.jquery.com/removeClass/ }\` - * @since 1.0 - * @since 1.4 - * @since 3.3 - * @example ​ ````Remove the class 'blue' from the matched elements. -```html - - - - - removeClass demo - - - - -​ -

          Hello

          -

          and

          -

          then

          -

          Goodbye

          -​ - - - -``` - * @example ​ ````Remove the class 'blue' and 'under' from the matched elements. -```html - - - - - removeClass demo - - - - -​ -

          Hello

          -

          and

          -

          then

          -

          Goodbye

          -​ - - - -``` - * @example ​ ````Remove all the classes from the matched elements. -```html - - - - - removeClass demo - - - - -​ -

          Hello

          -

          and

          -

          then

          -

          Goodbye

          -​ - - - -``` - */ - removeClass(className?: JQuery.TypeOrArray | ((this: TElement, index: number, className: string) => string)): this; - /** - * Remove a previously-stored piece of data. - * - * @param name A string naming the piece of data to delete. - * An array or space-separated string naming the pieces of data to delete. - * @see \`{@link https://api.jquery.com/removeData/ }\` - * @since 1.2.3 - * @since 1.7 - * @example ​ ````Set a data store for 2 names then remove one of them. -```html - - - - - removeData demo - - - - -​ -
          value1 before creation:
          -
          value1 after creation:
          -
          value1 after removal:
          -
          value2 after removal:
          -​ - - - -``` - */ - removeData(name?: JQuery.TypeOrArray): this; - /** - * Remove a property for the set of matched elements. - * - * @param propertyName The name of the property to remove. - * @see \`{@link https://api.jquery.com/removeProp/ }\` - * @since 1.6 - * @example ​ ````Set a numeric property on a paragraph and then remove it. -```html - - - - - removeProp demo - - - - -​ -

          -​ - - - -``` - */ - removeProp(propertyName: string): this; - /** - * Replace each target element with the set of matched elements. - * - * @param target A selector string, jQuery object, DOM element, or array of elements indicating which element(s) to replace. - * @see \`{@link https://api.jquery.com/replaceAll/ }\` - * @since 1.2 - * @example ​ ````Replace all the paragraphs with bold words. -```html - - - - - replaceAll demo - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - */ - replaceAll(target: JQuery.Selector | JQuery | JQuery.TypeOrArray): this; - /** - * Replace each element in the set of matched elements with the provided new content and return the set - * of elements that was removed. - * - * @param newContent The content to insert. May be an HTML string, DOM element, array of DOM elements, or jQuery object. - * A function that returns content with which to replace the set of matched elements. - * @see \`{@link https://api.jquery.com/replaceWith/ }\` - * @since 1.2 - * @since 1.4 - * @example ​ ````On click, replace the button with a div containing the same word. -```html - - - - - replaceWith demo - - - - -​ - - - -​ - - - -``` - * @example ​ ````Replace all paragraphs with bold words. -```html - - - - - replaceWith demo - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````On click, replace each paragraph with a div that is already in the DOM and selected with the $() function. Notice it doesn't clone the object but rather moves it to replace the paragraph. -```html - - - - - replaceWith demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -
          Replaced!
          -​ - - - -``` - * @example ​ ````On button click, replace the containing div with its child divs and append the class name of the selected element to the paragraph. -```html - - - - - replaceWith demo - - - - -​ -

          - -

          -
          -
          Scooby
          -
          Dooby
          -
          Doo
          -
          -​ - - - -``` - */ - replaceWith(newContent: JQuery.htmlString | JQuery | JQuery.TypeOrArray | ((this: TElement) => any)): this; - /** - * Bind an event handler to the "resize" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/resize/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To see the window width while (or after) it is resized, try: -```html - - - - - resize demo - - - -​​ - - - -``` - */ - resize(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/resize/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To see the window width while (or after) it is resized, try: -```html - - - - - resize demo - - - -​​ - - - -``` - */ - resize(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/scroll/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To do something when your page is scrolled: -```html - - - - - scroll demo - - - - -​ -
          Try scrolling the iframe.
          -

          Paragraph - Scroll happened!

          -​ - - - -``` - */ - scroll(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/scroll/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To do something when your page is scrolled: -```html - - - - - scroll demo - - - - -​ -
          Try scrolling the iframe.
          -

          Paragraph - Scroll happened!

          -​ - - - -``` - */ - scroll(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | 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. - * @see \`{@link https://api.jquery.com/scrollLeft/ }\` - * @since 1.2.6 - * @example ​ ````Get the scrollLeft of a paragraph. -```html - - - - - scrollLeft demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Set the scrollLeft of a div. -```html - - - - - scrollLeft demo - - - - -​ -

          lalala

          Hello

          -​ - - - -``` - */ - scrollLeft(value: number): this; - /** - * Get the current horizontal position of the scroll bar for the first element in the set of matched elements. - * - * @see \`{@link https://api.jquery.com/scrollLeft/ }\` - * @since 1.2.6 - * @example ​ ````Get the scrollLeft of a paragraph. -```html - - - - - scrollLeft demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Set the scrollLeft of a div. -```html - - - - - scrollLeft demo - - - - -​ -

          lalala

          Hello

          -​ - - - -``` - */ - scrollLeft(): number | undefined; - /** - * Set the current vertical position of the scroll bar for each of the set of matched elements. - * - * @param value A number indicating the new position to set the scroll bar to. - * @see \`{@link https://api.jquery.com/scrollTop/ }\` - * @since 1.2.6 - * @example ​ ````Get the scrollTop of a paragraph. -```html - - - - - scrollTop demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Set the scrollTop of a div. -```html - - - - - scrollTop demo - - - - -​ -

          lalala

          Hello

          -​ - - - -``` - */ - scrollTop(value: number): this; - /** - * Get the current vertical position of the scroll bar for the first element in the set of matched - * elements or set the vertical position of the scroll bar for every matched element. - * - * @see \`{@link https://api.jquery.com/scrollTop/ }\` - * @since 1.2.6 - * @example ​ ````Get the scrollTop of a paragraph. -```html - - - - - scrollTop demo - - - - -​ -

          Hello

          -​ - - - -``` - * @example ​ ````Set the scrollTop of a div. -```html - - - - - scrollTop demo - - - - -​ -

          lalala

          Hello

          -​ - - - -``` - */ - scrollTop(): number | undefined; - /** - * Bind an event handler to the "select" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/select/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To do something when text in input boxes is selected: -```html - - - - - select demo - - - - -​ -

          Click and drag the mouse to select text in the inputs.

          - - -
          - ​ - - - -``` - * @example ​ ````To trigger the select event on all input elements, try: -```html - - - - - select demo - - - -​​ - - - -``` - */ - select(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/select/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````To do something when text in input boxes is selected: -```html - - - - - select demo - - - - -​ -

          Click and drag the mouse to select text in the inputs.

          - - -
          - ​ - - - -``` - * @example ​ ````To trigger the select event on all input elements, try: -```html - - - - - select demo - - - -​​ - - - -``` - */ - select(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Encode a set of form elements as a string for submission. - * - * @see \`{@link https://api.jquery.com/serialize/ }\` - * @since 1.0 - * @example ​ ````Serialize a form to a query string that could be sent to a server in an Ajax request. -```html - - - - - serialize demo - - - - -​ -
          - -​ -
          - -​ -
          - - - - -​ -
          - - - - -
          -​ -

          -​ - - - -``` - */ - serialize(): string; - /** - * Encode a set of form elements as an array of names and values. - * - * @see \`{@link https://api.jquery.com/serializeArray/ }\` - * @since 1.2 - * @example ​ ````Get the values from a form, iterate through them, and append them to a results display. -```html - - - - - serializeArray demo - - - - -​ -

          Results:

          -
          - - -
          - - - - - - - - -
          -​ - - - -``` - */ - serializeArray(): JQuery.NameValuePair[]; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/show/ }\` - * @since 1.4.3 - * @example ​ ````Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. -```html - - - - - show demo - - - - -​ - -

          Hello 2

          -​ - - - -``` - * @example ​ ````Show the first div, followed by each next adjacent sibling div in order, with a 200ms animation. Each animation starts when the previous sibling div's animation ends. -```html - - - - - show demo - - - - -​ - - -
          Hello 3,
          -
          how
          -
          are
          -
          you?
          -​ - - - -``` - * @example ​ ````Show all span and input elements with an animation. Change the text once the animation is done. -```html - - - - - show demo - - - - -​ - -Are you sure? (type 'yes' if you are) -
          -
          - -
          -
          -

          I'm hidden...

          -​ - - - -``` - */ - show(duration: JQuery.Duration, easing: string, complete: (this: TElement) => void): this; - /** - * Display the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing_complete A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/show/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. -```html - - - - - show demo - - - - -​ - -

          Hello 2

          -​ - - - -``` - * @example ​ ````Show the first div, followed by each next adjacent sibling div in order, with a 200ms animation. Each animation starts when the previous sibling div's animation ends. -```html - - - - - show demo - - - - -​ - - -
          Hello 3,
          -
          how
          -
          are
          -
          you?
          -​ - - - -``` - * @example ​ ````Show all span and input elements with an animation. Change the text once the animation is done. -```html - - - - - show demo - - - - -​ - -Are you sure? (type 'yes' if you are) -
          -
          - -
          -
          -

          I'm hidden...

          -​ - - - -``` - */ - show(duration: JQuery.Duration, easing_complete: string | ((this: TElement) => void)): this; - /** - * Display the matched elements. - * - * @param duration_complete_options A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/show/ }\` - * @since 1.0 - * @example ​ ````Animates all hidden paragraphs to show slowly, completing the animation within 600 milliseconds. -```html - - - - - show demo - - - - -​ - -

          Hello 2

          -​ - - - -``` - * @example ​ ````Show the first div, followed by each next adjacent sibling div in order, with a 200ms animation. Each animation starts when the previous sibling div's animation ends. -```html - - - - - show demo - - - - -​ - - -
          Hello 3,
          -
          how
          -
          are
          -
          you?
          -​ - - - -``` - * @example ​ ````Show all span and input elements with an animation. Change the text once the animation is done. -```html - - - - - show demo - - - - -​ - -Are you sure? (type 'yes' if you are) -
          -
          - -
          -
          -

          I'm hidden...

          -​ - - - -``` - */ - show(duration_complete_options?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Get the siblings 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. - * @see \`{@link https://api.jquery.com/siblings/ }\` - * @since 1.0 - * @example ​ ````Find the unique siblings of all yellow li elements in the 3 lists (including other yellow li elements if appropriate). -```html - - - - - siblings demo - - - - -​ -
            -
          • One
          • -
          • Two
          • -
          • Three
          • -
          • Four
          • -
          -​ -
            -
          • Five
          • -
          • Six
          • -
          • Seven
          • -
          -​ -
            -
          • Eight
          • -
          • Nine
          • -
          • Ten
          • -
          • Eleven
          • -
          -​ -

          Unique siblings:

          -​ - - - -``` - * @example ​ ````Find all siblings with a class "selected" of each div. -```html - - - - - siblings demo - - - -​ -
          Hello
          -

          Hello Again

          -

          And Again

          -​ - - - -``` - */ - siblings(selector?: JQuery.Selector): this; - /** - * Reduce the set of matched elements to a subset specified by a range of indices. - * - * @param start An integer indicating the 0-based position at which the elements begin to be selected. If negative, - * it indicates an offset from the end of the set. - * @param end An integer indicating the 0-based position at which the elements stop being selected. If negative, - * it indicates an offset from the end of the set. If omitted, the range continues until the end of the set. - * @see \`{@link https://api.jquery.com/slice/ }\` - * @since 1.1.4 - * @example ​ ````Turns divs yellow based on a random slice. -```html - - - - - slice demo - - - - -​ -

          - Click the button!

          -
          -
          -
          -
          -
          -
          -
          -
          -
          - ​ - - - -``` - * @example ​ ````Selects all paragraphs, then slices the selection to include only the first element. -```html - - - - - slice demo - - - -​​ - - - -``` - * @example ​ ````Selects all paragraphs, then slices the selection to include only the first and second element. -```html - - - - - slice demo - - - -​​ - - - -``` - * @example ​ ````Selects all paragraphs, then slices the selection to include only the second element. -```html - - - - - slice demo - - - -​​ - - - -``` - * @example ​ ````Selects all paragraphs, then slices the selection to include only the second and third element. -```html - - - - - slice demo - - - -​​ - - - -``` - * @example ​ ````Selects all paragraphs, then slices the selection to include only the third element. -```html - - - - - slice demo - - - -​​ - - - -``` - */ - slice(start: number, end?: number): this; - /** - * Display the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideDown/ }\` - * @since 1.4.3 - * @example ​ ````Animates all divs to slide down and show themselves over 600 milliseconds. -```html - - - - - slideDown demo - - - - -​ -Click me! -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus. -```html - - - - - slideDown demo - - - - -​ -
          Push!
          - - - - ​ - - - -``` - */ - slideDown(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Display the matched elements with a sliding motion. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideDown/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all divs to slide down and show themselves over 600 milliseconds. -```html - - - - - slideDown demo - - - - -​ -Click me! -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus. -```html - - - - - slideDown demo - - - - -​ -
          Push!
          - - - - ​ - - - -``` - */ - slideDown(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Display the matched elements with a sliding motion. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/slideDown/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all divs to slide down and show themselves over 600 milliseconds. -```html - - - - - slideDown demo - - - - -​ -Click me! -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates all inputs to slide down, completing the animation within 1000 milliseconds. Once the animation is done, the input look is changed especially if it is the middle input which gets the focus. -```html - - - - - slideDown demo - - - - -​ -
          Push!
          - - - - ​ - - - -``` - */ - slideDown(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideToggle/ }\` - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds. -```html - - - - - slideToggle demo - - - - -​ - -

          - This is the paragraph to end all paragraphs. You - should feel lucky to have seen such a paragraph in - your life. Congratulations! -

          -​ - - - -``` - * @example ​ ````Animates divs between dividers with a toggle that makes some appear and some disappear. -```html - - - - - slideToggle demo - - - - -​ -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -

          There have been 0 toggled divs.

          -​ - - - -``` - */ - slideToggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideToggle/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds. -```html - - - - - slideToggle demo - - - - -​ - -

          - This is the paragraph to end all paragraphs. You - should feel lucky to have seen such a paragraph in - your life. Congratulations! -

          -​ - - - -``` - * @example ​ ````Animates divs between dividers with a toggle that makes some appear and some disappear. -```html - - - - - slideToggle demo - - - - -​ -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -

          There have been 0 toggled divs.

          -​ - - - -``` - */ - slideToggle(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Display or hide the matched elements with a sliding motion. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/slideToggle/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all paragraphs to slide up or down, completing the animation within 600 milliseconds. -```html - - - - - slideToggle demo - - - - -​ - -

          - This is the paragraph to end all paragraphs. You - should feel lucky to have seen such a paragraph in - your life. Congratulations! -

          -​ - - - -``` - * @example ​ ````Animates divs between dividers with a toggle that makes some appear and some disappear. -```html - - - - - slideToggle demo - - - - -​ -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -
          -

          There have been 0 toggled divs.

          -​ - - - -``` - */ - slideToggle(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideUp/ }\` - * @since 1.4.3 - * @example ​ ````Animates all divs to slide up, completing the animation within 400 milliseconds. -```html - - - - - slideUp demo - - - - -​ -Click me! -
          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert. -```html - - - - - slideUp demo - - - - -​ -
          - - -
          -​ -
          - - -
          -​ -
          - - -
          -​ -
          -​ - - - -``` - */ - slideUp(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration_easing A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/slideUp/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all divs to slide up, completing the animation within 400 milliseconds. -```html - - - - - slideUp demo - - - - -​ -Click me! -
          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert. -```html - - - - - slideUp demo - - - - -​ -
          - - -
          -​ -
          - - -
          -​ -
          - - -
          -​ -
          -​ - - - -``` - */ - slideUp(duration_easing: JQuery.Duration | string, complete: (this: TElement) => void): this; - /** - * Hide the matched elements with a sliding motion. - * - * @param duration_easing_complete_options A string or number determining how long the animation will run. - * A string indicating which easing function to use for the transition. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * @see \`{@link https://api.jquery.com/slideUp/ }\` - * @since 1.0 - * @since 1.4.3 - * @example ​ ````Animates all divs to slide up, completing the animation within 400 milliseconds. -```html - - - - - slideUp demo - - - - -​ -Click me! -
          -
          -
          -
          -
          -​ - - - -``` - * @example ​ ````Animates the parent paragraph to slide up, completing the animation within 200 milliseconds. Once the animation is done, it displays an alert. -```html - - - - - slideUp demo - - - - -​ -
          - - -
          -​ -
          - - -
          -​ -
          - - -
          -​ -
          -​ - - - -``` - */ - slideUp(duration_easing_complete_options?: JQuery.Duration | string | ((this: TElement) => void) | JQuery.EffectsOptions): this; - /** - * Stop the currently-running animation on the matched elements. - * - * @param queue The name of the queue in which to stop animations. - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - * @see \`{@link https://api.jquery.com/stop/ }\` - * @since 1.7 - * @example ​ ````Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one. -```html - - - - - stop demo - - - - -​ - - - -
          -​ - - - -``` - * @example ​ ````Click the slideToggle button to start the animation, then click again before the animation is completed. The animation will toggle the other direction from the saved starting point. -```html - - - - - stop demo - - - - -​ - -
          -​ - - - -``` - */ - stop(queue: string, clearQueue?: boolean, jumpToEnd?: boolean): this; - /** - * Stop the currently-running animation on the matched elements. - * - * @param clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false. - * @param jumpToEnd A Boolean indicating whether to complete the current animation immediately. Defaults to false. - * @see \`{@link https://api.jquery.com/stop/ }\` - * @since 1.2 - * @example ​ ````Click the Go button once to start the animation, then click the STOP button to stop it where it's currently positioned. Another option is to click several buttons to queue them up and see that stop just kills the currently playing one. -```html - - - - - stop demo - - - - -​ - - - -
          -​ - - - -``` - * @example ​ ````Click the slideToggle button to start the animation, then click again before the animation is completed. The animation will toggle the other direction from the saved starting point. -```html - - - - - stop demo - - - - -​ - -
          -​ - - - -``` - */ - stop(clearQueue?: boolean, jumpToEnd?: boolean): this; - /** - * Bind an event handler to the "submit" JavaScript event, or trigger that event on an element. - * - * @param eventData An object containing data that will be passed to the event handler. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/submit/ }\` - * @since 1.4.3 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: -```html - - - - - submit demo - - - - -​ -

          Type 'correct' to validate.

          -
          -
          - - -
          -
          - -​ - - - -``` - * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: -```html - - - - - submit demo - - - -​​ - - - -``` - * @example ​ ````To trigger the submit event on the first form on the page, try: -```html - - - - - submit demo - - - -​​ - - - -``` - */ - submit(eventData: TData, - handler: JQuery.EventHandler | JQuery.EventHandlerBase>): 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. - * @see \`{@link https://api.jquery.com/submit/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.3. Use \`{@link JQuery.on }\` or \`{@link JQuery.trigger }\`. - * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: -```html - - - - - submit demo - - - - -​ -

          Type 'correct' to validate.

          -
          -
          - - -
          -
          - -​ - - - -``` - * @example ​ ````If you'd like to prevent forms from being submitted unless a flag variable is set, try: -```html - - - - - submit demo - - - -​​ - - - -``` - * @example ​ ````To trigger the submit event on the first form on the page, try: -```html - - - - - submit demo - - - -​​ - - - -``` - */ - submit(handler?: JQuery.EventHandler | JQuery.EventHandlerBase> | false): this; - /** - * Set the content of each element in the set of matched elements to the specified text. - * - * @param text The text to set as the content of each matched element. When Number or Boolean is supplied, it will - * be converted to a String representation. - * A function returning the text content to set. Receives the index position of the element in the set - * and the old text value as arguments. - * @see \`{@link https://api.jquery.com/text/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone). -```html - - - - - text demo - - - - -​ -

          Test Paragraph.

          -

          -​ - - - -``` - * @example ​ ````Add text to the paragraph (notice the bold tag is escaped). -```html - - - - - text demo - - - - -​ -

          Test Paragraph.

          -​ - - - -``` - */ - text(text: string | number | boolean | ((this: TElement, index: number, text: string) => string | number | boolean)): this; - /** - * Get the combined text contents of each element in the set of matched elements, including their descendants. - * - * @see \`{@link https://api.jquery.com/text/ }\` - * @since 1.0 - * @example ​ ````Find the text in the first paragraph (stripping out the html), then set the html of the last paragraph to show it is just text (the red bold is gone). -```html - - - - - text demo - - - - -​ -

          Test Paragraph.

          -

          -​ - - - -``` - * @example ​ ````Add text to the paragraph (notice the bold tag is escaped). -```html - - - - - text demo - - - - -​ -

          Test Paragraph.

          -​ - - - -``` - */ - text(): string; - /** - * Retrieve all the elements contained in the jQuery set, as an array. - * - * @see \`{@link https://api.jquery.com/toArray/ }\` - * @since 1.4 - * @example ​ ````Select all divs in the document and return the DOM Elements as an Array; then use the built-in reverse() method to reverse that array. -```html - - - - - toArray demo - - - - -​ -Reversed - -​ -
          One
          -
          Two
          -
          Three
          ​ - - - -``` - */ - toArray(): TElement[]; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param easing A string indicating which easing function to use for the transition. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/toggle/ }\` - * @since 1.4.3 - * @example ​ ````Toggles all paragraphs. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - * @example ​ ````Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds. -```html - - - - - toggle demo - - - - -​ - -

          Hiya

          -

          Such interesting text, eh?

          -​ - - - -``` - * @example ​ ````Shows all paragraphs, then hides them all, back and forth. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - */ - toggle(duration: JQuery.Duration, easing: string, complete?: (this: TElement) => void): this; - /** - * Display or hide the matched elements. - * - * @param duration A string or number determining how long the animation will run. - * @param complete A function to call once the animation is complete, called once per matched element. - * @see \`{@link https://api.jquery.com/toggle/ }\` - * @since 1.0 - * @example ​ ````Toggles all paragraphs. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - * @example ​ ````Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds. -```html - - - - - toggle demo - - - - -​ - -

          Hiya

          -

          Such interesting text, eh?

          -​ - - - -``` - * @example ​ ````Shows all paragraphs, then hides them all, back and forth. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - */ - toggle(duration: JQuery.Duration, complete: (this: TElement) => void): this; - /** - * Display or hide the matched elements. - * - * @param duration_complete_options_display A string or number determining how long the animation will run. - * A function to call once the animation is complete, called once per matched element. - * A map of additional options to pass to the method. - * Use true to show the element or false to hide it. - * @see \`{@link https://api.jquery.com/toggle/ }\` - * @since 1.0 - * @since 1.3 - * @example ​ ````Toggles all paragraphs. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - * @example ​ ````Animates all paragraphs to be shown if they are hidden and hidden if they are visible, completing the animation within 600 milliseconds. -```html - - - - - toggle demo - - - - -​ - -

          Hiya

          -

          Such interesting text, eh?

          -​ - - - -``` - * @example ​ ````Shows all paragraphs, then hides them all, back and forth. -```html - - - - - toggle demo - - - -​ - -

          Hello

          -

          Good Bye

          -​ - - - -``` - */ - toggle(duration_complete_options_display?: JQuery.Duration | ((this: TElement) => void) | JQuery.EffectsOptions | boolean): this; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on - * either the class's presence or the value of the state argument. - * - * @param className One or more class names (separated by spaces) to be toggled for each element in the matched set. - * An array of classes to be toggled for each element in the matched set. - * A function that returns class names to be toggled in the class attribute of each element in the - * matched set. Receives the index position of the element in the set, the old class value, and the state as arguments. - * @param state A Boolean (not just truthy/falsy) value to determine whether the class should be added or removed. - * @see \`{@link https://api.jquery.com/toggleClass/ }\` - * @since 1.0 - * @since 1.3 - * @since 1.4 - * @since 3.3 - * @example ​ ````Toggle the class 'highlight' when a paragraph is clicked. -```html - - - - - toggleClass demo - - - - -​ -

          Click to toggle

          -

          highlight

          -

          on these

          -

          paragraphs

          -​ - - - -``` - * @example ​ ````Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click. -```html - - - - - toggleClass demo - - - - -​ -

          Click to toggle (clicks: 0)

          -

          highlight (clicks: 0)

          -

          on these (clicks: 0)

          -

          paragraphs (clicks: 0)

          -​ - - - -``` - * @example ​ ````Toggle the class name(s) indicated on the buttons for each div. -```html - - - - - toggleClass demo - - - - -​ -
          - - - - - reset -
          -
          -
          -
          -
          -
          -
          -​ - - - -``` - */ - toggleClass(className: JQuery.TypeOrArray | ((this: TElement, index: number, className: string, state: TState) => string), - state?: TState): this; - /** - * Add or remove one or more classes from each element in the set of matched elements, depending on - * either the class's presence or the value of the state argument. - * - * @param state A boolean value to determine whether the class should be added or removed. - * @see \`{@link https://api.jquery.com/toggleClass/ }\` - * @since 1.4 - * @deprecated Deprecated since 3.0. See \`{@link https://github.com/jquery/jquery/pull/2618 }\`. - * @example ​ ````Toggle the class 'highlight' when a paragraph is clicked. -```html - - - - - toggleClass demo - - - - -​ -

          Click to toggle

          -

          highlight

          -

          on these

          -

          paragraphs

          -​ - - - -``` - * @example ​ ````Add the "highlight" class to the clicked paragraph on every third click of that paragraph, remove it every first and second click. -```html - - - - - toggleClass demo - - - - -​ -

          Click to toggle (clicks: 0)

          -

          highlight (clicks: 0)

          -

          on these (clicks: 0)

          -

          paragraphs (clicks: 0)

          -​ - - - -``` - * @example ​ ````Toggle the class name(s) indicated on the buttons for each div. -```html - - - - - toggleClass demo - - - - -​ -
          - - - - - reset -
          -
          -
          -
          -
          -
          -
          -​ - - - -``` - */ - toggleClass(state?: boolean): this; - /** - * Execute all handlers and behaviors attached to the matched elements for the given event type. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - * @see \`{@link https://api.jquery.com/trigger/ }\` - * @since 1.0 - * @since 1.3 - * @example ​ ````Clicks to button #2 also trigger a click for button #1. -```html - - - - - trigger demo - - - - -​ - - -
          0 button #1 clicks.
          -
          0 button #2 clicks.
          -​ - - - -``` - * @example ​ ````To submit the first form without using the submit() function, try: -```html - - - - - trigger demo - - - -​​ - - - -``` - * @example ​ ````To submit the first form without using the submit() function, try: -```html - - - - - trigger demo - - - -​​ - - - -``` - * @example ​ ````To pass arbitrary data to an event: -```html - - - - - trigger demo - - - -​​ - - - -``` - * @example ​ ````To pass arbitrary data through an event object: -```html - - - - - trigger demo - - - -​​ - - - -``` - * @example ​ ````Alternative way to pass data through an event object: -```html - - - - - trigger demo - - - -​​ - - - -``` - */ - trigger(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): this; - /** - * Execute all handlers attached to an element for an event. - * - * @param eventType A string containing a JavaScript event type, such as click or submit. - * A jQuery.Event object. - * @param extraParameters Additional parameters to pass along to the event handler. - * @see \`{@link https://api.jquery.com/triggerHandler/ }\` - * @since 1.2 - * @since 1.3 - * @example ​ ````If you called .triggerHandler() on a focus event - the browser's default focus action would not be triggered, only the event handlers bound to the focus event. -```html - - - - - triggerHandler demo - - - -​ - -

          -​ - -​ - - - -``` - */ - triggerHandler(eventType: string | JQuery.Event, extraParameters?: any[] | JQuery.PlainObject | string | number | boolean): undefined | 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. - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/unbind/ }\` - * @since 1.0 - * @since 1.4.3 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. - * @example ​ ````Can bind and unbind events to the colored button. -```html - - - - - unbind demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````To unbind all events from all paragraphs, write: -```html - - - - - unbind demo - - - -​​ - - - -``` - * @example ​ ````To unbind all click events from all paragraphs, write: -```html - - - - - unbind demo - - - -​​ - - - -``` - * @example ​ ````To unbind just one previously bound handler, pass the function in as the second argument: -```html - - - - - unbind demo - - - -​​ - - - -``` - */ - unbind(event: string, handler: JQuery.EventHandlerBase> | 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. - * A jQuery.Event object. - * @see \`{@link https://api.jquery.com/unbind/ }\` - * @since 1.0 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. - * @example ​ ````Can bind and unbind events to the colored button. -```html - - - - - unbind demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````To unbind all events from all paragraphs, write: -```html - - - - - unbind demo - - - -​​ - - - -``` - * @example ​ ````To unbind all click events from all paragraphs, write: -```html - - - - - unbind demo - - - -​​ - - - -``` - * @example ​ ````To unbind just one previously bound handler, pass the function in as the second argument: -```html - - - - - unbind demo - - - -​​ - - - -``` - */ - unbind(event?: string | JQuery.Event): 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 eventType A string containing a JavaScript event type, such as "click" or "keydown" - * @param handler A function to execute each time the event is triggered. - * @see \`{@link https://api.jquery.com/undelegate/ }\` - * @since 1.4.2 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. - * @example ​ ````Can bind and unbind events to the colored button. -```html - - - - - undelegate demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````To unbind all delegated events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated click events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To undelegate just one previously bound handler, pass the function in as the third argument: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated events by their namespace: -```html - - - - - undelegate demo - - - -​​ - - - -``` - */ - undelegate(selector: JQuery.Selector, eventType: string, handler: JQuery.EventHandlerBase> | 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. - * @see \`{@link https://api.jquery.com/undelegate/ }\` - * @since 1.4.2 - * @since 1.4.3 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. - * @example ​ ````Can bind and unbind events to the colored button. -```html - - - - - undelegate demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````To unbind all delegated events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated click events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To undelegate just one previously bound handler, pass the function in as the third argument: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated events by their namespace: -```html - - - - - undelegate demo - - - -​​ - - - -``` - */ - undelegate(selector: JQuery.Selector, eventTypes: string | JQuery.PlainObject> | 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 namespace A selector which will be used to filter the event results. - * @see \`{@link https://api.jquery.com/undelegate/ }\` - * @since 1.4.2 - * @since 1.6 - * @deprecated Deprecated since 3.0. Use \`{@link JQuery.off }\`. - * @example ​ ````Can bind and unbind events to the colored button. -```html - - - - - undelegate demo - - - - -​ - - - -
          Click!
          -​ - - - -``` - * @example ​ ````To unbind all delegated events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated click events from all paragraphs, write: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To undelegate just one previously bound handler, pass the function in as the third argument: -```html - - - - - undelegate demo - - - -​​ - - - -``` - * @example ​ ````To unbind all delegated events by their namespace: -```html - - - - - undelegate demo - - - -​​ - - - -``` - */ - undelegate(namespace?: string): this; - /** - * Remove the parents of the set of matched elements from the DOM, leaving the matched elements in their place. - * - * @param selector A selector to check the parent element against. If an element's parent does not match the selector, - * the element won't be unwrapped. - * @see \`{@link https://api.jquery.com/unwrap/ }\` - * @since 1.4 - * @since 3.0 - * @example ​ ````Wrap/unwrap a div around each of the paragraphs. -```html - - - - - unwrap demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          ​ - - - -``` - */ - unwrap(selector?: string): this; - /** - * Set the value of each element in the set of matched elements. - * - * @param value A string of text, a number, or an array of strings corresponding to the value of each matched - * element to set as selected/checked. - * A function returning the value to set. this is the current element. Receives the index position of - * the element in the set and the old value as arguments. - * @see \`{@link https://api.jquery.com/val/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Get the single value from a single select and an array of values from a multiple select and display their values. -```html - - - - - val demo - - - - -​ -

          -​ - -​ - -​ - - - -``` - * @example ​ ````Find the value of an input box. -```html - - - - - val demo - - - - -​ - -

          -​ - - - -``` - * @example ​ ````Set the value of an input box. -```html - - - - - val demo - - - - -​ -
          - - - -
          - -​ - - - -``` - * @example ​ ````Use the function argument to modify the value of an input box. -```html - - - - - val demo - - - -​ -

          Type something and then click or tab out of the input.

          - -​ - - - -``` - * @example ​ ````Set a single select, a multiple select, checkboxes and a radio button . -```html - - - - - val demo - - - - -​ - -​ - -​ -
          - check1 - check2 - radio1 - radio2 -​ - - - -``` - */ - val(value: string | number | string[] | ((this: TElement, index: number, value: string) => string)): this; - /** - * Get the current value of the first element in the set of matched elements. - * - * @see \`{@link https://api.jquery.com/val/ }\` - * @since 1.0 - * @example ​ ````Get the single value from a single select and an array of values from a multiple select and display their values. -```html - - - - - val demo - - - - -​ -

          -​ - -​ - -​ - - - -``` - * @example ​ ````Find the value of an input box. -```html - - - - - val demo - - - - -​ - -

          -​ - - - -``` - * @example ​ ````Set the value of an input box. -```html - - - - - val demo - - - - -​ -
          - - - -
          - -​ - - - -``` - * @example ​ ````Use the function argument to modify the value of an input box. -```html - - - - - val demo - - - -​ -

          Type something and then click or tab out of the input.

          - -​ - - - -``` - * @example ​ ````Set a single select, a multiple select, checkboxes and a radio button . -```html - - - - - val demo - - - - -​ - -​ - -​ -
          - check1 - check2 - radio1 - radio2 -​ - - - -``` - */ - val(): string | number | string[] | undefined; - /** - * Set the CSS width of each element in the set of matched elements. - * - * @param value An integer representing the number of pixels, or an integer along with an optional unit of measure - * appended (as a string). - * A function returning the width to set. Receives the index position of the element in the set and the - * old width as arguments. Within the function, this refers to the current element in the set. - * @see \`{@link https://api.jquery.com/width/ }\` - * @since 1.0 - * @since 1.4.1 - * @example ​ ````Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. -```html - - - - - width demo - - - - -​ - - - -
           
          -

          - Sample paragraph to test width -

          -​ - - - -``` - * @example ​ ````Change the width of each div the first time it is clicked (and change its color). -```html - - - - - width demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - width(value: string | number | ((this: TElement, index: number, value: number) => string | number)): this; - /** - * Get the current computed width for the first element in the set of matched elements. - * - * @see \`{@link https://api.jquery.com/width/ }\` - * @since 1.0 - * @example ​ ````Show various widths. Note the values are from the iframe so might be smaller than you expected. The yellow highlight shows the iframe body. -```html - - - - - width demo - - - - -​ - - - -
           
          -

          - Sample paragraph to test width -

          -​ - - - -``` - * @example ​ ````Change the width of each div the first time it is clicked (and change its color). -```html - - - - - width demo - - - - -​ -
          d
          -
          d
          -
          d
          -
          d
          -
          d
          -​ - - - -``` - */ - width(): number | undefined; - /** - * Wrap an HTML structure around each element in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the - * matched elements. When you pass a jQuery collection containing more than one element, or a selector - * matching more than one element, the first element will be used. - * A callback function returning the HTML content or jQuery object to wrap around the matched elements. - * Receives the index position of the element in the set as an argument. Within the function, this - * refers to the current element in the set. - * @see \`{@link https://api.jquery.com/wrap/ }\` - * @since 1.0 - * @since 1.4 - * @example ​ ````Wrap a new div around all of the paragraphs. -```html - - - - - wrap demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html.> -```html - - - - - wrap demo - - - - -​ -Span Text -What about me? -Another One -​ - - - -``` - * @example ​ ````Wrap a new div around all of the paragraphs. -```html - - - - - wrap demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. -```html - - - - - wrap demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -
          -​ - - - -``` - */ - wrap(wrappingElement: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery)): this; - /** - * Wrap an HTML structure around all elements in the set of matched elements. - * - * @param wrappingElement A selector, element, HTML string, or jQuery object specifying the structure to wrap around the matched elements. - * A callback function returning the HTML content or jQuery object to wrap around all the matched - * elements. Within the function, this refers to the first element in the set. Prior to jQuery 3.0, the - * callback was incorrectly called for every element in the set and received the index position of the - * element in the set as an argument. - * @see \`{@link https://api.jquery.com/wrapAll/ }\` - * @since 1.2 - * @since 1.4 - * @example ​ ````Wrap a new div around all of the paragraphs. -```html - - - - - wrapAll demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Wraps a newly created tree of objects around the spans. Notice anything in between the spans gets left out like the <strong> (red text) in this example. Even the white space between spans is left out. Click View Source to see the original html. -```html - - - - - wrapAll demo - - - - -​ -Span Text -What about me? -Another One -​ - - - -``` - * @example ​ ````Wrap a new div around all of the paragraphs. -```html - - - - - wrapAll demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Wrap a jQuery object double depth div around all of the paragraphs. Notice it doesn't move the object but just clones it to wrap around its target. -```html - - - - - wrapAll demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -
          -​ - - - -``` - */ - wrapAll(wrappingElement: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement) => string | JQuery)): this; - /** - * Wrap an HTML structure around the content of each element in the set of matched elements. - * - * @param wrappingElement An HTML snippet, selector expression, jQuery object, or DOM element specifying the structure to wrap - * around the content of the matched elements. - * A callback function which generates a structure to wrap around the content of the matched elements. - * Receives the index position of the element in the set as an argument. Within the function, this - * refers to the current element in the set. - * @see \`{@link https://api.jquery.com/wrapInner/ }\` - * @since 1.2 - * @since 1.4 - * @example ​ ````Selects all paragraphs and wraps a bold tag around each of its contents. -```html - - - - - wrapInner demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Wraps a newly created tree of objects around the inside of the body. -```html - - - - - wrapInner demo - - - - -​ -Plain old text, or is it? -​ - - - -``` - * @example ​ ````Selects all paragraphs and wraps a bold tag around each of its contents. -```html - - - - - wrapInner demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - * @example ​ ````Selects all paragraphs and wraps a jQuery object around each of its contents. -```html - - - - - wrapInner demo - - - - -​ -

          Hello

          -

          cruel

          -

          World

          -​ - - - -``` - */ - wrapInner(wrappingElement: JQuery.Selector | JQuery.htmlString | Element | JQuery | ((this: TElement, index: number) => string | JQuery | Element)): this; - - [n: number]: TElement; -} - -// region ES5 compatibility -// #region ES5 compatibility - -// tslint:disable-next-line:no-empty-interface -interface Iterable { } - -interface SymbolConstructor { - /** - * A String value that is used in the creation of the default string description of an object. - * Called by the built-in method Object.prototype.toString. - */ - readonly toStringTag: symbol; -} - -declare var Symbol: SymbolConstructor; - -// #endregion - -declare namespace JQuery { - type TypeOrArray = T | T[]; - type Node = Element | Text | Comment | DocumentFragment; - - /** - * A string is designated htmlString in jQuery documentation when it is used to represent one or more - * DOM elements, typically to be created and inserted in the document. When passed as an argument of - * the jQuery() function, the string is identified as HTML if it starts with ) and is parsed - * as such until the final > character. Prior to jQuery 1.9, a string was considered to be HTML if it - * contained anywhere within the string. - */ - type htmlString = string; - /** - * A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most - * cases, the DOM document present in all browsers, but can also be an XML document received via Ajax. - */ - type Selector = string; - - /** - * The PlainObject type is a JavaScript object containing zero or more key-value pairs. The plain - * object is, in other words, an Object object. It is designated "plain" in jQuery documentation to - * distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and - * host objects such as document, all of which have a typeof value of "object." - * - * **Note**: The type declaration of PlainObject is imprecise. It includes host objects and user-defined - * arrays which do not match jQuery's definition. - */ - interface PlainObject { - [key: string]: T; - } - - // region Ajax - // #region Ajax - - interface AjaxSettings extends Ajax.AjaxSettingsBase { - /** - * A string containing the URL to which the request is sent. - */ - url?: string; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, - * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and - * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend - * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless - * of the type of request. - */ - beforeSend?(this: TContext, jqXHR: jqXHR, settings: AjaxSettings): false | void; - } - - interface UrlAjaxSettings extends Ajax.AjaxSettingsBase { - /** - * A string containing the URL to which the request is sent. - */ - url: string; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, - * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and - * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend - * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless - * of the type of request. - */ - beforeSend?(this: TContext, jqXHR: jqXHR, settings: UrlAjaxSettings): false | void; - } - - namespace Ajax { - type SuccessTextStatus = 'success' | 'notmodified' | 'nocontent'; - type ErrorTextStatus = 'timeout' | 'error' | 'abort' | 'parsererror'; - type TextStatus = SuccessTextStatus | ErrorTextStatus; - - interface SuccessCallback { - (this: TContext, data: any, textStatus: SuccessTextStatus, jqXHR: jqXHR): void; - } - - interface ErrorCallback { - (this: TContext, jqXHR: jqXHR, textStatus: ErrorTextStatus, errorThrown: string): void; - } - - interface CompleteCallback { - (this: TContext, jqXHR: jqXHR, textStatus: TextStatus): void; - } - - /** - * @see \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings }\` - */ - interface AjaxSettingsBase { - /** - * A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept - * request header. This header tells the server what kind of response it will accept in return. - */ - accepts?: PlainObject; - /** - * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need - * synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests - * do not support synchronous operation. Note that synchronous requests may temporarily lock the - * browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: - * false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback - * options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). - */ - async?: boolean; - /** - * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, - * XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and - * settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend - * function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless - * of the type of request. - */ - beforeSend?(this: TContext, jqXHR: jqXHR, settings: AjaxSettingsBase): false | void; - /** - * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache - * to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" - * to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a - * POST is made to a URL that has already been requested by a GET. - */ - cache?: boolean; - /** - * A function to be called when the request finishes (after success and error callbacks are executed). - * The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a - * string categorizing the status of the request ("success", "notmodified", "nocontent", "error", - * "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of - * functions. Each function will be called in turn. This is an Ajax Event. - */ - complete?: TypeOrArray>; - /** - * An object of string/regular-expression pairs that determine how jQuery will parse the response, - * given its content type. - */ - contents?: PlainObject; - /** - * When sending data to the server, use this content type. Default is - * "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly - * pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). - * As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C - * XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset - * will not force the browser to change the encoding. Note: For cross-domain requests, setting the - * content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or - * text/plain will trigger the browser to send a preflight OPTIONS request to the server. - */ - contentType?: string | false; - /** - * This object will be the context of all Ajax-related callbacks. By default, the context is an object - * that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). - */ - context?: TContext; - /** - * An object containing dataType-to-dataType converters. Each converter's value is a function that - * returns the transformed value of the response. - */ - converters?: PlainObject<((value: any) => any) | true>; - /** - * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of - * crossDomain to true. This allows, for example, server-side redirection to another domain. - */ - crossDomain?: boolean; - /** - * Data to be sent to the server. It is converted to a query string, if not already a string. It's - * appended to the url for GET-requests. See processData option to prevent this automatic processing. - * Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same - * key based on the value of the traditional setting (described below). - */ - data?: PlainObject | string; - /** - * A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering - * function to sanitize the response. You should return the sanitized data. The function accepts two - * arguments: The raw data returned from the server and the 'dataType' parameter. - */ - dataFilter?(data: string, type: string): any; - /** - * The type of data that you're expecting back from the server. If none is specified, jQuery will try - * to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON - * will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be - * returned as a string). The available types (and the result passed as the first argument to your - * success callback) are: - * - * "xml": Returns a XML document that can be processed via jQuery. - * - * "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. - * - * "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by - * appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to - * true. Note: This will turn POSTs into GETs for remote-domain requests. - * - * "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests - * are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON - * data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of - * jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} - * instead. (See json.org for more information on proper JSON formatting.) - * - * "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to - * specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to - * the URL unless the cache option is set to true. - * - * "text": A plain text string. - * - * multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it - * received in the Content-Type header to what you require. For example, if you want a text response to - * be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it - * received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string - * such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from - * jsonp to text, and then from text to xml. - */ - dataType?: 'xml' | 'html' | 'script' | 'json' | 'jsonp' | 'text' | string; - /** - * A function to be called if the request fails. The function receives three arguments: The jqXHR (in - * jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an - * optional exception object, if one occurred. Possible values for the second argument (besides null) - * are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives - * the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery - * 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: - * This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. - */ - error?: TypeOrArray>; - /** - * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to - * prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to - * control various Ajax Events. - */ - global?: boolean; - /** - * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest - * transport. The header X-Requested-With: XMLHttpRequest is always added, but its default - * XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from - * within the beforeSend function. - */ - headers?: PlainObject; - /** - * Allow the request to be successful only if the response has changed since the last request. This is - * done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery - * 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. - */ - ifModified?: boolean; - /** - * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery - * does not recognize it as such by default. The following protocols are currently recognized as local: - * file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so - * once in the $.ajaxSetup() method. - */ - isLocal?: boolean; - /** - * Override the callback function name in a JSONP request. This value will be used instead of - * 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would - * result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false - * prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for - * transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, - * { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax - * requests, consider setting the jsonp property to false for security reasons. - */ - jsonp?: string | false; - /** - * Specify the callback function name for a JSONP request. This value will be used instead of the - * random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name - * as it'll make it easier to manage the requests and provide callbacks and error handling. You may - * want to specify the callback when you want to enable better browser caching of GET requests. As of - * jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback - * is set to the return value of that function. - */ - jsonpCallback?: string | ((this: TContext) => string); - /** - * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). - */ - method?: string; - /** - * A mime type to override the XHR mime type. - */ - mimeType?: string; - /** - * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - password?: string; - /** - * By default, data passed in to the data option as an object (technically, anything other than a - * string) will be processed and transformed into a query string, fitting to the default content-type - * "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, - * set this option to false. - */ - processData?: boolean; - /** - * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or - * "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. - * Used when the character set on the local page is not the same as the one on the remote script. - */ - scriptCharset?: string; - /** - * An object of numeric HTTP codes and functions to be called when the response has the corresponding - * code. - * - * If the request is successful, the status code functions take the same parameters as the success - * callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. - */ - statusCode?: StatusCodeCallbacks; - /** - * A function to be called if the request succeeds. The function gets passed three arguments: The data - * returned from the server, formatted according to the dataType parameter or the dataFilter callback - * function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, - * XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each - * function will be called in turn. This is an Ajax Event. - */ - success?: TypeOrArray>; - /** - * Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This - * will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the - * $.ajax call is made; if several other requests are in progress and the browser has no connections - * available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and - * below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any - * object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be - * cancelled by a timeout; the script will run even if it arrives after the timeout period. - */ - timeout?: number; - /** - * Set this to true if you wish to use the traditional style of param serialization. - */ - traditional?: boolean; - /** - * An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. - */ - type?: string; - /** - * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. - */ - username?: string; - // ActiveXObject requires "lib": ["scripthost"] which consumers would also require - /** - * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), - * the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or - * enhancements to the factory. - */ - xhr?(): XMLHttpRequest; - /** - * An object of fieldName-fieldValue pairs to set on the native XHR object. - * - * In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS - * requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ - * should you require the use of it. - */ - xhrFields?: XHRFields; - } - - type StatusCodeCallbacks = { - // region Success Status Codes - // #region Success Status Codes - - // jQuery treats 2xx and 304 status codes as a success - - 200?: SuccessCallback; - 201?: SuccessCallback; - 202?: SuccessCallback; - 203?: SuccessCallback; - 204?: SuccessCallback; - 205?: SuccessCallback; - 206?: SuccessCallback; - 207?: SuccessCallback; - 208?: SuccessCallback; - 209?: SuccessCallback; - 210?: SuccessCallback; - 211?: SuccessCallback; - 212?: SuccessCallback; - 213?: SuccessCallback; - 214?: SuccessCallback; - 215?: SuccessCallback; - 216?: SuccessCallback; - 217?: SuccessCallback; - 218?: SuccessCallback; - 219?: SuccessCallback; - 220?: SuccessCallback; - 221?: SuccessCallback; - 222?: SuccessCallback; - 223?: SuccessCallback; - 224?: SuccessCallback; - 225?: SuccessCallback; - 226?: SuccessCallback; - 227?: SuccessCallback; - 228?: SuccessCallback; - 229?: SuccessCallback; - 230?: SuccessCallback; - 231?: SuccessCallback; - 232?: SuccessCallback; - 233?: SuccessCallback; - 234?: SuccessCallback; - 235?: SuccessCallback; - 236?: SuccessCallback; - 237?: SuccessCallback; - 238?: SuccessCallback; - 239?: SuccessCallback; - 240?: SuccessCallback; - 241?: SuccessCallback; - 242?: SuccessCallback; - 243?: SuccessCallback; - 244?: SuccessCallback; - 245?: SuccessCallback; - 246?: SuccessCallback; - 247?: SuccessCallback; - 248?: SuccessCallback; - 249?: SuccessCallback; - 250?: SuccessCallback; - 251?: SuccessCallback; - 252?: SuccessCallback; - 253?: SuccessCallback; - 254?: SuccessCallback; - 255?: SuccessCallback; - 256?: SuccessCallback; - 257?: SuccessCallback; - 258?: SuccessCallback; - 259?: SuccessCallback; - 260?: SuccessCallback; - 261?: SuccessCallback; - 262?: SuccessCallback; - 263?: SuccessCallback; - 264?: SuccessCallback; - 265?: SuccessCallback; - 266?: SuccessCallback; - 267?: SuccessCallback; - 268?: SuccessCallback; - 269?: SuccessCallback; - 270?: SuccessCallback; - 271?: SuccessCallback; - 272?: SuccessCallback; - 273?: SuccessCallback; - 274?: SuccessCallback; - 275?: SuccessCallback; - 276?: SuccessCallback; - 277?: SuccessCallback; - 278?: SuccessCallback; - 279?: SuccessCallback; - 280?: SuccessCallback; - 281?: SuccessCallback; - 282?: SuccessCallback; - 283?: SuccessCallback; - 284?: SuccessCallback; - 285?: SuccessCallback; - 286?: SuccessCallback; - 287?: SuccessCallback; - 288?: SuccessCallback; - 289?: SuccessCallback; - 290?: SuccessCallback; - 291?: SuccessCallback; - 292?: SuccessCallback; - 293?: SuccessCallback; - 294?: SuccessCallback; - 295?: SuccessCallback; - 296?: SuccessCallback; - 297?: SuccessCallback; - 298?: SuccessCallback; - 299?: SuccessCallback; - 304?: SuccessCallback; - - // #endregion - - // region Error Status Codes - // #region Error Status Codes - - 300?: ErrorCallback; - 301?: ErrorCallback; - 302?: ErrorCallback; - 303?: ErrorCallback; - 305?: ErrorCallback; - 306?: ErrorCallback; - 307?: ErrorCallback; - 308?: ErrorCallback; - 309?: ErrorCallback; - 310?: ErrorCallback; - 311?: ErrorCallback; - 312?: ErrorCallback; - 313?: ErrorCallback; - 314?: ErrorCallback; - 315?: ErrorCallback; - 316?: ErrorCallback; - 317?: ErrorCallback; - 318?: ErrorCallback; - 319?: ErrorCallback; - 320?: ErrorCallback; - 321?: ErrorCallback; - 322?: ErrorCallback; - 323?: ErrorCallback; - 324?: ErrorCallback; - 325?: ErrorCallback; - 326?: ErrorCallback; - 327?: ErrorCallback; - 328?: ErrorCallback; - 329?: ErrorCallback; - 330?: ErrorCallback; - 331?: ErrorCallback; - 332?: ErrorCallback; - 333?: ErrorCallback; - 334?: ErrorCallback; - 335?: ErrorCallback; - 336?: ErrorCallback; - 337?: ErrorCallback; - 338?: ErrorCallback; - 339?: ErrorCallback; - 340?: ErrorCallback; - 341?: ErrorCallback; - 342?: ErrorCallback; - 343?: ErrorCallback; - 344?: ErrorCallback; - 345?: ErrorCallback; - 346?: ErrorCallback; - 347?: ErrorCallback; - 348?: ErrorCallback; - 349?: ErrorCallback; - 350?: ErrorCallback; - 351?: ErrorCallback; - 352?: ErrorCallback; - 353?: ErrorCallback; - 354?: ErrorCallback; - 355?: ErrorCallback; - 356?: ErrorCallback; - 357?: ErrorCallback; - 358?: ErrorCallback; - 359?: ErrorCallback; - 360?: ErrorCallback; - 361?: ErrorCallback; - 362?: ErrorCallback; - 363?: ErrorCallback; - 364?: ErrorCallback; - 365?: ErrorCallback; - 366?: ErrorCallback; - 367?: ErrorCallback; - 368?: ErrorCallback; - 369?: ErrorCallback; - 370?: ErrorCallback; - 371?: ErrorCallback; - 372?: ErrorCallback; - 373?: ErrorCallback; - 374?: ErrorCallback; - 375?: ErrorCallback; - 376?: ErrorCallback; - 377?: ErrorCallback; - 378?: ErrorCallback; - 379?: ErrorCallback; - 380?: ErrorCallback; - 381?: ErrorCallback; - 382?: ErrorCallback; - 383?: ErrorCallback; - 384?: ErrorCallback; - 385?: ErrorCallback; - 386?: ErrorCallback; - 387?: ErrorCallback; - 388?: ErrorCallback; - 389?: ErrorCallback; - 390?: ErrorCallback; - 391?: ErrorCallback; - 392?: ErrorCallback; - 393?: ErrorCallback; - 394?: ErrorCallback; - 395?: ErrorCallback; - 396?: ErrorCallback; - 397?: ErrorCallback; - 398?: ErrorCallback; - 399?: ErrorCallback; - 400?: ErrorCallback; - 401?: ErrorCallback; - 402?: ErrorCallback; - 403?: ErrorCallback; - 404?: ErrorCallback; - 405?: ErrorCallback; - 406?: ErrorCallback; - 407?: ErrorCallback; - 408?: ErrorCallback; - 409?: ErrorCallback; - 410?: ErrorCallback; - 411?: ErrorCallback; - 412?: ErrorCallback; - 413?: ErrorCallback; - 414?: ErrorCallback; - 415?: ErrorCallback; - 416?: ErrorCallback; - 417?: ErrorCallback; - 418?: ErrorCallback; - 419?: ErrorCallback; - 420?: ErrorCallback; - 421?: ErrorCallback; - 422?: ErrorCallback; - 423?: ErrorCallback; - 424?: ErrorCallback; - 425?: ErrorCallback; - 426?: ErrorCallback; - 427?: ErrorCallback; - 428?: ErrorCallback; - 429?: ErrorCallback; - 430?: ErrorCallback; - 431?: ErrorCallback; - 432?: ErrorCallback; - 433?: ErrorCallback; - 434?: ErrorCallback; - 435?: ErrorCallback; - 436?: ErrorCallback; - 437?: ErrorCallback; - 438?: ErrorCallback; - 439?: ErrorCallback; - 440?: ErrorCallback; - 441?: ErrorCallback; - 442?: ErrorCallback; - 443?: ErrorCallback; - 444?: ErrorCallback; - 445?: ErrorCallback; - 446?: ErrorCallback; - 447?: ErrorCallback; - 448?: ErrorCallback; - 449?: ErrorCallback; - 450?: ErrorCallback; - 451?: ErrorCallback; - 452?: ErrorCallback; - 453?: ErrorCallback; - 454?: ErrorCallback; - 455?: ErrorCallback; - 456?: ErrorCallback; - 457?: ErrorCallback; - 458?: ErrorCallback; - 459?: ErrorCallback; - 460?: ErrorCallback; - 461?: ErrorCallback; - 462?: ErrorCallback; - 463?: ErrorCallback; - 464?: ErrorCallback; - 465?: ErrorCallback; - 466?: ErrorCallback; - 467?: ErrorCallback; - 468?: ErrorCallback; - 469?: ErrorCallback; - 470?: ErrorCallback; - 471?: ErrorCallback; - 472?: ErrorCallback; - 473?: ErrorCallback; - 474?: ErrorCallback; - 475?: ErrorCallback; - 476?: ErrorCallback; - 477?: ErrorCallback; - 478?: ErrorCallback; - 479?: ErrorCallback; - 480?: ErrorCallback; - 481?: ErrorCallback; - 482?: ErrorCallback; - 483?: ErrorCallback; - 484?: ErrorCallback; - 485?: ErrorCallback; - 486?: ErrorCallback; - 487?: ErrorCallback; - 488?: ErrorCallback; - 489?: ErrorCallback; - 490?: ErrorCallback; - 491?: ErrorCallback; - 492?: ErrorCallback; - 493?: ErrorCallback; - 494?: ErrorCallback; - 495?: ErrorCallback; - 496?: ErrorCallback; - 497?: ErrorCallback; - 498?: ErrorCallback; - 499?: ErrorCallback; - 500?: ErrorCallback; - 501?: ErrorCallback; - 502?: ErrorCallback; - 503?: ErrorCallback; - 504?: ErrorCallback; - 505?: ErrorCallback; - 506?: ErrorCallback; - 507?: ErrorCallback; - 508?: ErrorCallback; - 509?: ErrorCallback; - 510?: ErrorCallback; - 511?: ErrorCallback; - 512?: ErrorCallback; - 513?: ErrorCallback; - 514?: ErrorCallback; - 515?: ErrorCallback; - 516?: ErrorCallback; - 517?: ErrorCallback; - 518?: ErrorCallback; - 519?: ErrorCallback; - 520?: ErrorCallback; - 521?: ErrorCallback; - 522?: ErrorCallback; - 523?: ErrorCallback; - 524?: ErrorCallback; - 525?: ErrorCallback; - 526?: ErrorCallback; - 527?: ErrorCallback; - 528?: ErrorCallback; - 529?: ErrorCallback; - 530?: ErrorCallback; - 531?: ErrorCallback; - 532?: ErrorCallback; - 533?: ErrorCallback; - 534?: ErrorCallback; - 535?: ErrorCallback; - 536?: ErrorCallback; - 537?: ErrorCallback; - 538?: ErrorCallback; - 539?: ErrorCallback; - 540?: ErrorCallback; - 541?: ErrorCallback; - 542?: ErrorCallback; - 543?: ErrorCallback; - 544?: ErrorCallback; - 545?: ErrorCallback; - 546?: ErrorCallback; - 547?: ErrorCallback; - 548?: ErrorCallback; - 549?: ErrorCallback; - 550?: ErrorCallback; - 551?: ErrorCallback; - 552?: ErrorCallback; - 553?: ErrorCallback; - 554?: ErrorCallback; - 555?: ErrorCallback; - 556?: ErrorCallback; - 557?: ErrorCallback; - 558?: ErrorCallback; - 559?: ErrorCallback; - 560?: ErrorCallback; - 561?: ErrorCallback; - 562?: ErrorCallback; - 563?: ErrorCallback; - 564?: ErrorCallback; - 565?: ErrorCallback; - 566?: ErrorCallback; - 567?: ErrorCallback; - 568?: ErrorCallback; - 569?: ErrorCallback; - 570?: ErrorCallback; - 571?: ErrorCallback; - 572?: ErrorCallback; - 573?: ErrorCallback; - 574?: ErrorCallback; - 575?: ErrorCallback; - 576?: ErrorCallback; - 577?: ErrorCallback; - 578?: ErrorCallback; - 579?: ErrorCallback; - 580?: ErrorCallback; - 581?: ErrorCallback; - 582?: ErrorCallback; - 583?: ErrorCallback; - 584?: ErrorCallback; - 585?: ErrorCallback; - 586?: ErrorCallback; - 587?: ErrorCallback; - 588?: ErrorCallback; - 589?: ErrorCallback; - 590?: ErrorCallback; - 591?: ErrorCallback; - 592?: ErrorCallback; - 593?: ErrorCallback; - 594?: ErrorCallback; - 595?: ErrorCallback; - 596?: ErrorCallback; - 597?: ErrorCallback; - 598?: ErrorCallback; - 599?: ErrorCallback; - - // #endregion - } & { - // Status codes not listed require type annotations when defining the callback - [index: number]: SuccessCallback | ErrorCallback; - }; - - // Writable properties on XMLHttpRequest - interface XHRFields extends Partial> { - msCaching?: string; - } - } - - interface Transport { - send(headers: PlainObject, completeCallback: Transport.SuccessCallback): void; - abort(): void; - } - - namespace Transport { - interface SuccessCallback { - (status: number, statusText: Ajax.TextStatus, responses?: PlainObject, headers?: string): void; - } - } - - /** - * @see \`{@link https://api.jquery.com/jquery.ajax/#jqXHR }\` - */ - interface jqXHR extends Promise3, never, - Ajax.SuccessTextStatus, Ajax.ErrorTextStatus, never, - jqXHR, string, never>, - Pick, - Partial> { - responseJSON?: any; - - /** - * Determine the current state of a Deferred object. - * - * @see \`{@link https://api.jquery.com/deferred.state/ }\` - * @since 1.7 - */ - state(): 'pending' | 'resolved' | 'rejected'; - statusCode(map: Ajax.StatusCodeCallbacks): void; - } - - namespace jqXHR { - interface DoneCallback> extends Deferred.Callback3 { } - - interface FailCallback extends Deferred.Callback3 { } - - interface AlwaysCallback> extends Deferred.Callback3 { } - } - - // #endregion - - // region Callbacks - // #region Callbacks - - // tslint:disable-next-line:ban-types - interface Callbacks { - /** - * Add a callback or a collection of callbacks to a callback list. - * - * @param callback A function, or array of functions, that are to be added to the callback list. - * @param callbacks A function, or array of functions, that are to be added to the callback list. - * @see \`{@link https://api.jquery.com/callbacks.add/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.add() to add new callbacks to a callback list: -```html - - - - - callbacks.add demo - - - -​​ - - - -``` - */ - add(callback: TypeOrArray, ...callbacks: Array>): this; - /** - * Disable a callback list from doing anything more. - * - * @see \`{@link https://api.jquery.com/callbacks.disable/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.disable() to disable further calls to a callback list: -```html - - - - - callbacks.disable demo - - - -​​ - - - -``` - */ - disable(): this; - /** - * Determine if the callbacks list has been disabled. - * - * @see \`{@link https://api.jquery.com/callbacks.disabled/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.disabled() to determine if the callbacks list has been disabled: -```html - - - - - callbacks.disabled demo - - - -​​ - - - -``` - */ - disabled(): boolean; - /** - * Remove all of the callbacks from a list. - * - * @see \`{@link https://api.jquery.com/callbacks.empty/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.empty() to empty a list of callbacks: -```html - - - - - callbacks.empty demo - - - -​​ - - - -``` - */ - empty(): this; - /** - * Call all of the callbacks with the given arguments. - * - * @param args The argument or list of arguments to pass back to the callback list. - * @see \`{@link https://api.jquery.com/callbacks.fire/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.fire() to invoke the callbacks in a list with any arguments that have been passed: -```html - - - - - callbacks.fire demo - - - -​​ - - - -``` - */ - fire(...args: any[]): this; - /** - * Call all callbacks in a list with the given context and arguments. - * - * @param context A reference to the context in which the callbacks in the list should be fired. - * @param args An argument, or array of arguments, to pass to the callbacks in the list. - * @see \`{@link https://api.jquery.com/callbacks.fireWith/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.fireWith() to fire a list of callbacks with a specific context and an array of arguments: -```html - - - - - callbacks.fireWith demo - - - -​​ - - - -``` - */ - fireWith(context: object, args?: ArrayLike): this; - /** - * Determine if the callbacks have already been called at least once. - * - * @see \`{@link https://api.jquery.com/callbacks.fired/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.fired() to determine if the callbacks in a list have been called at least once: -```html - - - - - callbacks.fired demo - - - -​​ - - - -``` - */ - fired(): boolean; - /** - * Determine whether or not the list has any callbacks attached. If a callback is provided as an - * argument, determine whether it is in a list. - * - * @param callback The callback to search for. - * @see \`{@link https://api.jquery.com/callbacks.has/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.has() to check if a callback list contains a specific callback: -```html - - - - - callbacks.has demo - - - -​​ - - - -``` - */ - has(callback?: T): boolean; - /** - * Lock a callback list in its current state. - * - * @see \`{@link https://api.jquery.com/callbacks.lock/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.lock() to lock a callback list to avoid further changes being made to the list state: -```html - - - - - callbacks.lock demo - - - -​​ - - - -``` - * @example ​ ````Use callbacks.lock() to lock a callback list with "memory," and then resume using the list: -```html - - - - - callbacks.lock demo - - - -​ -
          -​ - - - -``` - */ - lock(): this; - /** - * Determine if the callbacks list has been locked. - * - * @see \`{@link https://api.jquery.com/callbacks.locked/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.locked() to determine the lock-state of a callback list: -```html - - - - - callbacks.locked demo - - - -​​ - - - -``` - */ - locked(): boolean; - /** - * Remove a callback or a collection of callbacks from a callback list. - * - * @param callbacks A function, or array of functions, that are to be removed from the callback list. - * @see \`{@link https://api.jquery.com/callbacks.remove/ }\` - * @since 1.7 - * @example ​ ````Use callbacks.remove() to remove callbacks from a callback list: -```html - - - - - callbacks.remove demo - - - -​​ - - - -``` - */ - remove(...callbacks: T[]): this; - } - - // #endregion - - // region CSS - // #region CSS - - interface CSSHook { - get(this: this, elem: TElement, computed: any, extra: any): any; - set(this: this, elem: TElement, value: any): void; - } - - // #endregion - - // region Deferred - // #region Deferred - - /** - * Any object that has a then method. - */ - interface Thenable extends PromiseLike { } - - // NOTE: This is a private copy of the global Promise interface. It is used by JQuery.PromiseBase to indicate compatibility with other Promise implementations. - // The global Promise interface cannot be used directly as it may be modified, as in the case of @types/bluebird-global. - /** - * Represents the completion of an asynchronous operation - */ - interface _Promise { - readonly [Symbol.toStringTag]: "Promise"; - /** - * Attaches callbacks for the resolution and/or rejection of the Promise. - * @param onfulfilled The callback to execute when the Promise is resolved. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of which ever callback is executed. - */ - then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, - onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): _Promise; - /** - * Attaches a callback for only the rejection of the Promise. - * @param onrejected The callback to execute when the Promise is rejected. - * @returns A Promise for the completion of the callback. - */ - catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): _Promise; - } - - // Type parameter guide - // -------------------- - // Each type parameter represents a parameter in one of the three possible callbacks. - // - // The first letter indicates which position the parameter is in. - // - // T = A = 1st position - // U = B = 2nd position - // V = C = 3rd position - // S = R = rest position - // - // The second letter indicates which whether it is a [R]esolve, Re[J]ect, or [N]otify value. - // - // The third letter indicates whether the value is returned in the [D]one filter, [F]ail filter, or [P]rogress filter. - - /** - * This object provides a subset of the methods of the Deferred object (then, done, fail, always, - * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. - * - * @see \`{@link https://api.jquery.com/Types/#Promise }\` - */ - interface PromiseBase extends _Promise, PromiseLike { - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - * @see \`{@link https://api.jquery.com/deferred.always/ }\` - * @since 1.6 - * @example ​ ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. -```html - - - - - deferred.always demo - - - -​​ - - - -``` - */ - always(alwaysCallback: TypeOrArray>, - ...alwaysCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - * @see \`{@link https://api.jquery.com/deferred.done/ }\` - * @since 1.5 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. -```html - - - - - deferred.done demo - - - -​​ - - - -``` - * @example ​ ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions: -```html - - - - - deferred.done demo - - - -​ - -

          Ready...

          -​ - - - -``` - */ - done(doneCallback: TypeOrArray>, - ...doneCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - * @see \`{@link https://api.jquery.com/deferred.fail/ }\` - * @since 1.5 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. -```html - - - - - deferred.fail demo - - - -​​ - - - -``` - */ - fail(failCallback: TypeOrArray>, - ...failCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. - * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates - * progress notifications. - * @see \`{@link https://api.jquery.com/deferred.progress/ }\` - * @since 1.7 - */ - progress(progressCallback: TypeOrArray>, - ...progressCallbacks: Array>>): this; - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - * @see \`{@link https://api.jquery.com/deferred.promise/ }\` - * @since 1.5 - * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - * @example ​ ````Use the target argument to promote an existing object to a Promise: -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - */ - promise(target: TTarget): this & TTarget; - /** - * Return a Deferred's Promise object. - * - * @see \`{@link https://api.jquery.com/deferred.promise/ }\` - * @since 1.5 - * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - * @example ​ ````Use the target argument to promote an existing object to a Promise: -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - */ - promise(): this; - /** - * Determine the current state of a Deferred object. - * - * @see \`{@link https://api.jquery.com/deferred.state/ }\` - * @since 1.7 - */ - state(): 'pending' | 'resolved' | 'rejected'; - - // region pipe - // #region pipe - - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: null, - progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link then JQuery.PromiseBase.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase; - - // #endregion - - // region then - // #region then - - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: null, - progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase; - - // #endregion - - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see \`{@link https://api.jquery.com/deferred.catch/ }\` - * @since 3.0 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method. -```html - - - - - deferred.catch demo - - - -​​ - - - -``` - */ - catch( - failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; - } - - /** - * This object provides a subset of the methods of the Deferred object (then, done, fail, always, - * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. - * - * @see \`{@link https://api.jquery.com/Types/#Promise }\` - */ - interface Promise3 extends PromiseBase { } - - /** - * This object provides a subset of the methods of the Deferred object (then, done, fail, always, - * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. - * - * @see \`{@link https://api.jquery.com/Types/#Promise }\` - */ - interface Promise2 extends PromiseBase { } - - /** - * This object provides a subset of the methods of the Deferred object (then, done, fail, always, - * pipe, progress, state and promise) to prevent users from changing the state of the Deferred. - * - * @see \`{@link https://api.jquery.com/Types/#Promise }\` - */ - interface Promise extends PromiseBase { } - - interface DeferredStatic { - // https://jquery.com/upgrade-guide/3.0/#callback-exit - exceptionHook: any; - (beforeStart?: (this: Deferred, deferred: Deferred) => void): Deferred; - } - - interface Deferred { - /** - * Call the progressCallbacks on a Deferred object with the given args. - * - * @param args Optional arguments that are passed to the progressCallbacks. - * @see \`{@link https://api.jquery.com/deferred.notify/ }\` - * @since 1.7 - */ - notify(...args: TN[]): this; - /** - * Call the progressCallbacks on a Deferred object with the given context and args. - * - * @param context Context passed to the progressCallbacks as the this object. - * @param args An optional array of arguments that are passed to the progressCallbacks. - * @see \`{@link https://api.jquery.com/deferred.notifyWith/ }\` - * @since 1.7 - */ - notifyWith(context: object, args?: ArrayLike): this; - /** - * Reject a Deferred object and call any failCallbacks with the given args. - * - * @param args Optional arguments that are passed to the failCallbacks. - * @see \`{@link https://api.jquery.com/deferred.reject/ }\` - * @since 1.5 - */ - reject(...args: TJ[]): this; - /** - * Reject a Deferred object and call any failCallbacks with the given context and args. - * - * @param context Context passed to the failCallbacks as the this object. - * @param args An optional array of arguments that are passed to the failCallbacks. - * @see \`{@link https://api.jquery.com/deferred.rejectWith/ }\` - * @since 1.5 - */ - rejectWith(context: object, args?: ArrayLike): this; - /** - * Resolve a Deferred object and call any doneCallbacks with the given args. - * - * @param args Optional arguments that are passed to the doneCallbacks. - * @see \`{@link https://api.jquery.com/deferred.resolve/ }\` - * @since 1.5 - */ - resolve(...args: TR[]): this; - /** - * Resolve a Deferred object and call any doneCallbacks with the given context and args. - * - * @param context Context passed to the doneCallbacks as the this object. - * @param args An optional array of arguments that are passed to the doneCallbacks. - * @see \`{@link https://api.jquery.com/deferred.resolveWith/ }\` - * @since 1.5 - */ - resolveWith(context: object, args?: ArrayLike): this; - - /** - * Add handlers to be called when the Deferred object is either resolved or rejected. - * - * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. - * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. - * @see \`{@link https://api.jquery.com/deferred.always/ }\` - * @since 1.6 - * @example ​ ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. -```html - - - - - deferred.always demo - - - -​​ - - - -``` - */ - always(alwaysCallback: TypeOrArray>, - ...alwaysCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is resolved. - * - * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. - * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. - * @see \`{@link https://api.jquery.com/deferred.done/ }\` - * @since 1.5 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. -```html - - - - - deferred.done demo - - - -​​ - - - -``` - * @example ​ ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions: -```html - - - - - deferred.done demo - - - -​ - -

          Ready...

          -​ - - - -``` - */ - done(doneCallback: TypeOrArray>, - ...doneCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. - * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. - * @see \`{@link https://api.jquery.com/deferred.fail/ }\` - * @since 1.5 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. -```html - - - - - deferred.fail demo - - - -​​ - - - -``` - */ - fail(failCallback: TypeOrArray>, - ...failCallbacks: Array>>): this; - /** - * Add handlers to be called when the Deferred object generates progress notifications. - * - * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. - * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates - * progress notifications. - * @see \`{@link https://api.jquery.com/deferred.progress/ }\` - * @since 1.7 - */ - progress(progressCallback: TypeOrArray>, - ...progressCallbacks: Array>>): this; - /** - * Return a Deferred's Promise object. - * - * @param target Object onto which the promise methods have to be attached - * @see \`{@link https://api.jquery.com/deferred.promise/ }\` - * @since 1.5 - * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - * @example ​ ````Use the target argument to promote an existing object to a Promise: -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - */ - promise(target: TTarget): Promise & TTarget; - /** - * Return a Deferred's Promise object. - * - * @see \`{@link https://api.jquery.com/deferred.promise/ }\` - * @since 1.5 - * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - * @example ​ ````Use the target argument to promote an existing object to a Promise: -```html - - - - - deferred.promise demo - - - -​​ - - - -``` - */ - promise(): Promise; - /** - * Determine the current state of a Deferred object. - * - * @see \`{@link https://api.jquery.com/deferred.state/ }\` - * @since 1.7 - */ - state(): 'pending' | 'resolved' | 'rejected'; - - // region pipe - // #region pipe - - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: null, - progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, - progressFilter?: null): PromiseBase; - /** - * Utility method to filter and/or chain Deferreds. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` - * @since 1.6 - * @since 1.7 - * @deprecated Deprecated since 1.8. Use \`{@link JQuery.Deferred.then }\`. - * @example ​ ````Filter resolve value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.pipe demo - - - -​​ - - - -``` - */ - pipe( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase; - - // #endregion - - // region then - // #region then - - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: null, - progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter A function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: null, - progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: null, - failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, - progressFilter?: null): PromiseBase; - /** - * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. - * - * @param doneFilter An optional function that is called when the Deferred is resolved. - * @param failFilter An optional function that is called when the Deferred is rejected. - * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. - * @see \`{@link https://api.jquery.com/deferred.then/ }\` - * @since 1.8 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Filter the resolve value: -```html - - - - - deferred.then demo - - - -​ - -

          -​ - - - -``` - * @example ​ ````Filter reject value: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - * @example ​ ````Chain tasks: -```html - - - - - deferred.then demo - - - -​​ - - - -``` - */ - then( - doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, - failFilter?: null, - progressFilter?: null): PromiseBase; - - // #endregion - - /** - * Add handlers to be called when the Deferred object is rejected. - * - * @param failFilter A function that is called when the Deferred is rejected. - * @see \`{@link https://api.jquery.com/deferred.catch/ }\` - * @since 3.0 - * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method. -```html - - - - - deferred.catch demo - - - -​​ - - - -``` - */ - catch( - failFilter?: ((...t: TJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; - } - - namespace Deferred { - interface CallbackBase { - (t: T, u: U, v: V, ...r: R[]): void; - } - - interface Callback3 extends CallbackBase { } - - interface Callback { - (...args: T[]): void; - } - - /** - * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. - */ - interface DoneCallback extends Callback { } - - /** - * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. - */ - interface FailCallback extends Callback { } - - /** - * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. - */ - interface AlwaysCallback extends Callback { } - - /** - * @deprecated Use \`{@link JQuery.Deferred.Callback }\`. - */ - interface ProgressCallback extends Callback { } - } - - // #endregion - - // region Effects - // #region Effects - - type Duration = number | 'fast' | 'slow'; - // TODO: Is the first element always a string or is that specific to the 'fx' queue? - type Queue = { 0: string; } & Array>; - - interface QueueFunction { - (this: TElement, next: () => void): void; - } - - /** - * @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\` - */ - interface EffectsOptions { - /** - * A function to be called when the animation on an element completes or stops without completing (its - * Promise object is either resolved or rejected). - */ - always?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A function that is called once the animation on an element is complete. - */ - complete?(this: TElement): void; - /** - * A function to be called when the animation on an element completes (its Promise object is resolved). - */ - done?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A string or number determining how long the animation will run. - */ - duration?: Duration; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to be called when the animation on an element fails to complete (its Promise object is rejected). - */ - fail?(this: TElement, animation: Promise, jumpedToEnd: boolean): void; - /** - * A function to be called after each step of the animation, only once per animated element regardless - * of the number of animated properties. - */ - progress?(this: TElement, animation: Promise, progress: number, remainingMs: number): void; - /** - * A Boolean indicating whether to place the animation in the effects queue. If false, the animation - * will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case - * the animation is added to the queue represented by that string. When a custom queue name is used the - * animation does not automatically start; you must call .dequeue("queuename") to start it. - */ - queue?: boolean | string; - /** - * An object containing one or more of the CSS properties defined by the properties argument and their - * corresponding easing functions. - */ - specialEasing?: PlainObject; - /** - * A function to call when the animation on an element begins. - */ - start?(this: TElement, animation: Promise): void; - /** - * A function to be called for each animated property of each animated element. This function provides - * an opportunity to modify the Tween object to change the value of the property before it is set. - */ - step?(this: TElement, now: number, tween: Tween): void; - } - - interface SpeedSettings { - /** - * A string or number determining how long the animation will run. - */ - duration?: Duration; - /** - * A string indicating which easing function to use for the transition. - */ - easing?: string; - /** - * A function to call once the animation is complete. - */ - complete?(this: TElement): void; - } - - // This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery. - // Undocumented - // https://github.com/jquery/api.jquery.com/issues/391 - // https://github.com/jquery/api.jquery.com/issues/61 - interface Tween { - easing: string; - elem: TElement; - end: number; - now: number; - options: EffectsOptions; - pos: number; - prop: string; - start: number; - unit: string; - } - - interface AnimationHook { - (fx: Tween): void; - } - - // #endregion - - // region Events - // #region Events - - // region Event - // #region Event - - // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. - - // Static members - 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; - } - - // Instance members - interface Event { - /** - * 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; - /** - * 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 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; - /** - * 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/ }\` - * @since 1.2.6 - * @example ​ ````Display the time since the click handler last executed. -```html - - - - - event.timeStamp demo - - - - -​ -
          Click.
          -​ - - - -``` - */ - timeStamp: number; - /** - * Describes the nature of the event. - * - * @see \`{@link https://api.jquery.com/event.type/ }\` - * @since 1.0 - * @example ​ ````On all anchor clicks, alert the event type. -```html - - - - - event.type demo - - - -​​ - - - -``` - */ - 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/ }\` - * @since 1.3 - * @example ​ ````Checks whether event.preventDefault() was called. -```html - - - - - event.isDefaultPrevented demo - - - -​​ - - - -``` - */ - isDefaultPrevented(): boolean; - /** - * Returns whether event.stopImmediatePropagation() was ever called on this event object. - * - * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` - * @since 1.3 - * @example ​ ````Checks whether event.stopImmediatePropagation() was called. -```html - - - - - event.isImmediatePropagationStopped demo - - - -​ - -
          - ​ - - - -``` - */ - isImmediatePropagationStopped(): boolean; - /** - * Returns whether event.stopPropagation() was ever called on this event object. - * - * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` - * @since 1.3 - * @example ​ ````Checks whether event.stopPropagation() was called -```html - - - - - event.isPropagationStopped demo - - - -​ - -
          - ​ - - - -``` - */ - isPropagationStopped(): boolean; - /** - * If this method is called, the default action of the event will not be triggered. - * - * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` - * @since 1.0 - * @example ​ ````Cancel the default action (navigation) of the click. -```html - - - - - event.preventDefault demo - - - -​ -default click action is prevented -
          -​ - - - -``` - */ - preventDefault(): void; - /** - * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. - * - * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` - * @since 1.3 - * @example ​ ````Prevents other event handlers from being called. -```html - - - - - event.stopImmediatePropagation demo - - - - -​ -

          paragraph

          -
          division
          -​ - - - -``` - */ - stopImmediatePropagation(): void; - /** - * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. - * - * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` - * @since 1.0 - * @example ​ ````Kill the bubbling on the click event. -```html - - - - - event.stopPropagation demo - - - -​​ - - - -``` - */ - stopPropagation(): void; - } - - // Generic members - interface Event extends Partial> { - /** - * The current DOM element within the event bubbling phase. - * - * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` - * @since 1.3 - * @example ​ ````Alert that currentTarget matches the `this` keyword. -```html - - - - - event.currentTarget demo - - - -​​ - - - -``` - */ - 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; - /** - * The element where the currently-called jQuery event handler was attached. - * - * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` - * @since 1.7 - * @example ​ ````When a button in any box class is clicked, change the box's background color to red. -```html - - - - - event.delegateTarget demo - - - -​​ - - - -``` - */ - 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. -```html - - - - - event.relatedTarget demo - - - -​​ - - - -``` - */ - relatedTarget: TTarget | null; - /** - * The DOM element that initiated the event. - * - * @see \`{@link https://api.jquery.com/event.target/ }\` - * @since 1.0 - * @example ​ ````Display the tag's name on click -```html - - - - - event.target demo - - - - -​ -
          -
          -

          - click -

          -
          -​ - - - -``` - * @example ​ ````Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children. -```html - - - - - event.target demo - - - -​ -
            -
          • item 1 -
              -
            • sub item 1-a
            • -
            • sub item 1-b
            • -
            -
          • -
          • item 2 -
              -
            • sub item 2-a
            • -
            • sub item 2-b
            • -
            -
          • -
          -​ - - - -``` - */ - target: TTarget; - } - - interface EventLike { - type: string; - } - - // #endregion - - interface EventHandler extends EventHandlerBase> { } - - interface EventHandlerBase { - // Extra parameters can be passed from trigger() - (this: TContext, t: T, ...args: any[]): void | false | any; - } - - // #endregion - - interface NameValuePair { - name: string; - value: string; - } - - interface Coordinates { - left: number; - top: number; - } - - // Workaround for TypeScript 2.3 which does not have support for weak types handling. - type CoordinatesPartial = - Pick | - Pick | - { [key: string]: never; }; - - interface ValHook { - get?(elem: TElement): any; - set?(elem: TElement, value: any): any; - } -} - -// region Legacy types -// #region Legacy types - -// tslint:disable-next-line:no-empty-interface -interface JQueryCallback extends JQuery.Callbacks { } -interface JQueryDeferred extends JQuery.Deferred { } -// tslint:disable-next-line:no-empty-interface -interface JQueryEventConstructor extends JQuery.EventStatic { } -interface JQueryDeferred extends JQuery.Deferred { } -// tslint:disable-next-line:no-empty-interface -interface JQueryAjaxSettings extends JQuery.AjaxSettings { } -interface JQueryAnimationOptions extends JQuery.EffectsOptions { } -// tslint:disable-next-line:no-empty-interface -interface JQueryCoordinates extends JQuery.Coordinates { } -interface JQueryGenericPromise extends JQuery.Thenable { } -// tslint:disable-next-line:no-empty-interface -interface JQueryXHR extends JQuery.jqXHR { } -interface JQueryPromise extends JQuery.Promise { } -// tslint:disable-next-line:no-empty-interface -interface JQuerySerializeArrayElement extends JQuery.NameValuePair { } - -/** - * @deprecated Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. - */ -// tslint:disable-next-line:no-empty-interface -interface JQuerySupport extends JQuery.PlainObject { } - -// Legacy types that are not represented in the current type definitions are marked deprecated. - -/** - * @deprecated Use \`{@link JQuery.Deferred.Callback }\` or \`{@link JQuery.Deferred.CallbackBase }\`. - */ -interface JQueryPromiseCallback { - (value?: T, ...args: any[]): void; -} -/** - * @deprecated Use \`{@link JQueryStatic.param JQueryStatic['param']}\`. - */ -interface JQueryParam { - /** - * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. - * - * @param obj An array or object to serialize. - * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. - */ - (obj: any, traditional?: boolean): string; -} -/** - * @deprecated Use \`{@link JQuery.Event }\`. - */ -interface BaseJQueryEventObject extends Event { - /** - * The current DOM element within the event bubbling phase. - * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` - */ - currentTarget: Element; - /** - * 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/ }\` - */ - data: any; - /** - * The element where the currently-called jQuery event handler was attached. - * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` - */ - delegateTarget: Element; - /** - * Returns whether event.preventDefault() was ever called on this event object. - * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` - */ - isDefaultPrevented(): boolean; - /** - * Returns whether event.stopImmediatePropagation() was ever called on this event object. - * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` - */ - isImmediatePropagationStopped(): boolean; - /** - * Returns whether event.stopPropagation() was ever called on this event object. - * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` - */ - isPropagationStopped(): boolean; - /** - * The namespace specified when the event was triggered. - * @see \`{@link https://api.jquery.com/event.namespace/ }\` - */ - namespace: string; - /** - * The browser's original Event object. - * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` - */ - originalEvent: Event; - /** - * If this method is called, the default action of the event will not be triggered. - * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` - */ - preventDefault(): any; - /** - * The other DOM element involved in the event, if any. - * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` - */ - relatedTarget: Element; - /** - * 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/ }\` - */ - result: any; - /** - * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. - * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` - */ - stopImmediatePropagation(): void; - /** - * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. - * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` - */ - stopPropagation(): void; - /** - * The DOM element that initiated the event. - * @see \`{@link https://api.jquery.com/event.target/ }\` - */ - target: Element; - /** - * The mouse position relative to the left edge of the document. - * @see \`{@link https://api.jquery.com/event.pageX/ }\` - */ - pageX: number; - /** - * The mouse position relative to the top edge of the document. - * @see \`{@link https://api.jquery.com/event.pageY/ }\` - */ - pageY: number; - /** - * For key or mouse events, this property indicates the specific key or button that was pressed. - * @see \`{@link https://api.jquery.com/event.which/ }\` - */ - which: number; - /** - * Indicates whether the META key was pressed when the event fired. - * @see \`{@link https://api.jquery.com/event.metaKey/ }\` - */ - metaKey: boolean; -} -/** - * @deprecated Use \`{@link JQuery.Event }\`. - */ -interface JQueryInputEventObject extends BaseJQueryEventObject { - altKey: boolean; - ctrlKey: boolean; - metaKey: boolean; - shiftKey: boolean; -} -/** - * @deprecated Use \`{@link JQuery.Event }\`. - */ -interface JQueryMouseEventObject extends JQueryInputEventObject { - button: number; - clientX: number; - clientY: number; - offsetX: number; - offsetY: number; - pageX: number; - pageY: number; - screenX: number; - screenY: number; -} -/** - * @deprecated Use \`{@link JQuery.Event }\`. - */ -interface JQueryKeyEventObject extends JQueryInputEventObject { - char: any; - charCode: number; - key: any; - keyCode: number; -} -/** - * @deprecated Use \`{@link JQuery.Event }\`. - */ -interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } -/** - * @deprecated - */ -interface JQueryPromiseOperator { - (callback1: JQuery.TypeOrArray>, - ...callbacksN: Array>>): JQueryPromise; -} -/** - * @deprecated Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. - */ -interface JQueryEasingFunction { - (percent: number): number; -} -/** - * @deprecated Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. - */ -interface JQueryEasingFunctions { - [name: string]: JQueryEasingFunction; - linear: JQueryEasingFunction; - swing: JQueryEasingFunction; -} - -// #endregion +export = jQuery; diff --git a/types/jquery/jquery-tests.ts b/types/jquery/jquery-tests.ts index 4d7c10b153..b1f63f3ecf 100644 --- a/types/jquery/jquery-tests.ts +++ b/types/jquery/jquery-tests.ts @@ -3,6 +3,91 @@ function JQueryStatic() { const jq: JQueryStatic = $; } + function ajaxSettings() { + // $ExpectType AjaxSettings + $.ajaxSettings; + } + + function Animation() { + // $ExpectType AnimationStatic + $.Animation; + } + + function Callbacks() { + // $ExpectType CallbacksStatic + $.Callbacks; + } + + function cssHooks() { + // $ExpectType CSSHooks + $.cssHooks; + } + + function cssNumber() { + // $ExpectType PlainObject + $.cssNumber; + } + + function Deferred() { + // $ExpectType DeferredStatic + $.Deferred; + } + + function easing() { + // $ExpectType Easings + $.easing; + } + + function Event() { + // $ExpectType EventStatic + $.Event; + } + + function event() { + // $ExpectType EventExtensions + $.event; + } + + function expr() { + // $ExpectType Selectors + $.expr; + } + + function fn() { + // $ExpectType JQuery + $.fn; + } + + function fx() { + // $ExpectType Effects + $.fx; + } + + function ready() { + // $ExpectType Thenable + $.ready; + } + + function support() { + // $ExpectType PlainObject + $.support; + } + + function timers() { + // $ExpectType TickFunction[] + $.timers; + } + + function Tween() { + // $ExpectType TweenStatic + $.Tween; + } + + function valHooks() { + // $ExpectType ValHooks + $.valHooks; + } + function call_signature() { // $ExpectType JQuery $('

          ', new Document()); @@ -111,123 +196,6 @@ function JQueryStatic() { } } - function ajaxSettings() { - // $ExpectType AjaxSettings - $.ajaxSettings; - } - - function Event() { - // $ExpectType EventStatic - $.Event; - } - - function cssHooks() { - // $ExpectType PlainObject> - $.cssHooks; - } - - function cssNumber() { - // $ExpectType PlainObject - $.cssNumber; - } - - function fn() { - // $ExpectType JQuery - $.fn; - } - - function fx() { - function interval() { - // $ExpectType number - $.fx.interval; - } - - function off() { - // $ExpectType boolean - $.fx.off; - } - - function step() { - // $ExpectType PlainObject> - $.fx.step; - } - } - - function ready() { - // $ExpectType Thenable - $.ready; - } - - function support() { - // $ExpectType PlainObject - $.support; - } - - function valHooks() { - // $ExpectType PlainObject> - $.valHooks; - } - - function Callbacks() { - // $ExpectType Callbacks - $.Callbacks('once'); - - // $ExpectType Callbacks - $.Callbacks(); - } - - function Deferred() { - function call_signature() { - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - - // $ExpectType Deferred - $.Deferred(function(deferred) { - // $ExpectType Deferred - this; - // $ExpectType Deferred - deferred; - }); - - // $ExpectType Deferred - $.Deferred(); - } - - function exceptionHook() { - $.Deferred.exceptionHook = undefined; - } - } - function ajax() { // $ExpectType jqXHR $.ajax('url', { @@ -325,6 +293,13 @@ function JQueryStatic() { $.camelCase('foo-bar'); } + function cleanData() { + const elems: ArrayLike = {} as any; + + // $ExpectType void + $.cleanData(elems); + } + function contains() { // $ExpectType boolean $.contains(new HTMLElement(), new HTMLElement()); @@ -336,21 +311,23 @@ function JQueryStatic() { } function data() { + const element: Element | Document | Window | JQuery.PlainObject = {} as any; + const value: string | undefined = {} as any; // $ExpectError - $.data(new HTMLElement(), 'myKey', value); + $.data(element, 'myKey', value); // $ExpectType "myValue" - $.data(new HTMLElement(), 'myKey', 'myValue'); + $.data(element, 'myKey', 'myValue'); // $ExpectType any - $.data(new HTMLElement(), 'myKey', undefined); + $.data(element, 'myKey', undefined); // $ExpectType any - $.data(new HTMLElement(), 'myKey'); + $.data(element, 'myKey'); // $ExpectType any - $.data(new HTMLElement()); + $.data(element); } function dequeue() { @@ -486,6 +463,9 @@ function JQueryStatic() { // $ExpectType { name: string; } & EventTarget $.extend(true, t, u); + // $ExpectType JQueryStatic & { name: string; } + $.extend(true, t); + // $ExpectType any $.extend(true, t, u, v, w, x, y, z, a); @@ -507,6 +487,9 @@ function JQueryStatic() { // $ExpectType { name: string; } & EventTarget $.extend(t, u); + // $ExpectType JQueryStatic & { name: string; } + $.extend(t); + // $ExpectType any $.extend(t, u, v, w, x, y, z, a); } @@ -628,6 +611,11 @@ function JQueryStatic() { // $ExpectType jqXHR jqXHR; }); + + // $ExpectType jqXHR + $.getScript({ + url: 'url', + }); } function globalEval() { @@ -658,8 +646,10 @@ function JQueryStatic() { } function hasData() { + const element: Element | Document | Window | JQuery.PlainObject = {} as any; + // $ExpectType boolean - $.hasData(new HTMLElement()); + $.hasData(element); } function holdReady() { @@ -903,6 +893,13 @@ function JQueryStatic() { $.noConflict(); } + function nodeName() { + const node: Node = undefined!; + + // $ExpectType boolean + $.nodeName(node, 'name'); + } + function noop() { // $ExpectType undefined $.noop(); @@ -1042,23 +1039,25 @@ function JQueryStatic() { } function proxy() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - interface I3 { kind: 'I3'; } - interface I4 { kind: 'I4'; } - interface I5 { kind: 'I5'; } - interface I6 { kind: 'I6'; } - interface I7 { kind: 'I7'; } - interface I8 { kind: 'I8'; } + interface JContext { kind: 'JContext'; } + interface J1 { kind: 'J1'; } + interface J2 { kind: 'J2'; } + interface J3 { kind: 'J3'; } + interface J4 { kind: 'J4'; } + interface J5 { kind: 'J5'; } + interface J6 { kind: 'J6'; } + interface J7 { kind: 'J7'; } + interface J8 { kind: 'J8'; } - const a: I8 = {} as any; - const b: I7 = {} as any; - const c: I6 = {} as any; - const d: I5 = {} as any; - const e: I4 = {} as any; - const f: I3 = {} as any; - const g: I2 = {} as any; - const h: I2 = {} as any; + const context: JContext = {} as any; + const a: J8 = {} as any; + const b: J7 = {} as any; + const c: J6 = {} as any; + const d: J5 = {} as any; + const e: J4 = {} as any; + const f: J3 = {} as any; + const g: J2 = {} as any; + const h: J1 = {} as any; type A = typeof a; type B = typeof b; @@ -1067,9 +1066,8 @@ function JQueryStatic() { type E = typeof e; type F = typeof f; type G = typeof g; - type H = typeof h; - // (fn, null) + // (funсtion, null) { // $ExpectType () => void $.proxy((a, b, c, d, e, f, g) => { }, null, a, b, c, d, e, f, g); @@ -1095,203 +1093,203 @@ function JQueryStatic() { // $ExpectType () => void $.proxy(() => { }, null); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, null, a, b, c, d); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1) => { }, null, a, b, c, d); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, t: I1) => { }, null, a, b, c); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, t: J1) => { }, null, a, b, c); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, t: I1) => { }, null, a, b); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, t: J1) => { }, null, a, b); - // $ExpectType (t: I1) => void - $.proxy((a: A, t: I1) => { }, null, a); + // $ExpectType (t: J1) => void + $.proxy((a: A, t: J1) => { }, null, a); - // $ExpectType (t: I1) => void - $.proxy((t: I1) => { }, null); + // $ExpectType (t: J1) => void + $.proxy((t: J1) => { }, null); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, t: I1, u: I2) => { }, null, a, b); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, t: J1, u: J2) => { }, null, a, b); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, t: I1, u: I2) => { }, null, a); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, t: J1, u: J2) => { }, null, a); - // $ExpectType (t: I1, u: I2) => void - $.proxy((t: I1, u: I2) => { }, null); + // $ExpectType (t: J1, u: J2) => void + $.proxy((t: J1, u: J2) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, t: I1, u: I2, v: I3) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, t: J1, u: J2, v: J3) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((t: I1, u: I2, v: I3) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((t: J1, u: J2, v: J3) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((t: J1, u: J2, v: J3, w: J4) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, null); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null); // $ExpectType (...args: any[]) => void - $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, null, a, b, c, d, e, f, g, h); + $.proxy((a, b, c, d, e, f, g, h, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, null, a, b, c, d, e, f, g, h); } - // (fn, undefined) + // (funсtion, undefined) { // $ExpectType () => void $.proxy((a, b, c, d, e, f, g) => { }, undefined, a, b, c, d, e, f, g); @@ -1317,428 +1315,647 @@ function JQueryStatic() { // $ExpectType () => void $.proxy(() => { }, undefined); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, c: C, t: I1) => { }, undefined, a, b, c); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, c: C, t: J1) => { }, undefined, a, b, c); - // $ExpectType (t: I1) => void - $.proxy((a: A, b: B, t: I1) => { }, undefined, a, b); + // $ExpectType (t: J1) => void + $.proxy((a: A, b: B, t: J1) => { }, undefined, a, b); - // $ExpectType (t: I1) => void - $.proxy((a: A, t: I1) => { }, undefined, a); + // $ExpectType (t: J1) => void + $.proxy((a: A, t: J1) => { }, undefined, a); - // $ExpectType (t: I1) => void - $.proxy((t: I1) => { }, undefined); + // $ExpectType (t: J1) => void + $.proxy((t: J1) => { }, undefined); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, b: B, t: I1, u: I2) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, b: B, t: J1, u: J2) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2) => void - $.proxy((a: A, t: I1, u: I2) => { }, undefined, a); + // $ExpectType (t: J1, u: J2) => void + $.proxy((a: A, t: J1, u: J2) => { }, undefined, a); - // $ExpectType (t: I1, u: I2) => void - $.proxy((t: I1, u: I2) => { }, undefined); + // $ExpectType (t: J1, u: J2) => void + $.proxy((t: J1, u: J2) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((a: A, t: I1, u: I2, v: I3) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((a: A, t: J1, u: J2, v: J3) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3) => void - $.proxy((t: I1, u: I2, v: I3) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy((t: J1, u: J2, v: J3) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4) => void - $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy((t: J1, u: J2, v: J3, w: J4) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) => { }, undefined); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f, g); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c, d, e, f, g); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c, d, e, f); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c, d, e); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c, d); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a); - // $ExpectType (t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined); + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy((t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined); // $ExpectType (...args: any[]) => void - $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, undefined, a, b, c, d, e, f, g, h); + $.proxy((a, b, c, d, e, f, g, h, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) => { }, undefined, a, b, c, d, e, f, g, h); } - // (fn, context) + // (funсtion, context) { - // $ExpectType (this: {}) => void - $.proxy((a, b, c, d, e, f, g) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}) => void - $.proxy((a, b, c, d, e, f) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}) => void - $.proxy((a, b, c, d, e) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}) => void - $.proxy((a, b, c, d) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}) => void - $.proxy((a, b, c) => { }, {}, a, b, c); - - // $ExpectType (this: {}) => void - $.proxy((a, b) => { }, {}, a, b); - - // $ExpectType (this: {}) => void - $.proxy((a) => { }, {}, a); - - // $ExpectType (this: {}) => void - $.proxy(() => { }, {}); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, c: C, t: I1) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, b: B, t: I1) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((a: A, t: I1) => { }, {}, a); - - // $ExpectType (this: {}, t: I1) => void - $.proxy((t: I1) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, b: B, t: I1, u: I2) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((a: A, t: I1, u: I2) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2) => void - $.proxy((t: I1, u: I2) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((a: A, t: I1, u: I2, v: I3) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3) => void - $.proxy((t: I1, u: I2, v: I3) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4) => void - $.proxy((t: I1, u: I2, v: I3, w: I4) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7) => { }, {}); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f, g); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, f: F, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, e: E, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, d: D, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, c: C, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, b: B, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((a: A, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a); - - // $ExpectType (this: {}, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, ...args: any[]) => void - $.proxy((t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}); - - // $ExpectType (this: {}, ...args: any[]) => void - $.proxy((a, b, c, d, e, f, g, h, t: I1, u: I2, v: I3, w: I4, x: I5, y: I6, z: I7, _: I8) => { }, {}, a, b, c, d, e, f, g, h); + // $ExpectType () => void + $.proxy(function(a, b, c, d, e, f, g) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType () => void + $.proxy(function(a, b, c, d, e, f) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType () => void + $.proxy(function(a, b, c, d, e) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType () => void + $.proxy(function(a, b, c, d) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType () => void + $.proxy(function(a, b, c) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType () => void + $.proxy(function(a, b) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType () => void + $.proxy(function(a) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType () => void + $.proxy(function() { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, c: C, t: J1) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, b: B, t: J1) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1) => void + $.proxy(function(a: A, t: J1) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1) => void + $.proxy(function(t: J1) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, b: B, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(a: A, t: J1, u: J2) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2) => void + $.proxy(function(t: J1, u: J2) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3) => void + $.proxy(function(t: J1, u: J2, v: J3) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4) => void + $.proxy(function(t: J1, u: J2, v: J3, w: J4) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5) => void + $.proxy(function(t: J1, u: J2, v: J3, w: J4, x: J5) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) => void + $.proxy(function(t: J1, u: J2, v: J3, w: J4, x: J5, y: J6) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, g: G, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, f: F, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, e: E, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, d: D, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c, d); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, c: C, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, b: B, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(a: A, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a); + + // $ExpectType (t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, ...args: any[]) => void + $.proxy(function(t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context); + + // $ExpectType (...args: any[]) => void + $.proxy(function(a, b, c, d, e, f, g, h, t: J1, u: J2, v: J3, w: J4, x: J5, y: J6, z: J7, _: J8) { + // $ExpectType JContext + this; + }, context, a, b, c, d, e, f, g, h); } - // $ExpectType (this: { myFunc: () => undefined; }, ...args: any[]) => any + // $ExpectType (...args: any[]) => any $.proxy({ myFunc: $.noop }, 'myFunc', 1, 2); - // $ExpectType (this: { myFunc: () => undefined; }, ...args: any[]) => any + // $ExpectType (...args: any[]) => any $.proxy({ myFunc: $.noop }, 'myFunc'); } @@ -1773,11 +1990,13 @@ function JQueryStatic() { } function removeData() { - // $ExpectType void - $.removeData(new HTMLElement(), 'test1'); + const element: Element | Document | Window | JQuery.PlainObject = {} as any; // $ExpectType void - $.removeData(new HTMLElement()); + $.removeData(element, 'test1'); + + // $ExpectType void + $.removeData(element); } function speed() { @@ -1815,6 +2034,10 @@ function JQueryStatic() { } }); + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + $.speed(false); + // $ExpectType EffectsOptions $.speed(); } @@ -1840,15 +2063,15 @@ function JQueryStatic() { } function when() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - interface I3 { kind: 'I3'; } - interface I4 { kind: 'I4'; } - interface I5 { kind: 'I5'; } - interface I6 { kind: 'I6'; } - interface I7 { kind: 'I7'; } - interface I8 { kind: 'I8'; } - interface I9 { kind: 'I9'; } + interface J1 { kind: 'J1'; } + interface J2 { kind: 'J2'; } + interface J3 { kind: 'J3'; } + interface J4 { kind: 'J4'; } + interface J5 { kind: 'J5'; } + interface J6 { kind: 'J6'; } + interface J7 { kind: 'J7'; } + interface J8 { kind: 'J8'; } + interface J9 { kind: 'J9'; } function Promise3() { const t = $.ajax() as JQuery.jqXHR; @@ -1998,22 +2221,22 @@ function JQueryStatic() { } function Promise() { - const p1: JQuery.Promise = {} as any; - const p2: JQuery.Promise = {} as any; - const p3: JQuery.Promise = {} as any; + const p1: JQuery.Promise = {} as any; + const p2: JQuery.Promise = {} as any; + const p3: JQuery.Promise = {} as any; // 3 parameters { const w = $.when(p1, p2, p3); w.then((a, b, c) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - c; // $ExpectType I3 + a; // $ExpectType J1 + b; // $ExpectType J2 + c; // $ExpectType J3 }, (a, b, c) => { - a; // $ExpectType I2 - b; // $ExpectType I3 - c; // $ExpectType I4 + a; // $ExpectType J2 + b; // $ExpectType J3 + c; // $ExpectType J4 }, (a, b, c) => { a; // $ExpectType never b; // $ExpectType never @@ -2026,11 +2249,11 @@ function JQueryStatic() { const w = $.when(p1, p2); w.then((a, b) => { - a; // $ExpectType I1 - b; // $ExpectType I2 + a; // $ExpectType J1 + b; // $ExpectType J2 }, (a, b) => { - a; // $ExpectType I2 - b; // $ExpectType I3 + a; // $ExpectType J2 + b; // $ExpectType J3 }, (a, b) => { a; // $ExpectType never b; // $ExpectType never @@ -2042,9 +2265,9 @@ function JQueryStatic() { const w = $.when(p1); w.then(a => { - a; // $ExpectType I1 + a; // $ExpectType J1 }, a => { - a; // $ExpectType I2 + a; // $ExpectType J2 }, a => { a; // $ExpectType never }); @@ -2052,18 +2275,18 @@ function JQueryStatic() { } function Thenable() { - const t1: JQuery.Thenable = {} as any; - const t2: JQuery.Thenable = {} as any; - const t3: JQuery.Thenable = {} as any; + const t1: JQuery.Thenable = {} as any; + const t2: JQuery.Thenable = {} as any; + const t3: JQuery.Thenable = {} as any; // 3 parameters { const w = $.when(t1, t2, t3); w.then((a, b, c) => { - a; // $ExpectType I1 - b; // $ExpectType I2 - c; // $ExpectType I3 + a; // $ExpectType J1 + b; // $ExpectType J2 + c; // $ExpectType J3 }, (a, b, c) => { a; // $ExpectType any b; // $ExpectType any @@ -2080,8 +2303,8 @@ function JQueryStatic() { const w = $.when(t1, t2); w.then((a, b) => { - a; // $ExpectType I1 - b; // $ExpectType I2 + a; // $ExpectType J1 + b; // $ExpectType J2 }, (a, b) => { a; // $ExpectType any b; // $ExpectType any @@ -2096,7 +2319,7 @@ function JQueryStatic() { const w = $.when(t1); w.then(a => { - a; // $ExpectType I1 + a; // $ExpectType J1 }, a => { a; // $ExpectType any }, a => { @@ -2207,7 +2430,7 @@ function JQuery() { $(document).ajaxComplete(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2223,7 +2446,7 @@ function JQuery() { $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2241,7 +2464,7 @@ function JQuery() { $(document).ajaxSend(function(event, jqXHR, ajaxOptions) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2277,7 +2500,7 @@ function JQuery() { $(document).ajaxSuccess(function(event, jqXHR, ajaxOptions, data) { // $ExpectType Document this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; // $ExpectType jqXHR jqXHR; @@ -2621,12 +2844,29 @@ function JQuery() { } function outerHeight() { + const value: string | number = undefined!; + + // $ExpectType JQuery + $('p').outerHeight(value, true); + // $ExpectType JQuery $('p').outerHeight('200px'); // $ExpectType JQuery $('p').outerHeight(400); + // $ExpectType JQuery + $('p').outerHeight(function(index, height) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + height; + + return '200px'; + }, false); + // $ExpectType JQuery $('p').outerHeight(function(index, height) { // $ExpectType HTMLElement @@ -2729,12 +2969,29 @@ function JQuery() { } function outerWidth() { + const value: string | number = undefined!; + + // $ExpectType JQuery + $('p').outerWidth(value, true); + // $ExpectType JQuery $('p').outerWidth('200px'); // $ExpectType JQuery $('p').outerWidth(400); + // $ExpectType JQuery + $('p').outerWidth(function(index, width) { + // $ExpectType HTMLElement + this; + // $ExpectType number + index; + // $ExpectType number + width; + + return '200px'; + }, false); + // $ExpectType JQuery $('p').outerWidth(function(index, width) { // $ExpectType HTMLElement @@ -3626,21 +3883,11 @@ function JQuery() { function events() { // [bind() overloads] https://github.com/jquery/api.jquery.com/issues/1048 function bind() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').bind('myEvent', 'myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', 'myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3648,77 +3895,51 @@ function JQuery() { $('p').bind('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').bind('myEvent', function(this: I1, event) { - // $ExpectType I1 - 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: I1, event) { - // $ExpectType I1 + 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 I1 { kind: 'I1'; } - // $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: I1, event) { - // $ExpectType I1 - 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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3727,44 +3948,32 @@ 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: I1, event) { - // $ExpectType I1 + 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 customContext_defaultData(this: I1, event: JQuery.Event) { } - - function customContext_customData(this: I1, event: JQuery.Event) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $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); @@ -3773,16 +3982,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); @@ -3793,52 +3996,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 I1 { kind: 'I1'; } - - // $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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3846,12 +4027,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 @@ -3859,34 +4057,19 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', null, 'myData', function(this: I1, event) { - // $ExpectType I1 + $('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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -3897,7 +4080,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; }); @@ -3910,20 +4101,15 @@ function JQuery() { }); // $ExpectType JQuery - $('table').on('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 + $('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) { @@ -3957,30 +4143,19 @@ function JQuery() { event; }); - // $ExpectType JQuery - $('table').on('myEvent', function(this: I1, event) { - // $ExpectType I1 - 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: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -3991,13 +4166,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4008,13 +4183,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + 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'); @@ -4025,13 +4217,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4042,34 +4234,37 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + 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 I1 { kind: 'I1'; } - // $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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4077,31 +4272,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: I1, event) { - // $ExpectType I1 + $('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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4112,15 +4299,7 @@ function JQuery() { $('table').one('myEvent', 3, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', 3, function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4128,15 +4307,7 @@ function JQuery() { $('table').one('myEvent', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('table').one('myEvent', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }); @@ -4147,15 +4318,15 @@ function JQuery() { $('table').one({ myEvent1: false, myEvent2(event) { - // $ExpectType HTMLElement + // $ExpectType any this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType any this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 'td', 'myData'); @@ -4166,13 +4337,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, null, 'myData'); @@ -4183,13 +4354,30 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + 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'); @@ -4200,13 +4388,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }, 3); @@ -4217,13 +4405,13 @@ function JQuery() { myEvent2(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType TriggeredEvent event; }, - myEvent3(this: I1, event) { - // $ExpectType I1 + click(event) { + // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType ClickEvent event; } }); @@ -4294,27 +4482,15 @@ 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 customContext_defaultData(this: I1, event: JQuery.Event) { } - - function customContext_customData(this: I1, event: JQuery.Event) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_defaultData); + $('p').unbind('myEvent', defaultData); // $ExpectType JQuery - $('p').unbind('myEvent', defaultContext_customData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_defaultData); - - // $ExpectType JQuery - $('p').unbind('myEvent', customContext_customData); + $('p').unbind('myEvent', customData); // $ExpectType JQuery $('p').unbind('myEvent', false); @@ -4322,35 +4498,24 @@ 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 customContext_defaultData(this: I1, event: JQuery.Event) { } - - function customContext_customData(this: I1, event: JQuery.Event) { } - - interface I1 { kind: 'I1'; } + function customData(this: HTMLElement, event: JQuery.TriggeredEvent) { } // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_defaultData); + $('table').undelegate('td', 'click', defaultData); // $ExpectType JQuery - $('table').undelegate('td', 'click', defaultContext_customData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_defaultData); - - // $ExpectType JQuery - $('table').undelegate('td', 'click', customContext_customData); + $('table').undelegate('td', 'click', customData); // $ExpectType JQuery $('table').undelegate('td', 'click', false); @@ -4361,10 +4526,8 @@ function JQuery() { // $ExpectType JQuery $('table').undelegate('td', { myEvent1: false, - defaultContext_defaultData, - defaultContext_customData, - customContext_defaultData, - customContext_customData + defaultData, + customData }); // $ExpectType JQuery @@ -4375,21 +4538,11 @@ function JQuery() { } function blur() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').blur('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4397,15 +4550,7 @@ function JQuery() { $('p').blur(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').blur(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType BlurEvent event; }); @@ -4417,21 +4562,11 @@ function JQuery() { } function change() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').change('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4439,15 +4574,7 @@ function JQuery() { $('p').change(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').change(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ChangeEvent event; }); @@ -4459,21 +4586,11 @@ function JQuery() { } function click() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').click('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4481,15 +4598,7 @@ function JQuery() { $('p').click(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').click(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ClickEvent event; }); @@ -4501,21 +4610,11 @@ function JQuery() { } function contextmenu() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').contextmenu('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4523,15 +4622,7 @@ function JQuery() { $('p').contextmenu(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').contextmenu(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ContextMenuEvent event; }); @@ -4543,21 +4634,11 @@ function JQuery() { } function dblclick() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').dblclick('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4565,15 +4646,7 @@ function JQuery() { $('p').dblclick(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').dblclick(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType DoubleClickEvent event; }); @@ -4585,21 +4658,11 @@ function JQuery() { } function focus() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').focus('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4607,15 +4670,7 @@ function JQuery() { $('p').focus(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focus(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusEvent event; }); @@ -4627,21 +4682,11 @@ function JQuery() { } function focusin() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').focusin('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4649,15 +4694,7 @@ function JQuery() { $('p').focusin(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusin(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusInEvent event; }); @@ -4669,21 +4706,11 @@ function JQuery() { } function focusout() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').focusout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4691,15 +4718,7 @@ function JQuery() { $('p').focusout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').focusout(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType FocusOutEvent event; }); @@ -4711,21 +4730,11 @@ function JQuery() { } function keydown() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').keydown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4733,15 +4742,7 @@ function JQuery() { $('p').keydown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keydown(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyDownEvent event; }); @@ -4753,21 +4754,11 @@ function JQuery() { } function keypress() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').keypress('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -4775,15 +4766,7 @@ function JQuery() { $('p').keypress(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keypress(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyPressEvent event; }); @@ -4795,21 +4778,11 @@ function JQuery() { } function keyup() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').keyup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -4817,15 +4790,7 @@ function JQuery() { $('p').keyup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').keyup(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType KeyUpEvent event; }); @@ -4837,21 +4802,11 @@ function JQuery() { } function mousedown() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mousedown('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -4859,15 +4814,7 @@ function JQuery() { $('p').mousedown(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousedown(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseDownEvent event; }); @@ -4879,21 +4826,11 @@ function JQuery() { } function mouseenter() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mouseenter('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -4901,15 +4838,7 @@ function JQuery() { $('p').mouseenter(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseenter(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }); @@ -4921,21 +4850,11 @@ function JQuery() { } function mouseleave() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mouseleave('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -4943,15 +4862,7 @@ function JQuery() { $('p').mouseleave(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseleave(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -4963,21 +4874,11 @@ function JQuery() { } function mousemove() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mousemove('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -4985,15 +4886,7 @@ function JQuery() { $('p').mousemove(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mousemove(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseMoveEvent event; }); @@ -5005,21 +4898,11 @@ function JQuery() { } function mouseout() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mouseout('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5027,15 +4910,7 @@ function JQuery() { $('p').mouseout(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseout(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseOutEvent event; }); @@ -5047,21 +4922,11 @@ function JQuery() { } function mouseover() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mouseover('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5069,15 +4934,7 @@ function JQuery() { $('p').mouseover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseover(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseOverEvent event; }); @@ -5089,21 +4946,11 @@ function JQuery() { } function mouseup() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').mouseup('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5111,15 +4958,7 @@ function JQuery() { $('p').mouseup(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').mouseup(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseUpEvent event; }); @@ -5131,21 +4970,11 @@ function JQuery() { } function resize() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').resize('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5153,15 +4982,7 @@ function JQuery() { $('p').resize(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').resize(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ResizeEvent event; }); @@ -5173,21 +4994,11 @@ function JQuery() { } function scroll() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').scroll('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5195,15 +5006,7 @@ function JQuery() { $('p').scroll(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').scroll(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType ScrollEvent event; }); @@ -5215,21 +5018,11 @@ function JQuery() { } function select() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').select('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5237,15 +5030,7 @@ function JQuery() { $('p').select(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').select(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType SelectEvent event; }); @@ -5257,21 +5042,11 @@ function JQuery() { } function submit() { - interface I1 { kind: 'I1'; } - // $ExpectType JQuery $('p').submit('myData', function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit('myData', function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5279,15 +5054,7 @@ function JQuery() { $('p').submit(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').submit(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType SubmitEvent event; }); @@ -5299,32 +5066,16 @@ function JQuery() { } function hover() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - // $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: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event - event; - }, function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5332,41 +5083,7 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }, function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event - event; - }, function(this: I2, event) { - // $ExpectType I2 - this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(function(event) { - // $ExpectType HTMLElement - this; - // $ExpectType Event - event; - }, false); - - // $ExpectType JQuery - $('p').hover(function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseEnterEvent event; }, false); @@ -5374,15 +5091,7 @@ function JQuery() { $('p').hover(false, function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event - event; - }); - - // $ExpectType JQuery - $('p').hover(false, function(this: I1, event) { - // $ExpectType I1 - this; - // $ExpectType Event + // $ExpectType MouseLeaveEvent event; }); @@ -5393,16 +5102,23 @@ function JQuery() { $('p').hover(function(event) { // $ExpectType HTMLElement this; - // $ExpectType Event + // $ExpectType MouseEnterEvent | MouseLeaveEvent event; - }); - // $ExpectType JQuery - $('p').hover(function(this: I1, event) { - // $ExpectType I1 - 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 @@ -6553,6 +6269,25 @@ function JQuery() { } } +function JQuery_Selectors() { + function pseudos_colon() { + // $ExpectType PseudoFunctions + $.expr[':']; + } + + function filter() { + // $ExpectType FilterFunctions + $.expr.filter; + } + + function stackoverflow_50727144() { + $.extend($.expr[":"], { + containsCaseInsensitive: (elem: any, i: number, match: any, array: any) => + (elem.textContent || elem.innerText || "").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0 + }); + } +} + function JQuery_AjaxSettings() { $.ajax({ accepts: { @@ -6719,172 +6454,6 @@ function JQuery_AjaxSettings() { }); } -function JQuery_Callbacks() { - function add() { - const callbacks = $.Callbacks(); - - // $ExpectType Callbacks - callbacks.add(() => { }, [() => { }], () => { }); - - // $ExpectType Callbacks - callbacks.add(() => { }, [() => { }]); - - // $ExpectType Callbacks - callbacks.add(() => { }, () => { }); - - // $ExpectType Callbacks - callbacks.add(() => { }); - - // $ExpectType Callbacks - callbacks.add([() => { }]); - } - - function disable() { - // $ExpectType Callbacks - $.Callbacks().disable(); - } - - function disabled() { - // $ExpectType boolean - $.Callbacks().disabled(); - } - - function empty() { - // $ExpectType Callbacks - $.Callbacks().empty(); - } - - function fire() { - // $ExpectType Callbacks - $.Callbacks().fire(1); - - // $ExpectType Callbacks - $.Callbacks().fire(); - } - - function fireWith() { - // $ExpectType Callbacks - $.Callbacks().fireWith(window, [1]); - - // $ExpectType Callbacks - $.Callbacks().fireWith(window); - } - - function fired() { - // $ExpectType boolean - $.Callbacks().fired(); - } - - function has() { - // $ExpectType boolean - $.Callbacks().has(() => { }); - - // $ExpectType boolean - $.Callbacks().has(); - } - - function lock() { - // $ExpectType Callbacks - $.Callbacks().lock(); - } - - function locked() { - // $ExpectType boolean - $.Callbacks().locked(); - } - - function remove() { - // $ExpectType Callbacks - $.Callbacks().remove(() => { }, () => { }); - } -} - -function JQuery_EffectsOptions() { - $('p').show({ - always(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - complete() { - // $ExpectType HTMLElement - this; - }, - done(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - duration: 5000, - easing: 'linear', - fail(animation, jumpToEnd) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType boolean - jumpToEnd; - }, - progress(animation, progress, remainingMs) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - // $ExpectType number - progress; - // $ExpectType number - remainingMs; - }, - queue: true, - specialEasing: { - width: 'linear', - height: 'easeOutBounce' - }, - start(animation) { - // $ExpectType HTMLElement - this; - // $ExpectType Promise - animation; - }, - step(now, tween) { - // $ExpectType HTMLElement - this; - // $ExpectType number - now; - // $ExpectType Tween - tween; - } - }); -} - -function JQuery_Event() { - function call_signature() { - // $ExpectType Event & Coordinates - $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - $.Event({ - type: 'keydown' - }); - } - - function constructor() { - // $ExpectType Event & Coordinates - new $.Event('keydown', $('p').offset()); - - // $ExpectType Event & { type: string; } - new $.Event({ - type: 'keydown' - }); - } -} - function JQuery_jqXHR() { const p: JQuery.jqXHR = {} as any; @@ -7153,26 +6722,158 @@ function JQuery_jqXHR() { } } +function JQuery_CallbacksStatic() { + // $ExpectType Callbacks + $.Callbacks('once'); + + // $ExpectType Callbacks + $.Callbacks(); +} + +function JQuery_Callbacks() { + function add() { + const callbacks = $.Callbacks(); + + // $ExpectType Callbacks + callbacks.add(() => { }, [() => { }], () => { }); + + // $ExpectType Callbacks + callbacks.add(() => { }, [() => { }]); + + // $ExpectType Callbacks + callbacks.add(() => { }, () => { }); + + // $ExpectType Callbacks + callbacks.add(() => { }); + + // $ExpectType Callbacks + callbacks.add([() => { }]); + } + + function disable() { + // $ExpectType Callbacks + $.Callbacks().disable(); + } + + function disabled() { + // $ExpectType boolean + $.Callbacks().disabled(); + } + + function empty() { + // $ExpectType Callbacks + $.Callbacks().empty(); + } + + function fire() { + // $ExpectType Callbacks + $.Callbacks().fire(1); + + // $ExpectType Callbacks + $.Callbacks().fire(); + } + + function fired() { + // $ExpectType boolean + $.Callbacks().fired(); + } + + function fireWith() { + // $ExpectType Callbacks + $.Callbacks().fireWith(window, [1]); + + // $ExpectType Callbacks + $.Callbacks().fireWith(window); + } + + function has() { + // $ExpectType boolean + $.Callbacks().has(() => { }); + + // $ExpectType boolean + $.Callbacks().has(); + } + + function lock() { + // $ExpectType Callbacks + $.Callbacks().lock(); + } + + function locked() { + // $ExpectType boolean + $.Callbacks().locked(); + } + + function remove() { + // $ExpectType Callbacks + $.Callbacks().remove(() => { }, () => { }); + } +} + +function JQuery_CSSHooks() { + $.cssHooks.borderRadius = { + get(elem, computed, extra) { + // $ExpectedType HTMLElement + elem; + // $ExpectedType any + computed; + // $ExpectedType any + extra; + }, + set(elem, value) { + // $ExpectedType HTMLElement + elem; + // $ExpectedType any + value; + } + }; + + $.cssHooks.borderRadius = { + get(elem, computed, extra) { + // $ExpectedType HTMLElement + elem; + // $ExpectedType any + computed; + // $ExpectedType any + extra; + } + }; + + $.cssHooks.borderRadius = { + set(elem, value) { + // $ExpectedType HTMLElement + elem; + // $ExpectedType any + value; + } + }; + + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + $.cssHooks.borderRadius = function get(elem: HTMLElement, computed: any, extra: any) { + return 1; + }; +} + function JQuery_Promise3() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - interface I3 { kind: 'I3'; } - interface I4 { kind: 'I4'; } - interface I5 { kind: 'I5'; } - interface I6 { kind: 'I6'; } - interface I7 { kind: 'I7'; } - interface I8 { kind: 'I8'; } - interface I9 { kind: 'I9'; } + interface J1 { kind: 'J1'; } + interface J2 { kind: 'J2'; } + interface J3 { kind: 'J3'; } + interface J4 { kind: 'J4'; } + interface J5 { kind: 'J5'; } + interface J6 { kind: 'J6'; } + interface J7 { kind: 'J7'; } + interface J8 { kind: 'J8'; } + interface J9 { kind: 'J9'; } - // tslint:disable-next-line:ban-types - const p: JQuery.Promise3 = {} as any; - const p1: JQuery.Promise3 = {} as any; - const p2: JQuery.Promise3 = {} as any; - const p3: JQuery.Promise3 = {} as any; + const p: JQuery.Promise3 = {} as any; + const p1: JQuery.Promise3 = {} as any; + const p2: JQuery.Promise3 = {} as any; + const p3: JQuery.Promise3 = {} as any; - const t1: JQuery.Thenable = {} as any; - const t2: JQuery.Thenable = {} as any; - const t3: JQuery.Thenable = {} as any; + const t1: JQuery.Thenable = {} as any; + const t2: JQuery.Thenable = {} as any; + const t3: JQuery.Thenable = {} as any; function then() { p.then((a, b, c) => { @@ -7182,7 +6883,7 @@ function JQuery_Promise3() { }, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, (a, b, c) => { a; // $ExpectType number b; // $ExpectType boolean @@ -7192,7 +6893,7 @@ function JQuery_Promise3() { p.then(null, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, (a, b, c) => { a; // $ExpectType number b; // $ExpectType boolean @@ -7222,7 +6923,7 @@ function JQuery_Promise3() { }, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, null); p.then((a, b, c) => { @@ -7232,19 +6933,19 @@ function JQuery_Promise3() { }, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }); p.then(null, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, null); p.then(null, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }); p.then((a, b, c) => { @@ -7287,7 +6988,7 @@ function JQuery_Promise3() { }, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, (a, b, c) => { a; // $ExpectType number b; // $ExpectType boolean @@ -7317,7 +7018,7 @@ function JQuery_Promise3() { }, (a, b, c) => { a; // $ExpectType Error b; // $ExpectType string - c; // $ExpectType Function + c; // $ExpectType Element }, (a, b, c) => { a; // $ExpectType number b; // $ExpectType boolean @@ -7354,7 +7055,7 @@ function JQuery_Promise3() { }); q.then((a) => { - a; // $ExpectType I1 | I2 + a; // $ExpectType J1 | J2 }, (a) => { a; // $ExpectType never }, (a, b, c) => { @@ -7373,17 +7074,17 @@ function JQuery_Promise3() { }); q.then((a, b, c) => { - a; // $ExpectType I1 | I2 - b; // $ExpectType I4 | I5 - c; // $ExpectType I7 | I8 + a; // $ExpectType J1 | J2 + b; // $ExpectType J4 | J5 + c; // $ExpectType J7 | J8 }, (a, b, c) => { - a; // $ExpectType I2 | I3 - b; // $ExpectType I5 | I6 - c; // $ExpectType I8 | I9 + a; // $ExpectType J2 | J3 + b; // $ExpectType J5 | J6 + c; // $ExpectType J8 | J9 }, (a, b, c) => { - a; // $ExpectType I3 | I4 - b; // $ExpectType I6 | I7 - c; // $ExpectType I1 | I9 + a; // $ExpectType J3 | J4 + b; // $ExpectType J6 | J7 + c; // $ExpectType J1 | J9 }); } @@ -7396,7 +7097,7 @@ function JQuery_Promise3() { }); q.then((a) => { - a; // $ExpectType number | I1 + a; // $ExpectType number | J1 }, (a) => { a; // never }, (a, b, c) => { @@ -7415,7 +7116,7 @@ function JQuery_Promise3() { }); q.then((a) => { - a; // $ExpectType number | I1 + a; // $ExpectType number | J1 }, (a) => { a; // never }, (a, b, c) => { @@ -7434,17 +7135,17 @@ function JQuery_Promise3() { }); q.then((a, b, c) => { - a; // $ExpectType number | I1 - b; // $ExpectType I4 - c; // $ExpectType I7 + a; // $ExpectType number | J1 + b; // $ExpectType J4 + c; // $ExpectType J7 }, (a, b, c) => { - a; // $ExpectType I2 - b; // $ExpectType I5 - c; // $ExpectType I8 + a; // $ExpectType J2 + b; // $ExpectType J5 + c; // $ExpectType J8 }, (a, b, c) => { - a; // $ExpectType I3 - b; // $ExpectType I6 - c; // $ExpectType I9 + a; // $ExpectType J3 + b; // $ExpectType J6 + c; // $ExpectType J9 }); } @@ -7457,17 +7158,17 @@ function JQuery_Promise3() { }); q.then((a, b, c) => { - a; // $ExpectType number | I1 - b; // $ExpectType I4 - c; // $ExpectType I7 + a; // $ExpectType number | J1 + b; // $ExpectType J4 + c; // $ExpectType J7 }, (a, b, c) => { - a; // $ExpectType I2 - b; // $ExpectType I5 - c; // $ExpectType I8 + a; // $ExpectType J2 + b; // $ExpectType J5 + c; // $ExpectType J8 }, (a, b, c) => { - a; // $ExpectType I3 - b; // $ExpectType I6 - c; // $ExpectType I9 + a; // $ExpectType J3 + b; // $ExpectType J6 + c; // $ExpectType J9 }); } @@ -7480,17 +7181,17 @@ function JQuery_Promise3() { }); q.then((a, b, c) => { - a; // $ExpectType I1 | I2 - b; // $ExpectType I5 - c; // $ExpectType I8 + a; // $ExpectType J1 | J2 + b; // $ExpectType J5 + c; // $ExpectType J8 }, (a, b, c) => { - a; // $ExpectType I3 - b; // $ExpectType I6 - c; // $ExpectType I9 + a; // $ExpectType J3 + b; // $ExpectType J6 + c; // $ExpectType J9 }, (a, b, c) => { - a; // $ExpectType I4 - b; // $ExpectType I7 - c; // $ExpectType I1 + a; // $ExpectType J4 + b; // $ExpectType J7 + c; // $ExpectType J1 }); } @@ -7503,17 +7204,17 @@ function JQuery_Promise3() { }); q.then((a, b, c) => { - a; // $ExpectType I1 | I2 - b; // $ExpectType I4 - c; // $ExpectType I7 + a; // $ExpectType J1 | J2 + b; // $ExpectType J4 + c; // $ExpectType J7 }, (a, b, c) => { - a; // $ExpectType I2 - b; // $ExpectType I5 - c; // $ExpectType I8 + a; // $ExpectType J2 + b; // $ExpectType J5 + c; // $ExpectType J8 }, (a, b, c) => { - a; // $ExpectType I3 - b; // $ExpectType I6 - c; // $ExpectType I9 + a; // $ExpectType J3 + b; // $ExpectType J6 + c; // $ExpectType J9 }); } } @@ -7532,9 +7233,9 @@ function JQuery_Promise3() { const a = $.ajax('/echo/json').catch(() => { return t1; }); - // $ExpectType PromiseBase + // $ExpectType PromiseBase a; - const b: JQuery.Promise3 = a; + const b: JQuery.Promise3 = a; } { const a = $.ajax('/echo/json').catch(() => { @@ -7839,18 +7540,609 @@ function JQuery_Promise(p: JQuery.Promise) { } } -function JQuery_Deferred() { - interface I1 { kind: 'I1'; } - interface I2 { kind: 'I2'; } - interface I3 { kind: 'I3'; } +function JQuery_DeferredStatic() { + function exceptionHook() { + $.Deferred.exceptionHook = undefined; + } - const d1 = $.Deferred(); + function call_signature() { + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); - function promise() { - const target: I1 = {} as any; + // $ExpectType Deferred + $.Deferred(); - d1.promise(target); // $ExpectType Promise & I1 + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); - d1.promise(); // $ExpectType Promise + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); + + // $ExpectType Deferred + $.Deferred(function(deferred) { + // $ExpectType Deferred + this; + // $ExpectType Deferred + deferred; + }); + + // $ExpectType Deferred + $.Deferred(); } } + +function JQuery_Deferred() { + interface J1 { kind: 'J1'; } + interface J2 { kind: 'J2'; } + interface J3 { kind: 'J3'; } + + const d1 = $.Deferred(); + + function promise() { + const target: J1 = {} as any; + + d1.promise(target); // $ExpectType Promise & J1 + + d1.promise(); // $ExpectType Promise + } +} + +function JQuery_EffectsOptions() { + $('p').show({ + always(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + complete() { + // $ExpectType HTMLElement + this; + }, + done(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + duration: 5000, + easing: 'linear', + fail(animation, jumpToEnd) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType boolean + jumpToEnd; + }, + progress(animation, progress, remainingMs) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + // $ExpectType number + progress; + // $ExpectType number + remainingMs; + }, + queue: true, + specialEasing: { + width: 'linear', + height: 'easeOutBounce' + }, + start(animation) { + // $ExpectType HTMLElement + this; + // $ExpectType Animation + animation; + }, + step(now, tween) { + // $ExpectType HTMLElement + this; + // $ExpectType number + now; + // $ExpectType Tween + tween; + } + }); +} + +function JQuery_AnimationStatic() { + function call_signature() { + const element: HTMLElement = undefined!; + + // $ExpectType Animation + $.Animation(element, {}, {}); + } + + function prefilter() { + // https://github.com/jquery/api.jquery.com/issues/256 -> http://jsfiddle.net/y4L35/ + { + // $ExpectType void + $.Animation.prefilter(function(element: HTMLElement, properties, options) { + // $ExpectType Animation + this; + // $ExpectType HTMLElement + element; + // $ExpectType PlainObject + properties; + // $ExpectType EffectsOptions + options; + // $ExpectType any + options.removeAfter; + + if (options.removeAfter) { + this.done(() => { + $(element).remove(); + }); + } + }); + + $("#element").hide({ + duration: 500, + removeAfter: true, + complete() { + // 0, because the prefilter done happens first! + console.log($(this).parent().length); + } + }); + } + } + + function tweener() { + // $ExpectType void + $.Animation.tweener('*', function(propName, finalValue) { + // $ExpectType Animation + this; + // $ExpectType string + propName; + // $ExpectType number + finalValue; + + return this.createTween(propName, finalValue); + }); + } +} + +function JQuery_Animation() { + const element: Element = undefined!; + + const animation = $.Animation(element, {}, {}); + + animation.done((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType true | undefined + jumpedToEnd; + }); + + animation.fail((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType false + jumpedToEnd; + }); + + animation.always((anim, jumpedToEnd) => { + // $ExpectType Animation + anim; + // $ExpectType boolean | undefined + jumpedToEnd; + }); + + animation.progress((anim, progress, remainingMs) => { + // $ExpectType Animation + anim; + // $ExpectType number + progress; + // $ExpectType number + remainingMs; + }); +} + +function JQuery_TweenStatic() { + function propHooks() { + $.Tween.propHooks['myProp'] = { + get(tween) { + // $ExpectType Tween + tween; + + return tween.elem[tween.prop as keyof typeof tween.elem]; + }, + set(tween) { + // $ExpectType Tween + tween; + }, + }; + + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + $.Tween.propHooks['myProp'] = 1; + } + + function call_signature() { + const elem: HTMLElement = undefined!; + + // $ExpectType Tween + $.Tween(elem, {}, 'myProp', 1, 'myEasing', 'myUnit'); + + // $ExpectType Tween + $.Tween(elem, {}, 'myProp', 1, 'myEasing'); + + // $ExpectType Tween + $.Tween(elem, {}, 'myProp', 1); + } +} + +function JQuery_Easings() { + jQuery.easing.easeInCubic = (p) => { + return Math.pow(p, 3); + }; +} + +function JQuery_Effects() { + function interval() { + // $ExpectType number + $.fx.interval; + } + + function off() { + // $ExpectType boolean + $.fx.off; + } + + function step() { + // $ExpectType PlainObject> + $.fx.step; + } + + function stop() { + // $ExpectType () => void + $.fx.stop; + + function override() { + let animating: boolean; + + jQuery.fx.stop = () => { + animating = false; + }; + } + } + + function timer() { + // $ExpectType (tickFunction: TickFunction) => void + $.fx.timer; + + function override() { + let animating: boolean; + const raf: () => void = {} as any; + + jQuery.fx.timer = (timer) => { + // $ExpectType TickFunction + timer; + + if (timer() && jQuery.timers.push(timer) && !animating) { + animating = true; + raf(); + } + }; + } + } +} + +function JQuery_Event() { + function call_signature() { + // $ExpectType Event & Coordinates + $.Event('keydown', $('p').offset()); + } + + function constructor() { + // $ExpectType Event & Coordinates + new $.Event('keydown', $('p').offset()); + } + + // https://stackoverflow.com/questions/49892574/trigger-a-jquery-3-event-with-ctrlkey-set + function stackoverflow_49892574() { + 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 special() { + jQuery.event.special.multiclick = { + noBubble: true, + bindType: 'click', + delegateType: 'click', + setup(data, namespaces, eventHandle) { + // $ExpectType EventTarget + this; + // $ExpectType any + data; + // $ExpectType string + namespaces; + // $ExpectType EventHandlerBase> + eventHandle; + + return false; + }, + teardown() { + // $ExpectType EventTarget + this; + + return false; + }, + add(handleObj) { + // $ExpectType EventTarget + this; + // $ExpectType HandleObject + handleObj; + }, + remove(handleObj) { + // $ExpectType EventTarget + this; + // $ExpectType HandleObject + handleObj; + }, + trigger(event, data) { + // $ExpectType EventTarget + this; + // $ExpectType Event + event; + // $ExpectType any + data; + + return false; + }, + _default(event, data) { + // $ExpectType TriggeredEvent + event; + // $ExpectType any + data; + + return false; + }, + handle(event, data) { + // $ExpectType TriggeredEvent & { handleObj: HandleObject; } + event; + // $ExpectType any + data; + }, + preDispatch(event) { + // $ExpectType EventTarget + this; + // $ExpectType Event + event; + + return false; + }, + postDispatch(event) { + // $ExpectType EventTarget + this; + // $ExpectType Event + event; + } + }; + + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + jQuery.event.special.multiclick = 1; + } +} + +declare namespace JQuery { + interface ValHooks { + textarea: ValHook; + } +} + +function JQuery_ValHooks() { + jQuery.valHooks.textarea = { + get(elem) { + // $ExpectType HTMLTextAreaElement + elem; + + return elem.value.replace(/\r?\n/g, "\r\n"); + }, + set(elem) { + // $ExpectType HTMLTextAreaElement + elem; + + return elem.value; + } + }; + + // Weak type test. This may be removed if the TypeScript requirement is increased to 2.4+. + // $ExpectError + jQuery.valHooks.textarea = function get(elem: HTMLTextAreaElement) { + return elem.value.replace(/\r?\n/g, "\r\n"); + }; +} diff --git a/types/jquery/legacy.d.ts b/types/jquery/legacy.d.ts new file mode 100644 index 0000000000..a3a98b936c --- /dev/null +++ b/types/jquery/legacy.d.ts @@ -0,0 +1,201 @@ +// tslint:disable:no-irregular-whitespace + +// tslint:disable-next-line:no-empty-interface +interface JQueryCallback extends JQuery.Callbacks { } +interface JQueryDeferred extends JQuery.Deferred { } +// tslint:disable-next-line:no-empty-interface +interface JQueryEventConstructor extends JQuery.EventStatic { } +interface JQueryDeferred extends JQuery.Deferred { } +// tslint:disable-next-line:no-empty-interface +interface JQueryAjaxSettings extends JQuery.AjaxSettings { } +interface JQueryAnimationOptions extends JQuery.EffectsOptions { } +// tslint:disable-next-line:no-empty-interface +interface JQueryCoordinates extends JQuery.Coordinates { } +interface JQueryGenericPromise extends JQuery.Thenable { } +// tslint:disable-next-line:no-empty-interface +interface JQueryXHR extends JQuery.jqXHR { } +interface JQueryPromise extends JQuery.Promise { } +// tslint:disable-next-line:no-empty-interface +interface JQuerySerializeArrayElement extends JQuery.NameValuePair { } + +/** + * @deprecated ​ Deprecated since 1.9. See \`{@link https://api.jquery.com/jQuery.support/ }\`. + */ +// tslint:disable-next-line:no-empty-interface +interface JQuerySupport extends JQuery.PlainObject { } + +// Legacy types that are not represented in the current type definitions are marked deprecated. + +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Deferred.Callback }\` or \`{@link JQuery.Deferred.CallbackBase }\`. + */ +interface JQueryPromiseCallback { + // tslint:disable-next-line:callable-types + (value?: T, ...args: any[]): void; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQueryStatic.param JQueryStatic['param']}\`. + */ +interface JQueryParam { + /** + * Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. + * @param obj An array or object to serialize. + * @param traditional A Boolean indicating whether to perform a traditional "shallow" serialization. + */ + // tslint:disable-next-line:callable-types + (obj: any, traditional?: boolean): string; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\`. + */ +interface BaseJQueryEventObject extends Event { + /** + * The current DOM element within the event bubbling phase. + * @see \`{@link https://api.jquery.com/event.currentTarget/ }\` + */ + currentTarget: Element; + /** + * 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/ }\` + */ + data: any; + /** + * The element where the currently-called jQuery event handler was attached. + * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` + */ + delegateTarget: Element; + /** + * Returns whether event.preventDefault() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` + */ + isDefaultPrevented(): boolean; + /** + * Returns whether event.stopImmediatePropagation() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` + */ + isImmediatePropagationStopped(): boolean; + /** + * Returns whether event.stopPropagation() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` + */ + isPropagationStopped(): boolean; + /** + * The namespace specified when the event was triggered. + * @see \`{@link https://api.jquery.com/event.namespace/ }\` + */ + namespace: string; + /** + * The browser's original Event object. + * @see \`{@link https://api.jquery.com/category/events/event-object/ }\` + */ + originalEvent: Event; + /** + * If this method is called, the default action of the event will not be triggered. + * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` + */ + preventDefault(): any; + /** + * The other DOM element involved in the event, if any. + * @see \`{@link https://api.jquery.com/event.relatedTarget/ }\` + */ + relatedTarget: Element; + /** + * 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/ }\` + */ + result: any; + /** + * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. + * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` + */ + stopImmediatePropagation(): void; + /** + * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. + * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` + */ + stopPropagation(): void; + /** + * The DOM element that initiated the event. + * @see \`{@link https://api.jquery.com/event.target/ }\` + */ + target: Element; + /** + * The mouse position relative to the left edge of the document. + * @see \`{@link https://api.jquery.com/event.pageX/ }\` + */ + pageX: number; + /** + * The mouse position relative to the top edge of the document. + * @see \`{@link https://api.jquery.com/event.pageY/ }\` + */ + pageY: number; + /** + * For key or mouse events, this property indicates the specific key or button that was pressed. + * @see \`{@link https://api.jquery.com/event.which/ }\` + */ + which: number; + /** + * Indicates whether the META key was pressed when the event fired. + * @see \`{@link https://api.jquery.com/event.metaKey/ }\` + */ + metaKey: boolean; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\`. + */ +interface JQueryInputEventObject extends BaseJQueryEventObject { + altKey: boolean; + ctrlKey: boolean; + metaKey: boolean; + shiftKey: boolean; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\`. + */ +interface JQueryMouseEventObject extends JQueryInputEventObject { + button: number; + clientX: number; + clientY: number; + offsetX: number; + offsetY: number; + pageX: number; + pageY: number; + screenX: number; + screenY: number; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\`. + */ +interface JQueryKeyEventObject extends JQueryInputEventObject { + char: any; + charCode: number; + key: any; + keyCode: number; +} +/** + * @deprecated ​ Deprecated. Use \`{@link JQuery.Event }\`. + */ +interface JQueryEventObject extends BaseJQueryEventObject, JQueryInputEventObject, JQueryMouseEventObject, JQueryKeyEventObject { } +/** + * @deprecated ​ Deprecated. + */ +interface JQueryPromiseOperator { + // tslint:disable-next-line:callable-types + (callback1: JQuery.TypeOrArray>, + ...callbacksN: Array>>): JQueryPromise; +} +/** + * @deprecated ​ Deprecated. Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. + */ +interface JQueryEasingFunction { + // tslint:disable-next-line:callable-types + (percent: number): number; +} +/** + * @deprecated ​ Deprecated. Internal. See \`{@link https://github.com/jquery/api.jquery.com/issues/912 }\`. + */ +interface JQueryEasingFunctions { + [name: string]: JQueryEasingFunction; + linear: JQueryEasingFunction; + swing: JQueryEasingFunction; +} diff --git a/types/jquery/misc.d.ts b/types/jquery/misc.d.ts new file mode 100644 index 0000000000..ebba2f7a31 --- /dev/null +++ b/types/jquery/misc.d.ts @@ -0,0 +1,6562 @@ +// tslint:disable:jsdoc-format +// tslint:disable:max-line-length +// tslint:disable:no-irregular-whitespace + +declare namespace JQuery { + type TypeOrArray = T | T[]; + type Node = Element | Text | Comment | DocumentFragment; + + /** + * A string is designated htmlString in jQuery documentation when it is used to represent one or more DOM elements, typically to be created and inserted in the document. When passed as an argument of the jQuery() function, the string is identified as HTML if it starts with ) and is parsed as such until the final > character. Prior to jQuery 1.9, a string was considered to be HTML if it contained anywhere within the string. + */ + type htmlString = string; + /** + * A selector is used in jQuery to select DOM elements from a DOM document. That document is, in most cases, the DOM document present in all browsers, but can also be an XML document received via Ajax. + */ + type Selector = string; + + /** + * The PlainObject type is a JavaScript object containing zero or more key-value pairs. The plain object is, in other words, an Object object. It is designated "plain" in jQuery documentation to distinguish it from other kinds of JavaScript objects: for example, null, user-defined arrays, and host objects such as document, all of which have a typeof value of "object." + * + * **Note**: The type declaration of PlainObject is imprecise. It includes host objects and user-defined arrays which do not match jQuery's definition. + */ + interface PlainObject { + [key: string]: T; + } + + interface Selectors extends Sizzle.Selectors { + /** + * @deprecated ​ Deprecated since 3.0. Use \`{@link Selectors#pseudos }\`. + * + * **Cause**: The standard way to add new custom selectors through jQuery is `jQuery.expr.pseudos`. These two other aliases are deprecated, although they still work as of jQuery 3.0. + * + * **Solution**: Rename any of the older usage to `jQuery.expr.pseudos`. The functionality is identical. + */ + ':': Sizzle.Selectors.PseudoFunctions; + /** + * @deprecated ​ Deprecated since 3.0. Use \`{@link Selectors#pseudos }\`. + * + * **Cause**: The standard way to add new custom selectors through jQuery is `jQuery.expr.pseudos`. These two other aliases are deprecated, although they still work as of jQuery 3.0. + * + * **Solution**: Rename any of the older usage to `jQuery.expr.pseudos`. The functionality is identical. + */ + filter: Sizzle.Selectors.FilterFunctions; + } + + // region Ajax + // #region Ajax + + interface AjaxSettings extends Ajax.AjaxSettingsBase { + /** + * A string containing the URL to which the request is sent. + */ + url?: string; + } + + interface UrlAjaxSettings extends Ajax.AjaxSettingsBase { + /** + * A string containing the URL to which the request is sent. + */ + url: string; + } + + namespace Ajax { + type SuccessTextStatus = 'success' | 'notmodified' | 'nocontent'; + type ErrorTextStatus = 'timeout' | 'error' | 'abort' | 'parsererror'; + type TextStatus = SuccessTextStatus | ErrorTextStatus; + + type SuccessCallback = (this: TContext, data: any, textStatus: SuccessTextStatus, jqXHR: jqXHR) => void; + + type ErrorCallback = (this: TContext, jqXHR: jqXHR, textStatus: ErrorTextStatus, errorThrown: string) => void; + + type CompleteCallback = (this: TContext, jqXHR: jqXHR, textStatus: TextStatus) => void; + + /** + * @see \`{@link https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings }\` + */ + interface AjaxSettingsBase { + /** + * A set of key/value pairs that map a given dataType to its MIME type, which gets sent in the Accept request header. This header tells the server what kind of response it will accept in return. + */ + accepts?: PlainObject; + /** + * By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active. As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done(). + */ + async?: boolean; + /** + * A pre-request callback function that can be used to modify the jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object before it is sent. Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event. Returning false in the beforeSend function will cancel the request. As of jQuery 1.5, the beforeSend option will be called regardless of the type of request. + */ + beforeSend?(this: TContext, jqXHR: jqXHR, settings: this): false | void; + /** + * If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET. + */ + cache?: boolean; + /** + * A function to be called when the request finishes (after success and error callbacks are executed). The function gets passed two arguments: The jqXHR (in jQuery 1.4.x, XMLHTTPRequest) object and a string categorizing the status of the request ("success", "notmodified", "nocontent", "error", "timeout", "abort", or "parsererror"). As of jQuery 1.5, the complete setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + complete?: TypeOrArray>; + /** + * An object of string/regular-expression pairs that determine how jQuery will parse the response, given its content type. + */ + contents?: PlainObject; + /** + * When sending data to the server, use this content type. Default is "application/x-www-form-urlencoded; charset=UTF-8", which is fine for most cases. If you explicitly pass in a content-type to $.ajax(), then it is always sent to the server (even if no data is sent). As of jQuery 1.6 you can pass false to tell jQuery to not set any content type header. Note: The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding. Note: For cross-domain requests, setting the content type to anything other than application/x-www-form-urlencoded, multipart/form-data, or text/plain will trigger the browser to send a preflight OPTIONS request to the server. + */ + contentType?: string | false; + /** + * This object will be the context of all Ajax-related callbacks. By default, the context is an object that represents the Ajax settings used in the call ($.ajaxSettings merged with the settings passed to $.ajax). + */ + context?: TContext; + /** + * An object containing dataType-to-dataType converters. Each converter's value is a function that returns the transformed value of the response. + */ + converters?: PlainObject<((value: any) => any) | true>; + /** + * If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true. This allows, for example, server-side redirection to another domain. + */ + crossDomain?: boolean; + /** + * Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below). + */ + data?: PlainObject | string; + /** + * A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. + */ + dataFilter?(data: string, type: string): any; + /** + * The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are: + * + * "xml": Returns a XML document that can be processed via jQuery. + * + * "html": Returns HTML as plain text; included script tags are evaluated when inserted in the DOM. + * + * "script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, _=[TIMESTAMP], to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests. + * + * "json": Evaluates the response as JSON and returns a JavaScript object. Cross-domain "json" requests are converted to "jsonp" unless the request includes jsonp: false in its request options. The JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected; the server should return a response of null or {} instead. (See json.org for more information on proper JSON formatting.) + * + * "jsonp": Loads in a JSON block using JSONP. Adds an extra "?callback=?" to the end of your URL to specify the callback. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. + * + * "text": A plain text string. + * + * multiple, space-separated values: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require. For example, if you want a text response to be treated as XML, use "text xml" for the dataType. You can also make a JSONP request, have it received as text, and interpreted by jQuery as XML: "jsonp text xml". Similarly, a shorthand string such as "jsonp xml" will first attempt to convert from jsonp to xml, and, failing that, convert from jsonp to text, and then from text to xml. + */ + dataType?: 'xml' | 'html' | 'script' | 'json' | 'jsonp' | 'text' | string; + /** + * A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error." As of jQuery 1.5, the error setting can accept an array of functions. Each function will be called in turn. Note: This handler is not called for cross-domain script and cross-domain JSONP requests. This is an Ajax Event. + */ + error?: TypeOrArray>; + /** + * Whether to trigger global Ajax event handlers for this request. The default is true. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. This can be used to control various Ajax Events. + */ + global?: boolean; + /** + * An object of additional header key/value pairs to send along with requests using the XMLHttpRequest transport. The header X-Requested-With: XMLHttpRequest is always added, but its default XMLHttpRequest value can be changed here. Values in the headers setting can also be overwritten from within the beforeSend function. + */ + headers?: PlainObject; + /** + * Allow the request to be successful only if the response has changed since the last request. This is done by checking the Last-Modified header. Default value is false, ignoring the header. In jQuery 1.4 this technique also checks the 'etag' specified by the server to catch unmodified data. + */ + ifModified?: boolean; + /** + * Allow the current environment to be recognized as "local," (e.g. the filesystem), even if jQuery does not recognize it as such by default. The following protocols are currently recognized as local: file, *-extension, and widget. If the isLocal setting needs modification, it is recommended to do so once in the $.ajaxSetup() method. + */ + isLocal?: boolean; + /** + * Override the callback function name in a JSONP request. This value will be used instead of 'callback' in the 'callback=?' part of the query string in the url. So {jsonp:'onJSONPLoad'} would result in 'onJSONPLoad=?' passed to the server. As of jQuery 1.5, setting the jsonp option to false prevents jQuery from adding the "?callback" string to the URL or attempting to use "=?" for transformation. In this case, you should also explicitly set the jsonpCallback setting. For example, { jsonp: false, jsonpCallback: "callbackName" }. If you don't trust the target of your Ajax requests, consider setting the jsonp property to false for security reasons. + */ + jsonp?: string | false; + /** + * Specify the callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests. As of jQuery 1.5, you can also use a function for this setting, in which case the value of jsonpCallback is set to the return value of that function. + */ + jsonpCallback?: string | ((this: TContext) => string); + /** + * The HTTP method to use for the request (e.g. "POST", "GET", "PUT"). + */ + method?: string; + /** + * A mime type to override the XHR mime type. + */ + mimeType?: string; + /** + * A password to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + password?: string; + /** + * By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false. + */ + processData?: boolean; + /** + * Only applies when the "script" transport is used (e.g., cross-domain requests with "jsonp" or "script" dataType and "GET" type). Sets the charset attribute on the script tag used in the request. Used when the character set on the local page is not the same as the one on the remote script. + */ + scriptCharset?: string; + /** + * An object of numeric HTTP codes and functions to be called when the response has the corresponding code. + * + * If the request is successful, the status code functions take the same parameters as the success callback; if it results in an error (including 3xx redirect), they take the same parameters as the error callback. + */ + statusCode?: StatusCodeCallbacks; + /** + * A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter or the dataFilter callback function, if specified; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event. + */ + success?: TypeOrArray>; + /** + * Set a timeout (in milliseconds) for the request. A value of 0 means there will be no timeout. This will override any global timeout set with $.ajaxSetup(). The timeout period starts at the point the $.ajax call is made; if several other requests are in progress and the browser has no connections available, it is possible for a request to time out before it can be sent. In jQuery 1.4.x and below, the XMLHttpRequest object will be in an invalid state if the request times out; accessing any object members may throw an exception. In Firefox 3.0+ only, script and JSONP requests cannot be cancelled by a timeout; the script will run even if it arrives after the timeout period. + */ + timeout?: number; + /** + * Set this to true if you wish to use the traditional style of param serialization. + */ + traditional?: boolean; + /** + * An alias for method. You should use type if you're using versions of jQuery prior to 1.9.0. + */ + type?: string; + /** + * A username to be used with XMLHttpRequest in response to an HTTP access authentication request. + */ + username?: string; + // ActiveXObject requires "lib": ["scripthost"] which consumers would also require + /** + * Callback for creating the XMLHttpRequest object. Defaults to the ActiveXObject when available (IE), the XMLHttpRequest otherwise. Override to provide your own implementation for XMLHttpRequest or enhancements to the factory. + */ + xhr?(): XMLHttpRequest; + /** + * An object of fieldName-fieldValue pairs to set on the native XHR object. + * + * In jQuery 1.5, the withCredentials property was not propagated to the native XHR and thus CORS requests requiring it would ignore this flag. For this reason, we recommend using jQuery 1.5.1+ should you require the use of it. + */ + xhrFields?: XHRFields; + } + + // region StatusCodeCallbacks + // #region StatusCodeCallbacks + + type StatusCodeCallbacks = { + // region Success Status Codes + // #region Success Status Codes + + // jQuery treats 2xx and 304 status codes as a success + + 200?: SuccessCallback; + 201?: SuccessCallback; + 202?: SuccessCallback; + 203?: SuccessCallback; + 204?: SuccessCallback; + 205?: SuccessCallback; + 206?: SuccessCallback; + 207?: SuccessCallback; + 208?: SuccessCallback; + 209?: SuccessCallback; + 210?: SuccessCallback; + 211?: SuccessCallback; + 212?: SuccessCallback; + 213?: SuccessCallback; + 214?: SuccessCallback; + 215?: SuccessCallback; + 216?: SuccessCallback; + 217?: SuccessCallback; + 218?: SuccessCallback; + 219?: SuccessCallback; + 220?: SuccessCallback; + 221?: SuccessCallback; + 222?: SuccessCallback; + 223?: SuccessCallback; + 224?: SuccessCallback; + 225?: SuccessCallback; + 226?: SuccessCallback; + 227?: SuccessCallback; + 228?: SuccessCallback; + 229?: SuccessCallback; + 230?: SuccessCallback; + 231?: SuccessCallback; + 232?: SuccessCallback; + 233?: SuccessCallback; + 234?: SuccessCallback; + 235?: SuccessCallback; + 236?: SuccessCallback; + 237?: SuccessCallback; + 238?: SuccessCallback; + 239?: SuccessCallback; + 240?: SuccessCallback; + 241?: SuccessCallback; + 242?: SuccessCallback; + 243?: SuccessCallback; + 244?: SuccessCallback; + 245?: SuccessCallback; + 246?: SuccessCallback; + 247?: SuccessCallback; + 248?: SuccessCallback; + 249?: SuccessCallback; + 250?: SuccessCallback; + 251?: SuccessCallback; + 252?: SuccessCallback; + 253?: SuccessCallback; + 254?: SuccessCallback; + 255?: SuccessCallback; + 256?: SuccessCallback; + 257?: SuccessCallback; + 258?: SuccessCallback; + 259?: SuccessCallback; + 260?: SuccessCallback; + 261?: SuccessCallback; + 262?: SuccessCallback; + 263?: SuccessCallback; + 264?: SuccessCallback; + 265?: SuccessCallback; + 266?: SuccessCallback; + 267?: SuccessCallback; + 268?: SuccessCallback; + 269?: SuccessCallback; + 270?: SuccessCallback; + 271?: SuccessCallback; + 272?: SuccessCallback; + 273?: SuccessCallback; + 274?: SuccessCallback; + 275?: SuccessCallback; + 276?: SuccessCallback; + 277?: SuccessCallback; + 278?: SuccessCallback; + 279?: SuccessCallback; + 280?: SuccessCallback; + 281?: SuccessCallback; + 282?: SuccessCallback; + 283?: SuccessCallback; + 284?: SuccessCallback; + 285?: SuccessCallback; + 286?: SuccessCallback; + 287?: SuccessCallback; + 288?: SuccessCallback; + 289?: SuccessCallback; + 290?: SuccessCallback; + 291?: SuccessCallback; + 292?: SuccessCallback; + 293?: SuccessCallback; + 294?: SuccessCallback; + 295?: SuccessCallback; + 296?: SuccessCallback; + 297?: SuccessCallback; + 298?: SuccessCallback; + 299?: SuccessCallback; + 304?: SuccessCallback; + + // #endregion + + // region Error Status Codes + // #region Error Status Codes + + 300?: ErrorCallback; + 301?: ErrorCallback; + 302?: ErrorCallback; + 303?: ErrorCallback; + 305?: ErrorCallback; + 306?: ErrorCallback; + 307?: ErrorCallback; + 308?: ErrorCallback; + 309?: ErrorCallback; + 310?: ErrorCallback; + 311?: ErrorCallback; + 312?: ErrorCallback; + 313?: ErrorCallback; + 314?: ErrorCallback; + 315?: ErrorCallback; + 316?: ErrorCallback; + 317?: ErrorCallback; + 318?: ErrorCallback; + 319?: ErrorCallback; + 320?: ErrorCallback; + 321?: ErrorCallback; + 322?: ErrorCallback; + 323?: ErrorCallback; + 324?: ErrorCallback; + 325?: ErrorCallback; + 326?: ErrorCallback; + 327?: ErrorCallback; + 328?: ErrorCallback; + 329?: ErrorCallback; + 330?: ErrorCallback; + 331?: ErrorCallback; + 332?: ErrorCallback; + 333?: ErrorCallback; + 334?: ErrorCallback; + 335?: ErrorCallback; + 336?: ErrorCallback; + 337?: ErrorCallback; + 338?: ErrorCallback; + 339?: ErrorCallback; + 340?: ErrorCallback; + 341?: ErrorCallback; + 342?: ErrorCallback; + 343?: ErrorCallback; + 344?: ErrorCallback; + 345?: ErrorCallback; + 346?: ErrorCallback; + 347?: ErrorCallback; + 348?: ErrorCallback; + 349?: ErrorCallback; + 350?: ErrorCallback; + 351?: ErrorCallback; + 352?: ErrorCallback; + 353?: ErrorCallback; + 354?: ErrorCallback; + 355?: ErrorCallback; + 356?: ErrorCallback; + 357?: ErrorCallback; + 358?: ErrorCallback; + 359?: ErrorCallback; + 360?: ErrorCallback; + 361?: ErrorCallback; + 362?: ErrorCallback; + 363?: ErrorCallback; + 364?: ErrorCallback; + 365?: ErrorCallback; + 366?: ErrorCallback; + 367?: ErrorCallback; + 368?: ErrorCallback; + 369?: ErrorCallback; + 370?: ErrorCallback; + 371?: ErrorCallback; + 372?: ErrorCallback; + 373?: ErrorCallback; + 374?: ErrorCallback; + 375?: ErrorCallback; + 376?: ErrorCallback; + 377?: ErrorCallback; + 378?: ErrorCallback; + 379?: ErrorCallback; + 380?: ErrorCallback; + 381?: ErrorCallback; + 382?: ErrorCallback; + 383?: ErrorCallback; + 384?: ErrorCallback; + 385?: ErrorCallback; + 386?: ErrorCallback; + 387?: ErrorCallback; + 388?: ErrorCallback; + 389?: ErrorCallback; + 390?: ErrorCallback; + 391?: ErrorCallback; + 392?: ErrorCallback; + 393?: ErrorCallback; + 394?: ErrorCallback; + 395?: ErrorCallback; + 396?: ErrorCallback; + 397?: ErrorCallback; + 398?: ErrorCallback; + 399?: ErrorCallback; + 400?: ErrorCallback; + 401?: ErrorCallback; + 402?: ErrorCallback; + 403?: ErrorCallback; + 404?: ErrorCallback; + 405?: ErrorCallback; + 406?: ErrorCallback; + 407?: ErrorCallback; + 408?: ErrorCallback; + 409?: ErrorCallback; + 410?: ErrorCallback; + 411?: ErrorCallback; + 412?: ErrorCallback; + 413?: ErrorCallback; + 414?: ErrorCallback; + 415?: ErrorCallback; + 416?: ErrorCallback; + 417?: ErrorCallback; + 418?: ErrorCallback; + 419?: ErrorCallback; + 420?: ErrorCallback; + 421?: ErrorCallback; + 422?: ErrorCallback; + 423?: ErrorCallback; + 424?: ErrorCallback; + 425?: ErrorCallback; + 426?: ErrorCallback; + 427?: ErrorCallback; + 428?: ErrorCallback; + 429?: ErrorCallback; + 430?: ErrorCallback; + 431?: ErrorCallback; + 432?: ErrorCallback; + 433?: ErrorCallback; + 434?: ErrorCallback; + 435?: ErrorCallback; + 436?: ErrorCallback; + 437?: ErrorCallback; + 438?: ErrorCallback; + 439?: ErrorCallback; + 440?: ErrorCallback; + 441?: ErrorCallback; + 442?: ErrorCallback; + 443?: ErrorCallback; + 444?: ErrorCallback; + 445?: ErrorCallback; + 446?: ErrorCallback; + 447?: ErrorCallback; + 448?: ErrorCallback; + 449?: ErrorCallback; + 450?: ErrorCallback; + 451?: ErrorCallback; + 452?: ErrorCallback; + 453?: ErrorCallback; + 454?: ErrorCallback; + 455?: ErrorCallback; + 456?: ErrorCallback; + 457?: ErrorCallback; + 458?: ErrorCallback; + 459?: ErrorCallback; + 460?: ErrorCallback; + 461?: ErrorCallback; + 462?: ErrorCallback; + 463?: ErrorCallback; + 464?: ErrorCallback; + 465?: ErrorCallback; + 466?: ErrorCallback; + 467?: ErrorCallback; + 468?: ErrorCallback; + 469?: ErrorCallback; + 470?: ErrorCallback; + 471?: ErrorCallback; + 472?: ErrorCallback; + 473?: ErrorCallback; + 474?: ErrorCallback; + 475?: ErrorCallback; + 476?: ErrorCallback; + 477?: ErrorCallback; + 478?: ErrorCallback; + 479?: ErrorCallback; + 480?: ErrorCallback; + 481?: ErrorCallback; + 482?: ErrorCallback; + 483?: ErrorCallback; + 484?: ErrorCallback; + 485?: ErrorCallback; + 486?: ErrorCallback; + 487?: ErrorCallback; + 488?: ErrorCallback; + 489?: ErrorCallback; + 490?: ErrorCallback; + 491?: ErrorCallback; + 492?: ErrorCallback; + 493?: ErrorCallback; + 494?: ErrorCallback; + 495?: ErrorCallback; + 496?: ErrorCallback; + 497?: ErrorCallback; + 498?: ErrorCallback; + 499?: ErrorCallback; + 500?: ErrorCallback; + 501?: ErrorCallback; + 502?: ErrorCallback; + 503?: ErrorCallback; + 504?: ErrorCallback; + 505?: ErrorCallback; + 506?: ErrorCallback; + 507?: ErrorCallback; + 508?: ErrorCallback; + 509?: ErrorCallback; + 510?: ErrorCallback; + 511?: ErrorCallback; + 512?: ErrorCallback; + 513?: ErrorCallback; + 514?: ErrorCallback; + 515?: ErrorCallback; + 516?: ErrorCallback; + 517?: ErrorCallback; + 518?: ErrorCallback; + 519?: ErrorCallback; + 520?: ErrorCallback; + 521?: ErrorCallback; + 522?: ErrorCallback; + 523?: ErrorCallback; + 524?: ErrorCallback; + 525?: ErrorCallback; + 526?: ErrorCallback; + 527?: ErrorCallback; + 528?: ErrorCallback; + 529?: ErrorCallback; + 530?: ErrorCallback; + 531?: ErrorCallback; + 532?: ErrorCallback; + 533?: ErrorCallback; + 534?: ErrorCallback; + 535?: ErrorCallback; + 536?: ErrorCallback; + 537?: ErrorCallback; + 538?: ErrorCallback; + 539?: ErrorCallback; + 540?: ErrorCallback; + 541?: ErrorCallback; + 542?: ErrorCallback; + 543?: ErrorCallback; + 544?: ErrorCallback; + 545?: ErrorCallback; + 546?: ErrorCallback; + 547?: ErrorCallback; + 548?: ErrorCallback; + 549?: ErrorCallback; + 550?: ErrorCallback; + 551?: ErrorCallback; + 552?: ErrorCallback; + 553?: ErrorCallback; + 554?: ErrorCallback; + 555?: ErrorCallback; + 556?: ErrorCallback; + 557?: ErrorCallback; + 558?: ErrorCallback; + 559?: ErrorCallback; + 560?: ErrorCallback; + 561?: ErrorCallback; + 562?: ErrorCallback; + 563?: ErrorCallback; + 564?: ErrorCallback; + 565?: ErrorCallback; + 566?: ErrorCallback; + 567?: ErrorCallback; + 568?: ErrorCallback; + 569?: ErrorCallback; + 570?: ErrorCallback; + 571?: ErrorCallback; + 572?: ErrorCallback; + 573?: ErrorCallback; + 574?: ErrorCallback; + 575?: ErrorCallback; + 576?: ErrorCallback; + 577?: ErrorCallback; + 578?: ErrorCallback; + 579?: ErrorCallback; + 580?: ErrorCallback; + 581?: ErrorCallback; + 582?: ErrorCallback; + 583?: ErrorCallback; + 584?: ErrorCallback; + 585?: ErrorCallback; + 586?: ErrorCallback; + 587?: ErrorCallback; + 588?: ErrorCallback; + 589?: ErrorCallback; + 590?: ErrorCallback; + 591?: ErrorCallback; + 592?: ErrorCallback; + 593?: ErrorCallback; + 594?: ErrorCallback; + 595?: ErrorCallback; + 596?: ErrorCallback; + 597?: ErrorCallback; + 598?: ErrorCallback; + 599?: ErrorCallback; + + // #endregion + } & { + // Status codes not listed require type annotations when defining the callback + [index: number]: SuccessCallback | ErrorCallback; + }; + + // #endregion + + // Writable properties on XMLHttpRequest + interface XHRFields extends Partial> { + msCaching?: string; + } + } + + interface Transport { + send(headers: PlainObject, completeCallback: Transport.SuccessCallback): void; + abort(): void; + } + + namespace Transport { + type SuccessCallback = (status: number, statusText: Ajax.TextStatus, responses?: PlainObject, headers?: string) => void; + } + + /** + * @see \`{@link https://api.jquery.com/jquery.ajax/#jqXHR }\` + */ + interface jqXHR extends Promise3, never, + Ajax.SuccessTextStatus, Ajax.ErrorTextStatus, never, + jqXHR, string, never>, + Pick, + Partial> { + responseJSON?: any; + + /** + * Determine the current state of a Deferred object. + * @see \`{@link https://api.jquery.com/deferred.state/ }\` + * @since 1.7 + */ + state(): 'pending' | 'resolved' | 'rejected'; + statusCode(map: Ajax.StatusCodeCallbacks): void; + } + + namespace jqXHR { + interface DoneCallback> extends Deferred.Callback3 { } + + interface FailCallback extends Deferred.Callback3 { } + + interface AlwaysCallback> extends Deferred.Callback3 { } + } + + // #endregion + + // region Callbacks + // #region Callbacks + + interface CallbacksStatic { + /** + * A multi-purpose callbacks list object that provides a powerful way to manage callback lists. + * @param flags An optional list of space-separated flags that change how the callback list behaves. + * @see \`{@link https://api.jquery.com/jQuery.Callbacks/ }\` + * @since 1.7 + */ + // tslint:disable-next-line:ban-types callable-types no-unnecessary-generics + (flags?: string): Callbacks; + } + + // tslint:disable-next-line:ban-types + interface Callbacks { + /** + * Add a callback or a collection of callbacks to a callback list. + * @param callback A function, or array of functions, that are to be added to the callback list. + * @param callbacks A function, or array of functions, that are to be added to the callback list. + * @see \`{@link https://api.jquery.com/callbacks.add/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.add() to add new callbacks to a callback list: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo: " + value ); +}; +​ +// Another function to also be added to the list +var bar = function( value ) { + console.log( "bar: " + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the function "foo" to the list +callbacks.add( foo ); +​ +// Fire the items on the list +callbacks.fire( "hello" ); +// Outputs: "foo: hello" +​ +// Add the function "bar" to the list +callbacks.add( bar ); +​ +// Fire the items on the list again +callbacks.fire( "world" ); +​ +// Outputs: +// "foo: world" +// "bar: world" +``` + */ + add(callback: TypeOrArray, ...callbacks: Array>): this; + /** + * Disable a callback list from doing anything more. + * @see \`{@link https://api.jquery.com/callbacks.disable/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.disable() to disable further calls to a callback list: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the above function to the list +callbacks.add( foo ); +​ +// Fire the items on the list +callbacks.fire( "foo" ); +// Outputs: foo +​ +// Disable further calls being possible +callbacks.disable(); +​ +// Attempt to fire with "foobar" as an argument +callbacks.fire( "foobar" ); +// foobar isn't output +``` + */ + disable(): this; + /** + * Determine if the callbacks list has been disabled. + * @see \`{@link https://api.jquery.com/callbacks.disabled/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.disabled() to determine if the callbacks list has been disabled: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo:" + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the logging function to the callback list +callbacks.add( foo ); +​ +// Fire the items on the list, passing an argument +callbacks.fire( "hello" ); +// Outputs "foo: hello" +​ +// Disable the callbacks list +callbacks.disable(); +​ +// Test the disabled state of the list +console.log ( callbacks.disabled() ); +// Outputs: true +``` + */ + disabled(): boolean; + /** + * Remove all of the callbacks from a list. + * @see \`{@link https://api.jquery.com/callbacks.empty/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.empty() to empty a list of callbacks: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value1, value2 ) { + console.log( "foo: " + value1 + "," + value2 ); +}; +​ +// Another function to also be added to the list +var bar = function( value1, value2 ) { + console.log( "bar: " + value1 + "," + value2 ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the two functions +callbacks.add( foo ); +callbacks.add( bar ); +​ +// Empty the callbacks list +callbacks.empty(); +​ +// Check to ensure all callbacks have been removed +console.log( callbacks.has( foo ) ); +// false +console.log( callbacks.has( bar ) ); +// false +``` + */ + empty(): this; + /** + * Call all of the callbacks with the given arguments. + * @param args The argument or list of arguments to pass back to the callback list. + * @see \`{@link https://api.jquery.com/callbacks.fire/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.fire() to invoke the callbacks in a list with any arguments that have been passed: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo:" + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the function "foo" to the list +callbacks.add( foo ); +​ +// Fire the items on the list +callbacks.fire( "hello" ); // Outputs: "foo: hello" +callbacks.fire( "world" ); // Outputs: "foo: world" +​ +// Add another function to the list +var bar = function( value ){ + console.log( "bar:" + value ); +}; +​ +// Add this function to the list +callbacks.add( bar ); +​ +// Fire the items on the list again +callbacks.fire( "hello again" ); +// Outputs: +// "foo: hello again" +// "bar: hello again" +``` + */ + fire(...args: any[]): this; + /** + * Determine if the callbacks have already been called at least once. + * @see \`{@link https://api.jquery.com/callbacks.fired/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.fired() to determine if the callbacks in a list have been called at least once: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo:" + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the function "foo" to the list +callbacks.add( foo ); +​ +// Fire the items on the list +callbacks.fire( "hello" ); // Outputs: "foo: hello" +callbacks.fire( "world" ); // Outputs: "foo: world" +​ +// Test to establish if the callbacks have been called +console.log( callbacks.fired() ); +``` + */ + fired(): boolean; + /** + * Call all callbacks in a list with the given context and arguments. + * @param context A reference to the context in which the callbacks in the list should be fired. + * @param args An argument, or array of arguments, to pass to the callbacks in the list. + * @see \`{@link https://api.jquery.com/callbacks.fireWith/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.fireWith() to fire a list of callbacks with a specific context and an array of arguments: +```javascript +// A sample logging function to be added to a callbacks list +var log = function( value1, value2 ) { + console.log( "Received: " + value1 + "," + value2 ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the log method to the callbacks list +callbacks.add( log ); +​ +// Fire the callbacks on the list using the context "window" +// and an arguments array +​ +callbacks.fireWith( window, [ "foo","bar" ] ); +// Outputs: "Received: foo, bar" +``` + */ + fireWith(context: object, args?: ArrayLike): this; + /** + * Determine whether or not the list has any callbacks attached. If a callback is provided as an argument, determine whether it is in a list. + * @param callback The callback to search for. + * @see \`{@link https://api.jquery.com/callbacks.has/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.has() to check if a callback list contains a specific callback: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value1, value2 ) { + console.log( "Received: " + value1 + "," + value2 ); +}; +​ +// A second function which will not be added to the list +var bar = function( value1, value2 ) { + console.log( "foobar" ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the log method to the callbacks list +callbacks.add( foo ); +​ +// Determine which callbacks are in the list +console.log( callbacks.has( foo ) ); +// true +console.log( callbacks.has( bar ) ); +// false +``` + */ + has(callback?: T): boolean; + /** + * Lock a callback list in its current state. + * @see \`{@link https://api.jquery.com/callbacks.lock/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.lock() to lock a callback list to avoid further changes being made to the list state: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo:" + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the logging function to the callback list +callbacks.add( foo ); +​ +// Fire the items on the list, passing an argument +callbacks.fire( "hello" ); +// Outputs "foo: hello" +​ +// Lock the callbacks list +callbacks.lock(); +​ +// Try firing the items again +callbacks.fire( "world" ); +​ +// As the list was locked, no items were called, +// so "world" isn't logged +``` + * @example ​ ````Use callbacks.lock() to lock a callback list with "memory," and then resume using the list: +```html + + + + + callbacks.lock demo + + + +​ +
          +​ + +​ + + +``` + */ + lock(): this; + /** + * Determine if the callbacks list has been locked. + * @see \`{@link https://api.jquery.com/callbacks.locked/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.locked() to determine the lock-state of a callback list: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo: " + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the logging function to the callback list +callbacks.add( foo ); +​ +// Fire the items on the list, passing an argument +callbacks.fire( "hello" ); +// Outputs "foo: hello" +​ +// Lock the callbacks list +callbacks.lock(); +​ +// Test the lock-state of the list +console.log ( callbacks.locked() ); +// true +``` + */ + locked(): boolean; + /** + * Remove a callback or a collection of callbacks from a callback list. + * @param callbacks A function, or array of functions, that are to be removed from the callback list. + * @see \`{@link https://api.jquery.com/callbacks.remove/ }\` + * @since 1.7 + * @example ​ ````Use callbacks.remove() to remove callbacks from a callback list: +```javascript +// A sample logging function to be added to a callbacks list +var foo = function( value ) { + console.log( "foo: " + value ); +}; +​ +var callbacks = $.Callbacks(); +​ +// Add the function "foo" to the list +callbacks.add( foo ); +​ +// Fire the items on the list +callbacks.fire( "hello" ); +// Outputs: "foo: hello" +​ +// Remove "foo" from the callback list +callbacks.remove( foo ); +​ +// Fire the items on the list again +callbacks.fire( "world" ); +​ +// Nothing output as "foo" is no longer in the list +``` + */ + remove(...callbacks: T[]): this; + } + + // #endregion + + // region CSS hooks + // #region CSS hooks + + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type CSSHook = + Partial<_CSSHook> & ( + Pick<_CSSHook, 'get'> | + Pick<_CSSHook, 'set'> + ); + + interface _CSSHook { + get(elem: TElement, computed: any, extra: any): any; + set(elem: TElement, value: any): void; + } + + interface CSSHooks { + // Set to HTMLElement to minimize breaks but should probably be Element. + [propertyName: string]: CSSHook; + } + + // #endregion + + // region Deferred + // #region Deferred + + /** + * Any object that has a then method. + */ + interface Thenable extends PromiseLike { } + + // NOTE: This is a private copy of the global Promise interface. It is used by JQuery.PromiseBase to indicate compatibility with other Promise implementations. + // The global Promise interface cannot be used directly as it may be modified, as in the case of @types/bluebird-global. + /** + * Represents the completion of an asynchronous operation + */ + interface _Promise { + readonly [Symbol.toStringTag]: "Promise"; + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: any) => TResult2 | PromiseLike) | null): _Promise; + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onrejected?: ((reason: any) => TResult | PromiseLike) | null): _Promise; + } + + // Type parameter guide + // -------------------- + // Each type parameter represents a parameter in one of the three possible callbacks. + // + // The first letter indicates which position the parameter is in. + // + // T = A = 1st position + // U = B = 2nd position + // V = C = 3rd position + // S = R = rest position + // + // The second letter indicates which whether it is a [R]esolve, Re[J]ect, or [N]otify value. + // + // The third letter indicates whether the value is returned in the [D]one filter, [F]ail filter, or [P]rogress filter. + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * @see \`{@link https://api.jquery.com/Types/#Promise }\` + */ + interface PromiseBase extends _Promise, PromiseLike { + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + * @see \`{@link https://api.jquery.com/deferred.always/ }\` + * @since 1.6 + * @example ​ ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. +```javascript +$.get( "test.php" ).always(function() { + alert( "$.get completed with success or error callback arguments" ); +}); +``` + */ + always(alwaysCallback: TypeOrArray>, + ...alwaysCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is resolved. + * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + * @see \`{@link https://api.jquery.com/deferred.done/ }\` + * @since 1.5 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. +```javascript +$.get( "test.php" ).done(function() { + alert( "$.get succeeded" ); +}); +``` + * @example ​ ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions: +```html + + + + + deferred.done demo + + + +​ + +

          Ready...

          +​ + +​ + + +``` + */ + done(doneCallback: TypeOrArray>, + ...doneCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is rejected. + * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + * @see \`{@link https://api.jquery.com/deferred.fail/ }\` + * @since 1.5 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. +```javascript +$.get( "test.php" ) + .done(function() { + alert( "$.get succeeded" ); + }) + .fail(function() { + alert( "$.get failed!" ); + }); +``` + */ + fail(failCallback: TypeOrArray>, + ...failCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. + * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates + * progress notifications. + * @see \`{@link https://api.jquery.com/deferred.progress/ }\` + * @since 1.7 + */ + progress(progressCallback: TypeOrArray>, + ...progressCallbacks: Array>>): this; + /** + * Return a Deferred's Promise object. + * @param target Object onto which the promise methods have to be attached + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` + * @since 1.5 + * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. +```javascript +function asyncEvent() { + var dfd = jQuery.Deferred(); +​ + // Resolve after a random interval + setTimeout(function() { + dfd.resolve( "hurray" ); + }, Math.floor( 400 + Math.random() * 2000 ) ); +​ + // Reject after a random interval + setTimeout(function() { + dfd.reject( "sorry" ); + }, Math.floor( 400 + Math.random() * 2000 ) ); +​ + // Show a "working..." message every half-second + setTimeout(function working() { + if ( dfd.state() === "pending" ) { + dfd.notify( "working... " ); + setTimeout( working, 500 ); + } + }, 1 ); +​ + // Return the Promise so caller can't change the Deferred + return dfd.promise(); +} +​ +// Attach a done, fail, and progress handler for the asyncEvent +$.when( asyncEvent() ).then( + function( status ) { + alert( status + ", things are going well" ); + }, + function( status ) { + alert( status + ", you fail this time" ); + }, + function( status ) { + $( "body" ).append( status ); + } +); +``` + */ + promise(target: TTarget): this & TTarget; + /** + * Return a Deferred's Promise object. + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` + * @since 1.5 + * @example ​ ````Use the target argument to promote an existing object to a Promise: +```javascript +// Existing object +var obj = { + hello: function( name ) { + alert( "Hello " + name ); + } + }, + // Create a Deferred + defer = $.Deferred(); +​ +// Set object as a promise +defer.promise( obj ); +​ +// Resolve the deferred +defer.resolve( "John" ); +​ +// Use the object as a Promise +obj.done(function( name ) { + obj.hello( name ); // Will alert "Hello John" +}).hello( "Karl" ); // Will alert "Hello Karl" +``` + */ + promise(): this; + /** + * Determine the current state of a Deferred object. + * @see \`{@link https://api.jquery.com/deferred.state/ }\` + * @since 1.7 + */ + state(): 'pending' | 'resolved' | 'rejected'; + + // region pipe + // #region pipe + + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: null, + progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; + + // #endregion + + // region then + // #region then + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. +```javascript +$.get( "test.php" ).then( + function() { + alert( "$.get succeeded" ); + }, function() { + alert( "$.get failed!" ); + } +); +``` + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: null, + progressFilter?: (t: TN, u: UN, v: VN, ...s: SN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. +```javascript +$.get( "test.php" ).then( + function() { + alert( "$.get succeeded" ); + }, function() { + alert( "$.get failed!" ); + } +); +``` + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: (t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (t: TR, u: UR, v: VR, ...s: SR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; + + // #endregion + + /** + * Add handlers to be called when the Deferred object is rejected. + * @param failFilter A function that is called when the Deferred is rejected. + * @see \`{@link https://api.jquery.com/deferred.catch/ }\` + * @since 3.0 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method. +```javascript +$.get( "test.php" ) + .then( function() { + alert( "$.get succeeded" ); + } ) + .catch( function() { + alert( "$.get failed!" ); + } ); +``` + */ + catch( + failFilter?: ((t: TJ, u: UJ, v: VJ, ...s: SJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; + } + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * @see \`{@link https://api.jquery.com/Types/#Promise }\` + */ + interface Promise3 extends PromiseBase { } + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * @see \`{@link https://api.jquery.com/Types/#Promise }\` + */ + interface Promise2 extends PromiseBase { } + + /** + * This object provides a subset of the methods of the Deferred object (then, done, fail, always, pipe, progress, state and promise) to prevent users from changing the state of the Deferred. + * @see \`{@link https://api.jquery.com/Types/#Promise }\` + */ + interface Promise extends PromiseBase { } + + interface DeferredStatic { + // https://jquery.com/upgrade-guide/3.0/#callback-exit + exceptionHook: any; + /** + * A factory function that returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. + * @param beforeStart A function that is called just before the constructor returns. + * @see \`{@link https://api.jquery.com/jQuery.Deferred/ }\` + * @since 1.5 + */ + (beforeStart?: (this: Deferred, deferred: Deferred) => void): Deferred; + } + + interface Deferred { + /** + * Call the progressCallbacks on a Deferred object with the given args. + * @param args Optional arguments that are passed to the progressCallbacks. + * @see \`{@link https://api.jquery.com/deferred.notify/ }\` + * @since 1.7 + */ + notify(...args: TN[]): this; + /** + * Call the progressCallbacks on a Deferred object with the given context and args. + * @param context Context passed to the progressCallbacks as the this object. + * @param args An optional array of arguments that are passed to the progressCallbacks. + * @see \`{@link https://api.jquery.com/deferred.notifyWith/ }\` + * @since 1.7 + */ + notifyWith(context: object, args?: ArrayLike): this; + /** + * Reject a Deferred object and call any failCallbacks with the given args. + * @param args Optional arguments that are passed to the failCallbacks. + * @see \`{@link https://api.jquery.com/deferred.reject/ }\` + * @since 1.5 + */ + reject(...args: TJ[]): this; + /** + * Reject a Deferred object and call any failCallbacks with the given context and args. + * @param context Context passed to the failCallbacks as the this object. + * @param args An optional array of arguments that are passed to the failCallbacks. + * @see \`{@link https://api.jquery.com/deferred.rejectWith/ }\` + * @since 1.5 + */ + rejectWith(context: object, args?: ArrayLike): this; + /** + * Resolve a Deferred object and call any doneCallbacks with the given args. + * @param args Optional arguments that are passed to the doneCallbacks. + * @see \`{@link https://api.jquery.com/deferred.resolve/ }\` + * @since 1.5 + */ + resolve(...args: TR[]): this; + /** + * Resolve a Deferred object and call any doneCallbacks with the given context and args. + * @param context Context passed to the doneCallbacks as the this object. + * @param args An optional array of arguments that are passed to the doneCallbacks. + * @see \`{@link https://api.jquery.com/deferred.resolveWith/ }\` + * @since 1.5 + */ + resolveWith(context: object, args?: ArrayLike): this; + + /** + * Add handlers to be called when the Deferred object is either resolved or rejected. + * @param alwaysCallback A function, or array of functions, that is called when the Deferred is resolved or rejected. + * @param alwaysCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved or rejected. + * @see \`{@link https://api.jquery.com/deferred.always/ }\` + * @since 1.6 + * @example ​ ````Since the jQuery.get() method returns a jqXHR object, which is derived from a Deferred object, we can attach a callback for both success and error using the deferred.always() method. +```javascript +$.get( "test.php" ).always(function() { + alert( "$.get completed with success or error callback arguments" ); +}); +``` + */ + always(alwaysCallback: TypeOrArray>, + ...alwaysCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is resolved. + * @param doneCallback A function, or array of functions, that are called when the Deferred is resolved. + * @param doneCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is resolved. + * @see \`{@link https://api.jquery.com/deferred.done/ }\` + * @since 1.5 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach a success callback using the .done() method. +```javascript +$.get( "test.php" ).done(function() { + alert( "$.get succeeded" ); +}); +``` + * @example ​ ````Resolve a Deferred object when the user clicks a button, triggering a number of callback functions: +```html + + + + + deferred.done demo + + + +​ + +

          Ready...

          +​ + +​ + + +``` + */ + done(doneCallback: TypeOrArray>, + ...doneCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object is rejected. + * @param failCallback A function, or array of functions, that are called when the Deferred is rejected. + * @param failCallbacks Optional additional functions, or arrays of functions, that are called when the Deferred is rejected. + * @see \`{@link https://api.jquery.com/deferred.fail/ }\` + * @since 1.5 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred, you can attach a success and failure callback using the deferred.done() and deferred.fail() methods. +```javascript +$.get( "test.php" ) + .done(function() { + alert( "$.get succeeded" ); + }) + .fail(function() { + alert( "$.get failed!" ); + }); +``` + */ + fail(failCallback: TypeOrArray>, + ...failCallbacks: Array>>): this; + /** + * Add handlers to be called when the Deferred object generates progress notifications. + * @param progressCallback A function, or array of functions, to be called when the Deferred generates progress notifications. + * @param progressCallbacks Optional additional functions, or arrays of functions, to be called when the Deferred generates + * progress notifications. + * @see \`{@link https://api.jquery.com/deferred.progress/ }\` + * @since 1.7 + */ + progress(progressCallback: TypeOrArray>, + ...progressCallbacks: Array>>): this; + /** + * Return a Deferred's Promise object. + * @param target Object onto which the promise methods have to be attached + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` + * @since 1.5 + * @example ​ ````Use the target argument to promote an existing object to a Promise: +```javascript +// Existing object +var obj = { + hello: function( name ) { + alert( "Hello " + name ); + } + }, + // Create a Deferred + defer = $.Deferred(); +​ +// Set object as a promise +defer.promise( obj ); +​ +// Resolve the deferred +defer.resolve( "John" ); +​ +// Use the object as a Promise +obj.done(function( name ) { + obj.hello( name ); // Will alert "Hello John" +}).hello( "Karl" ); // Will alert "Hello Karl" +``` + */ + promise(target: TTarget): Promise & TTarget; + /** + * Return a Deferred's Promise object. + * @see \`{@link https://api.jquery.com/deferred.promise/ }\` + * @since 1.5 + * @example ​ ````Create a Deferred and set two timer-based functions to either resolve or reject the Deferred after a random interval. Whichever one fires first "wins" and will call one of the callbacks. The second timeout has no effect since the Deferred is already complete (in a resolved or rejected state) from the first timeout action. Also set a timer-based progress notification function, and call a progress handler that adds "working..." to the document body. +```javascript +function asyncEvent() { + var dfd = jQuery.Deferred(); +​ + // Resolve after a random interval + setTimeout(function() { + dfd.resolve( "hurray" ); + }, Math.floor( 400 + Math.random() * 2000 ) ); +​ + // Reject after a random interval + setTimeout(function() { + dfd.reject( "sorry" ); + }, Math.floor( 400 + Math.random() * 2000 ) ); +​ + // Show a "working..." message every half-second + setTimeout(function working() { + if ( dfd.state() === "pending" ) { + dfd.notify( "working... " ); + setTimeout( working, 500 ); + } + }, 1 ); +​ + // Return the Promise so caller can't change the Deferred + return dfd.promise(); +} +​ +// Attach a done, fail, and progress handler for the asyncEvent +$.when( asyncEvent() ).then( + function( status ) { + alert( status + ", things are going well" ); + }, + function( status ) { + alert( status + ", you fail this time" ); + }, + function( status ) { + $( "body" ).append( status ); + } +); +``` + */ + promise(): Promise; + /** + * Determine the current state of a Deferred object. + * @see \`{@link https://api.jquery.com/deferred.state/ }\` + * @since 1.7 + */ + state(): 'pending' | 'resolved' | 'rejected'; + + // region pipe + // #region pipe + + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: null, + progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | AJF, + progressFilter?: null): PromiseBase; + /** + * Utility method to filter and/or chain Deferreds. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.pipe/ }\` + * @since 1.6 + * @since 1.7 + * @deprecated ​ Deprecated since 1.8. Use \`{@link then }\`. + * + * **Cause**: The `.pipe()` method on a `jQuery.Deferred` object was deprecated as of jQuery 1.8, when the `.then()` method was changed to perform the same function. + * + * **Solution**: In most cases it is sufficient to change all occurrences of `.pipe()` to `.then()`. Ensure that you aren't relying on context/state propagation (e.g., using `this`) or synchronous callback invocation, which were dropped from `.then()` for Promises/A+ interoperability as of jQuery 3.0. + * @example ​ ````Filter resolve value: +```javascript +var defer = $.Deferred(), + filtered = defer.pipe(function( value ) { + return value * 2; + }); +​ +defer.resolve( 5 ); +filtered.done(function( value ) { + alert( "Value is ( 2*5 = ) 10: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.pipe(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + pipe( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; + + // #endregion + + // region then + // #region then + + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. +```javascript +$.get( "test.php" ).then( + function() { + alert( "$.get succeeded" ); + }, function() { + alert( "$.get failed!" ); + } +); +``` + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: null, + progressFilter: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter A function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: null, + progressFilter?: (...t: TN[]) => PromiseBase | Thenable | ANP): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can attach handlers using the .then method. +```javascript +$.get( "test.php" ).then( + function() { + alert( "$.get succeeded" ); + }, function() { + alert( "$.get failed!" ); + } +); +``` + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter reject value: +```javascript +var defer = $.Deferred(), + filtered = defer.then( null, function( value ) { + return value * 3; + }); +​ +defer.reject( 6 ); +filtered.fail(function( value ) { + alert( "Value is ( 3*6 = ) 18: " + value ); +}); +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: null, + failFilter: (...t: TJ[]) => PromiseBase | Thenable | ARF, + progressFilter?: null): PromiseBase; + /** + * Add handlers to be called when the Deferred object is resolved, rejected, or still in progress. + * @param doneFilter An optional function that is called when the Deferred is resolved. + * @param failFilter An optional function that is called when the Deferred is rejected. + * @param progressFilter An optional function that is called when progress notifications are sent to the Deferred. + * @see \`{@link https://api.jquery.com/deferred.then/ }\` + * @since 1.8 + * @example ​ ````Filter the resolve value: +```html + + + + + deferred.then demo + + + +​ + +

          +​ + +​ + + +``` + * @example ​ ````Chain tasks: +```javascript +var request = $.ajax( url, { dataType: "json" } ), + chained = request.then(function( data ) { + return $.ajax( url2, { data: { user: data.userId } } ); + }); +​ +chained.done(function( data ) { + // data retrieved from url2 as provided by the first request +}); +``` + */ + then( + doneFilter: (...t: TR[]) => PromiseBase | Thenable | ARD, + failFilter?: null, + progressFilter?: null): PromiseBase; + + // #endregion + + /** + * Add handlers to be called when the Deferred object is rejected. + * @param failFilter A function that is called when the Deferred is rejected. + * @see \`{@link https://api.jquery.com/deferred.catch/ }\` + * @since 3.0 + * @example ​ ````Since the jQuery.get method returns a jqXHR object, which is derived from a Deferred object, we can rejection handlers using the .catch method. +```javascript +$.get( "test.php" ) + .then( function() { + alert( "$.get succeeded" ); + } ) + .catch( function() { + alert( "$.get failed!" ); + } ); +``` + */ + catch( + failFilter?: ((...t: TJ[]) => PromiseBase | Thenable | ARF) | null): PromiseBase; + } + + namespace Deferred { + type CallbackBase = (t: T, u: U, v: V, ...r: R[]) => void; + + interface Callback3 extends CallbackBase { } + + type Callback = (...args: T[]) => void; + + /** + * @deprecated ​ Deprecated. Use \`{@link Callback }\`. + */ + interface DoneCallback extends Callback { } + + /** + * @deprecated ​ Deprecated. Use \`{@link Callback }\`. + */ + interface FailCallback extends Callback { } + + /** + * @deprecated ​ Deprecated. Use \`{@link Callback }\`. + */ + interface AlwaysCallback extends Callback { } + + /** + * @deprecated ​ Deprecated. Use \`{@link Callback }\`. + */ + interface ProgressCallback extends Callback { } + } + + // #endregion + + // region Effects + // #region Effects + + type Duration = number | 'fast' | 'slow'; + + /** + * @see \`{@link https://api.jquery.com/animate/#animate-properties-options }\` + */ + interface EffectsOptions extends PlainObject { + /** + * A function to be called when the animation on an element completes or stops without completing (its Promise object is either resolved or rejected). + */ + always?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A function that is called once the animation on an element is complete. + */ + complete?(this: TElement): void; + /** + * A function to be called when the animation on an element completes (its Promise object is resolved). + */ + done?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A string or number determining how long the animation will run. + */ + duration?: Duration; + /** + * A string indicating which easing function to use for the transition. + */ + easing?: string; + /** + * A function to be called when the animation on an element fails to complete (its Promise object is rejected). + */ + fail?(this: TElement, animation: Animation, jumpedToEnd: boolean): void; + /** + * A function to be called after each step of the animation, only once per animated element regardless of the number of animated properties. + */ + progress?(this: TElement, animation: Animation, progress: number, remainingMs: number): void; + /** + * A Boolean indicating whether to place the animation in the effects queue. If false, the animation will begin immediately. As of jQuery 1.7, the queue option can also accept a string, in which case the animation is added to the queue represented by that string. When a custom queue name is used the animation does not automatically start; you must call .dequeue("queuename") to start it. + */ + queue?: boolean | string; + /** + * An object containing one or more of the CSS properties defined by the properties argument and their corresponding easing functions. + */ + specialEasing?: PlainObject; + /** + * A function to call when the animation on an element begins. + */ + start?(this: TElement, animation: Animation): void; + /** + * A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set. + */ + step?(this: TElement, now: number, tween: Tween): void; + } + + // region Animation + // #region Animation + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + interface AnimationStatic { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + (element: TElement, props: PlainObject, opts: EffectsOptions): Animation; + /** + * During the initial setup, `jQuery.Animation` will call any callbacks that have been registered through `jQuery.Animation.prefilter( function( element, props, opts ) )`. + * @param callback The prefilter will have `this` set to an animation object, and you can modify any of the `props` or + * `opts` however you need. The prefilter _may_ return its own promise which also implements `stop()`, + * in which case, processing of prefilters stops. If the prefilter is not trying to override the animation + * entirely, it should return `undefined` or some other falsy value. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#prefilters }\` + * @since 1.8 + */ + prefilter( + callback: (this: Animation, element: TElement, props: PlainObject, opts: EffectsOptions) => Animation | _Falsy | void, + prepend?: boolean + ): void; + /** + * A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property. + * + * You can override the default process for creating a tween in order to provide your own tween object by using `jQuery.Animation.tweener( props, callback( prop, value ) )`. + * @param props A space separated list of properties to be passed to your tweener, or `"*"` if it should be called + * for all properties. + * @param callback The callback will be called with `this` being an `Animation` object. The tweener function will + * generally start with `var tween = this.createTween( prop, value );`, but doesn't nessecarily need to + * use the `jQuery.Tween()` factory. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\` + * @since 1.8 + */ + tweener(props: string, callback: Tweener): void; + } + + /** + * The promise will be resolved when the animation reaches its end, and rejected when terminated early. The context of callbacks attached to the promise will be the element, and the arguments will be the `Animation` object and a boolean `jumpedToEnd` which when true means the animation was stopped with `gotoEnd`, when `undefined` the animation completed naturally. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + interface Animation extends Promise3< + Animation, Animation, Animation, + true | undefined, false, number, + never, never, number + > { + /** + * The duration specified in ms + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + duration: number; + /** + * The element being animatied + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + elem: TElement; + /** + * The final value of each property animating + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + props: PlainObject; + /** + * The animation options + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + opts: EffectsOptions; + /** + * The original properties before being filtered + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + originalProps: PlainObject; + /** + * The original options before being filtered + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + originalOpts: EffectsOptions; + /** + * The numeric value of `new Date()` when the animation began + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + startTime: number; + /** + * The animations tweens. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + tweens: Array>; + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + createTween(propName: string, finalValue: number): Tween; + /** + * Stops the animation early, optionally going to the end. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#animation-factory }\` + * @since 1.8 + */ + stop(gotoEnd: boolean): this; + } + + /** + * A "Tweener" is a function responsible for creating a tween object, and you might want to override these if you want to implement complex values ( like a clip/transform array matrix ) in a single property. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweeners }\` + * @since 1.8 + */ + type Tweener = (this: Animation, propName: string, finalValue: number) => Tween; + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + interface TweenStatic { + /** + * `jQuery.Tween.propHooks[ prop ]` is a hook point that replaces `jQuery.fx.step[ prop ]` (which is being deprecated.) These hooks are used by the tween to get and set values on elements. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + * @example +```javascript +jQuery.Tween.propHooks[ property ] = { + get: function( tween ) { + // get tween.prop from tween.elem and return it + }, + set: function( tween ) { + // set tween.prop on tween.elem to tween.now + tween.unit + } +} +``` + */ + propHooks: PropHooks; + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + (elem: TElement, options: EffectsOptions, prop: string, end: number, easing?: string, unit?: string): Tween; + } + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + // This should be a class but doesn't work correctly under the JQuery namespace. Tween should be an inner class of jQuery. + interface Tween { + /** + * The easing used + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + easing: string; + /** + * The element being animated + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + elem: TElement; + /** + * The ending value of the tween + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + end: number; + /** + * The current value of the tween + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + now: number; + /** + * A reference to the animation options + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + options: EffectsOptions; + // Undocumented. Is this intended to be public? + pos?: number; + /** + * The property being animated + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + prop: string; + /** + * The starting value of the tween + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + start: number; + /** + * The CSS unit for the tween + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + unit: string; + /** + * Reads the current value for property from the element + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + cur(): any; + /** + * Updates the value for the property on the animated elemd. + * @param progress A number from 0 to 1. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tweens }\` + * @since 1.8 + */ + run(progress: number): this; + } + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type PropHook = { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + get(tween: Tween): any; + } | { + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + set(tween: Tween): void; + } | { + [key: string]: never; + }; + + /** + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#tween-hooks }\` + * @since 1.8 + */ + interface PropHooks { + [property: string]: PropHook; + } + + // #endregion + + // region Easing + // #region Easing + + type EasingMethod = (percent: number) => number; + + interface Easings { + [name: string]: EasingMethod; + } + + // #endregion + + // region Effects (fx) + // #region Effects (fx) + + interface Effects { + /** + * The rate (in milliseconds) at which animations fire. + * @see \`{@link https://api.jquery.com/jQuery.fx.interval/ }\` + * @since 1.4.3 + * @deprecated ​ Deprecated since 3.0. See \`{@link https://api.jquery.com/jQuery.fx.interval/ }\`. + * + * **Cause**: As of jQuery 3.0 the `jQuery.fx.interval` property can be used to change the animation interval only on browsers that do not support the `window.requestAnimationFrame()` method. That is currently only Internet Explorer 9 and the Android Browser. Once support is dropped for these browsers, the property will serve no purpose and it will be removed. + * + * **Solution**: Find and remove code that changes or uses `jQuery.fx.interval`. If the value is being used by code in your page or a plugin, the code may be making assumptions that are no longer valid. The default value of `jQuery.fx.interval` is `13` (milliseconds), which could be used instead of accessing this property. + * @example ​ ````Cause all animations to run with less frames. +```html + + + + + jQuery.fx.interval demo + + + + +​ +

          +
          +​ + + + +``` + */ + interval: number; + /** + * Globally disable all animations. + * @see \`{@link https://api.jquery.com/jQuery.fx.off/ }\` + * @since 1.3 + * @example ​ ````Toggle animation on and off +```html + + + + + jQuery.fx.off demo + + + + +​ + + +
          +​ + + + +``` + */ + off: boolean; + /** + * @deprecated ​ Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`. + * + * `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook. + */ + step: PlainObject>; + /** + * _overridable_ Clears up the `setInterval` + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + stop(): void; + /** + * Calls `.run()` on each object in the `jQuery.timers` array, removing it from the array if `.run()` returns a falsy value. Calls `jQuery.fx.stop()` whenever there are no timers remaining. + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + tick(): void; + /** + * _overridable_ Creates a `setInterval` if one doesn't already exist, and pushes `tickFunction` to the `jQuery.timers` array. `tickFunction` should also have `anim`, `elem`, and `queue` properties that reference the animation object, animated element, and queue option to facilitate `jQuery.fn.stop()` + * + * By overriding `fx.timer` and `fx.stop` you should be able to implement any animation tick behaviour you desire. (like using `requestAnimationFrame` instead of `setTimeout`.) + * + * There is an example of overriding the timer loop in \`{@link https://github.com/gnarf37/jquery-requestAnimationFrame jquery.requestAnimationFrame}\` + * @see \`{@link https://gist.github.com/gnarf/54829d408993526fe475#plugging-in-a-different-timer-loop }\` + * @since 1.8 + */ + timer(tickFunction: TickFunction): void; + } + + /** + * @deprecated ​ Deprecated since 1.8. Use \`{@link Tween.propHooks jQuery.Tween.propHooks}\`. + * + * `jQuery.fx.step` functions are being replaced by `jQuery.Tween.propHooks` and may eventually be removed, but are still supported via the default tween propHook. + */ + type AnimationHook = (fx: Tween) => void; + + interface TickFunction { + anim: Animation; + elem: TElement; + queue: boolean | string; + (): any; + } + + // #endregion + + // region Queue + // #region Queue + + // TODO: Is the first element always a string or is that specific to the 'fx' queue? + type Queue = { 0: string; } & Array>; + + type QueueFunction = (this: TElement, next: () => void) => void; + + // #endregion + + // region Speed + // #region Speed + + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type SpeedSettings = { + /** + * A string or number determining how long the animation will run. + */ + duration: Duration; + } | { + /** + * A string indicating which easing function to use for the transition. + */ + easing: string; + } | { + /** + * A function to call once the animation is complete. + */ + complete(this: TElement): void; + } | { + [key: string]: never; + }; + + // #endregion + + // #endregion + + // region Events + // #region Events + + // region Event + // #region Event + + // This should be a class but doesn't work correctly under the JQuery namespace. Event should be an inner class of jQuery. + + /** + * 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 { + /** + * 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; + } + + /** + * 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 + + // Event + + bubbles: boolean | undefined; + cancelable: boolean | undefined; + eventPhase: number | undefined; + + // UIEvent + + detail: number | undefined; + view: Window | undefined; + + // MouseEvent + + 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/ }\` + * @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 | 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: number | undefined; + screenX: number | undefined; + screenY: number | undefined; + /** @deprecated */ + toElement: Element | undefined; + + // PointerEvent + + pointerId: number | undefined; + pointerType: string | undefined; + + // KeyboardEvent + + /** @deprecated */ + char: string | undefined; + /** @deprecated */ + charCode: number | undefined; + key: string | undefined; + /** @deprecated */ + keyCode: number | undefined; + + // TouchEvent + + changedTouches: TouchList | undefined; + targetTouches: TouchList | undefined; + touches: TouchList | 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 | undefined; + + // MouseEvent, KeyboardEvent, TouchEvent + + 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/ }\` + * @since 1.0.4 + * @example ​ ````Determine whether the META key was pressed when the event fired. +```html + + + + + event.metaKey demo + + + + +​ + +
          +​ + +​ + + +``` + */ + metaKey: boolean | undefined; + shiftKey: boolean | undefined; + + // #endregion + + /** + * The difference in milliseconds between the time the browser created the event and January 1, 1970. + * @see \`{@link https://api.jquery.com/event.timeStamp/ }\` + * @since 1.2.6 + * @example ​ ````Display the time since the click handler last executed. +```html + + + + + event.timeStamp demo + + + + +​ +
          Click.
          +​ + +​ + + +``` + */ + timeStamp: number; + /** + * Describes the nature of the event. + * @see \`{@link https://api.jquery.com/event.type/ }\` + * @since 1.0 + * @example ​ ````On all anchor clicks, alert the event type. +```javascript +$( "a" ).click(function( event ) { + alert( event.type ); // "click" +}); +``` + */ + type: string; + /** + * Returns whether event.preventDefault() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isDefaultPrevented/ }\` + * @since 1.3 + * @example ​ ````Checks whether event.preventDefault() was called. +```javascript +$( "a" ).click(function( event ) { + alert( event.isDefaultPrevented() ); // false + event.preventDefault(); + alert( event.isDefaultPrevented() ); // true +}); +``` + */ + isDefaultPrevented(): boolean; + /** + * Returns whether event.stopImmediatePropagation() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isImmediatePropagationStopped/ }\` + * @since 1.3 + * @example ​ ````Checks whether event.stopImmediatePropagation() was called. +```html + + + + + event.isImmediatePropagationStopped demo + + + +​ + +
          + ​ + +​ + + +``` + */ + isImmediatePropagationStopped(): boolean; + /** + * Returns whether event.stopPropagation() was ever called on this event object. + * @see \`{@link https://api.jquery.com/event.isPropagationStopped/ }\` + * @since 1.3 + * @example ​ ````Checks whether event.stopPropagation() was called +```html + + + + + event.isPropagationStopped demo + + + +​ + +
          + ​ + +​ + + +``` + */ + isPropagationStopped(): boolean; + /** + * If this method is called, the default action of the event will not be triggered. + * @see \`{@link https://api.jquery.com/event.preventDefault/ }\` + * @since 1.0 + * @example ​ ````Cancel the default action (navigation) of the click. +```html + + + + + event.preventDefault demo + + + +​ +default click action is prevented +
          +​ + +​ + + +``` + */ + preventDefault(): void; + /** + * Keeps the rest of the handlers from being executed and prevents the event from bubbling up the DOM tree. + * @see \`{@link https://api.jquery.com/event.stopImmediatePropagation/ }\` + * @since 1.3 + * @example ​ ````Prevents other event handlers from being called. +```html + + + + + event.stopImmediatePropagation demo + + + + +​ +

          paragraph

          +
          division
          +​ + +​ + + +``` + */ + stopImmediatePropagation(): void; + /** + * Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. + * @see \`{@link https://api.jquery.com/event.stopPropagation/ }\` + * @since 1.0 + * @example ​ ````Kill the bubbling on the click event. +```javascript +$( "p" ).click(function( event ) { + event.stopPropagation(); + // Do something +}); +``` + */ + stopPropagation(): void; + } + + // #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/ }\` + * @since 1.3 + * @example ​ ````Alert that currentTarget matches the `this` keyword. +```javascript +$( "p" ).click(function( event ) { + alert( event.currentTarget === this ); // true +}); +``` + */ + currentTarget: TCurrentTarget; + /** + * The element where the currently-called jQuery event handler was attached. + * @see \`{@link https://api.jquery.com/event.delegateTarget/ }\` + * @since 1.7 + * @example ​ ````When a button in any box class is clicked, change the box's background color to red. +```javascript +$( ".box" ).on( "click", "button", function( event ) { + $( event.delegateTarget ).css( "background-color", "red" ); +}); +``` + */ + delegateTarget: TDelegateTarget; + /** + * The DOM element that initiated the event. + * @see \`{@link https://api.jquery.com/event.target/ }\` + * @since 1.0 + * @example ​ ````Display the tag's name on click +```html + + + + + event.target demo + + + + +​ +
          +
          +

          + click +

          +
          +​ + +​ + + +``` + * @example ​ ````Implements a simple event delegation: The click handler is added to an unordered list, and the children of its li children are hidden. Clicking one of the li children toggles (see toggle()) their children. +```html + + + + + event.target demo + + + +​ +
            +
          • item 1 +
              +
            • sub item 1-a
            • +
            • sub item 1-b
            • +
            +
          • +
          • item 2 +
              +
            • sub item 2-a
            • +
            • sub item 2-b
            • +
            +
          • +
          +​ + +​ + + +``` + */ + 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; + } + + // 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 + + // 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 { + /** + * 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. + * + * As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated pieces of code want to process the same event name. Special event authors who need to modify events with existing hooks will need to take precautions to avoid introducing unwanted side-effects by clobbering those hooks. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\` + */ + special: SpecialEventHooks; + } + + // region Special event hooks + // #region Special event hooks + + /** + * 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. + * + * As with `fixHooks`, the special event hooks design assumes it will be very rare that two unrelated pieces of code want to process the same event name. Special event authors who need to modify events with existing hooks will need to take precautions to avoid introducing unwanted side-effects by clobbering those hooks. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#special-event-hooks }\` + */ + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type SpecialEventHook = { + /** + * Indicates whether this event type should be bubbled when the `.trigger()` method is called; by default it is `false`, meaning that a triggered event will bubble to the element's parents up to the document (if attached to a document) and then to the window. Note that defining `noBubble` on an event will effectively prevent that event from being used for delegated events with `.trigger()`. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#nobubble-boolean }\` + */ + noBubble: boolean; + } | { + /** + * When defined, these string properties specify that a special event should be handled like another event type until the event is delivered. The `bindType` is used if the event is attached directly, and the `delegateType` is used for delegated events. These types are generally DOM event types, and _should not_ be a special event themselves. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\` + */ + bindType: string; + } | { + /** + * When defined, these string properties specify that a special event should be handled like another event type until the event is delivered. The `bindType` is used if the event is attached directly, and the `delegateType` is used for delegated events. These types are generally DOM event types, and _should not_ be a special event themselves. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#bindtype-string-delegatetype-string }\` + */ + delegateType: string; + } | { + /** + * The setup hook is called the first time an event of a particular type is attached to an element; this provides the hook an opportunity to do processing that will apply to all events of this type on this element. The `this` keyword will be a reference to the element where the event is being attached and `eventHandle` is jQuery's event handler function. In most cases the `namespaces` argument should not be used, since it only represents the namespaces of the _first_ event being attached; subsequent events may not have this same namespaces. + * + * This hook can perform whatever processing it desires, including attaching its own event handlers to the element or to other elements and recording setup information on the element using the `jQuery.data()` method. If the setup hook wants jQuery to add a browser event (via `addEventListener` or `attachEvent`, depending on browser) it should return `false`. In all other cases, jQuery will not add the browser event, but will continue all its other bookkeeping for the event. This would be appropriate, for example, if the event was never fired by the browser but invoked by `.trigger()`. To attach the jQuery event handler in the setup hook, use the `eventHandle` argument. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#setup-function-data-object-namespaces-eventhandle-function }\` + */ + setup(this: TTarget, data: TData, namespaces: string, eventHandle: EventHandler): void | false; + } | { + /** + * The teardown hook is called when the final event of a particular type is removed from an element. The `this` keyword will be a reference to the element where the event is being cleaned up. This hook should return `false` if it wants jQuery to remove the event from the browser's event system (via `removeEventListener` or `detachEvent`). In most cases, the setup and teardown hooks should return the same value. + * + * If the setup hook attached event handlers or added data to an element through a mechanism such as `jQuery.data()`, the teardown hook should reverse the process and remove them. jQuery will generally remove the data and events when an element is totally removed from the document, but failing to remove data or events on teardown will cause a memory leak if the element stays in the document. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#teardown-function }\` + */ + teardown(this: TTarget): void | false; + } | { + /** + * Each time an event handler is added to an element through an API such as `.on()`, jQuery calls this hook. The `this` keyword will be the element to which the event handler is being added, and the `handleObj` argument is as described in the section above. The return value of this hook is ignored. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#add-function-handleobj }\` + */ + add(this: TTarget, handleObj: HandleObject): void; + } | { + /** + * When an event handler is removed from an element using an API such as `.off()`, this hook is called. The `this` keyword will be the element where the handler is being removed, and the `handleObj` argument is as described in the section above. The return value of this hook is ignored. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#remove-function-handleobj }\` + */ + remove(this: TTarget, handleObj: HandleObject): void; + } | { + /** + * Called when the `.trigger()` or `.triggerHandler()` methods are used to trigger an event for the special type from code, as opposed to events that originate from within the browser. The `this` keyword will be the element being triggered, and the event argument will be a `jQuery.Event` object constructed from the caller's input. At minimum, the event type, data, namespace, and target properties are set on the event. The data argument represents additional data passed by `.trigger()` if present. + * + * 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; + } | { + /** + * 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: 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. + * + * 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: TriggeredEvent & { handleObj: HandleObject; }, ...data: TData[]): void; + } | { + preDispatch(this: TTarget, event: Event): false | void; + } | { + postDispatch(this: TTarget, event: Event): void; + } | { + [key: string]: never; + }; + + interface SpecialEventHooks { + [event: string]: SpecialEventHook; + } + + /** + * Many of the special event hook functions below are passed a `handleObj` object that provides more information about the event, how it was attached, and its current state. This object and its contents should be treated as read-only data, and only the properties below are documented for use by special event handlers. + * @see \`{@link https://learn.jquery.com/events/event-extensions/#the-handleobj-object }\` + */ + interface HandleObject { + /** + * The type of event, such as `"click"`. When special event mapping is used via `bindType` or `delegateType`, this will be the mapped type. + */ + readonly type: string; + /** + * The original type name regardless of whether it was mapped via `bindType` or `delegateType`. So when a "pushy" event is mapped to "click" its `origType` would be "pushy". + */ + readonly origType: string; + /** + * Namespace(s), if any, provided when the event was attached, such as `"myPlugin"`. When multiple namespaces are given, they are separated by periods and sorted in ascending alphabetical order. If no namespaces are provided, this property is an empty string. + */ + readonly namespace: string; + /** + * For delegated events, this is the selector used to filter descendant elements and determine if the handler should be called. For directly bound events, this property is `null`. + */ + readonly selector: string | undefined | null; + /** + * The data, if any, passed to jQuery during event binding, e.g. `{ myData: 42 }`. If the data argument was omitted or `undefined`, this property is `undefined` as well. + */ + readonly data: TData; + /** + * Event handler function passed to jQuery during event binding. If `false` was passed during event binding, the handler refers to a single shared function that simply returns `false`. + */ + readonly handler: EventHandler; + } + + // #endregion + + // #endregion + + // #endregion + + interface NameValuePair { + name: string; + value: string; + } + + // region Coordinates + // #region Coordinates + + interface Coordinates { + left: number; + top: number; + } + + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type CoordinatesPartial = + Pick | + Pick | + { [key: string]: never; }; + + // #endregion + + // region Val hooks + // #region Val hooks + + // Workaround for TypeScript 2.3 which does not have support for weak types handling. + type ValHook = { + get(elem: TElement): any; + } | { + set(elem: TElement, value: any): any; + } | { + [key: string]: never; + }; + + interface ValHooks { + // Set to HTMLElement to minimize breaks but should probably be Element. + [nodeName: string]: ValHook; + } + + // #endregion + + type _Falsy = false | null | undefined | 0 | '' | typeof document.all; +} + +declare const jQuery: JQueryStatic; +declare const $: JQueryStatic; + +type _Event = Event; +type _UIEvent = UIEvent; +type _MouseEvent = MouseEvent; +type _KeyboardEvent = KeyboardEvent; +type _TouchEvent = TouchEvent; +type _FocusEvent = FocusEvent; + +// region ES5 compatibility +// #region ES5 compatibility + +// Forward declaration of `Iterable`. +// tslint:disable-next-line:no-empty-interface +interface Iterable { } + +interface SymbolConstructor { + /** + * A String value that is used in the creation of the default string description of an object. + * Called by the built-in method Object.prototype.toString. + */ + readonly toStringTag: symbol; +} + +declare var Symbol: SymbolConstructor; + +// #endregion diff --git a/types/jquery/test/example-tests.ts b/types/jquery/test/example-tests.ts index 60fbd431bb..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(); @@ -2334,7 +2334,9 @@ function examples() { } function jQuery_contains_0() { + // tslint:disable-next-line no-unnecessary-type-assertion $.contains(document.documentElement!, document.body); // true + // tslint:disable-next-line no-unnecessary-type-assertion $.contains(document.body, document.documentElement!); // false } @@ -3016,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 @@ -3031,7 +3033,7 @@ function examples() { var you = { type: 'person', - test: function(event: JQuery.Event) { + test: function(event: JQuery.TriggeredEvent) { $('#log').append(this.type + ' '); }, }; @@ -3073,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 @@ -3794,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 ef52084da5..b1a0353b4e 100644 --- a/types/jquery/test/learn-tests.ts +++ b/types/jquery/test/learn-tests.ts @@ -7,7 +7,8 @@ interface JQuery { } interface GreenifyPlugin { - (this: JQuery): void; + // tslint:disable-next-line:callable-types + (this: JQuery): void; } jQuery.fn.greenify = function() { @@ -15,3 +16,45 @@ jQuery.fn.greenify = function() { }; jQuery("a").greenify(); // Makes all the links green. + +// https://learn.jquery.com/events/event-extensions/ + +// Events + +function special() { + function defineSpecialEvent() { + jQuery.event.special.pushy = { + bindType: "click", + delegateType: "click" + }; + } + + function handleObj() { + jQuery.event.special.multiclick = { + delegateType: "click", + bindType: "click", + handle(event) { + const handleObj = event.handleObj; + const targetData = jQuery.data(event.target as Element); + let ret = null; + + // If a multiple of the click count, run the handler + targetData.clicks = (targetData.clicks || 0) + 1; + + if (targetData.clicks % event.data.clicks === 0) { + event.type = handleObj.origType; + ret = handleObj.handler.apply(this, arguments); + event.type = handleObj.type; + return ret; + } + } + }; + + // Sample usage + $("p").on("multiclick", { + clicks: 3 + }, () => { + alert("clicked 3 times"); + }); + } +} diff --git a/types/jquery/test/longdesc-tests.ts b/types/jquery/test/longdesc-tests.ts index 4390ae014a..e1ee36a575 100644 --- a/types/jquery/test/longdesc-tests.ts +++ b/types/jquery/test/longdesc-tests.ts @@ -1,3 +1,4 @@ +// tslint:disable:ban-types // tslint:disable:no-var-keyword // tslint:disable:object-literal-key-quotes // tslint:disable:object-literal-shorthand @@ -537,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+ @@ -885,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(); } @@ -951,8 +952,10 @@ function longdesc() { function jquery_ajax_transport_2() { $.ajaxTransport('script', function(options, originalOptions, jqXHR) { + let transport: JQuery.Transport = undefined!; + // Will only be called for script requests - return {} as JQuery.Transport; + return transport; }); } @@ -1294,7 +1297,7 @@ function longdesc() { return $.css(elem, borderRadius!); }, set: function(elem, value) { - ( elem.style)[borderRadius!] = value; + (elem.style as any)[borderRadius!] = value; }, }; } @@ -1341,7 +1344,7 @@ function longdesc() { function jquery_css_hooks_6() { $.fx.step.someCSSProp = function(fx) { - $.cssHooks.someCSSProp.set(fx.elem as HTMLElement, fx.now + fx.unit); + $.cssHooks.someCSSProp.set!(fx.elem as HTMLElement, fx.now + fx.unit); }; } @@ -2013,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/jquery/tsconfig.json b/types/jquery/tsconfig.json index 86c99c452f..8b159bc81f 100644 --- a/types/jquery/tsconfig.json +++ b/types/jquery/tsconfig.json @@ -20,6 +20,7 @@ }, "files": [ "index.d.ts", + "dist/jquery.slim.d.ts", "jquery-tests.ts", "test/example-tests.ts", "test/longdesc-tests.ts", diff --git a/types/jquery/tslint.json b/types/jquery/tslint.json index 93e1f3e072..f93cf8562a 100644 --- a/types/jquery/tslint.json +++ b/types/jquery/tslint.json @@ -1,12 +1,3 @@ { - "extends": "dtslint/dt.json", - "rules": { - "callable-types": false, - "interface-name": false, - "no-any-union": false, - "no-declare-current-package": false, - - "ban-types": false, - "no-object-literal-type-assertion": false - } + "extends": "dtslint/dt.json" } diff --git a/types/jquery/v1/jquery-tests.ts b/types/jquery/v1/jquery-tests.ts index d00c075125..bb13b8c215 100644 --- a/types/jquery/v1/jquery-tests.ts +++ b/types/jquery/v1/jquery-tests.ts @@ -2715,7 +2715,7 @@ function test_fn_extend() { } function test_jquery() { - var a = { what: "A regular JS object" }, + var a: any = { what: "A regular JS object" }, b = $('body'); if (a.jquery) { alert(' a is a jQuery object! '); diff --git a/types/jquery/v2/jquery-tests.ts b/types/jquery/v2/jquery-tests.ts index fa651a196f..01a06c62a8 100644 --- a/types/jquery/v2/jquery-tests.ts +++ b/types/jquery/v2/jquery-tests.ts @@ -2715,7 +2715,7 @@ function test_fn_extend() { } function test_jquery() { - var a = { what: "A regular JS object" }, + var a: any = { what: "A regular JS object" }, b = $('body'); if (a.jquery) { alert(' a is a jQuery object! '); diff --git a/types/jqueryui/index.d.ts b/types/jqueryui/index.d.ts index 7092de2d06..cc164360c0 100644 --- a/types/jqueryui/index.d.ts +++ b/types/jqueryui/index.d.ts @@ -1857,7 +1857,9 @@ interface JQuery { tabs(): JQuery; tabs(methodName: 'destroy'): void; tabs(methodName: 'disable'): void; + tabs(methodName: 'disable', index: number): void; tabs(methodName: 'enable'): void; + tabs(methodName: 'enable', index: number): void; tabs(methodName: 'load', index: number): void; tabs(methodName: 'refresh'): void; tabs(methodName: 'widget'): JQuery; diff --git a/types/jqueryui/tslint.json b/types/jqueryui/tslint.json index 22ecc7ce6f..ca9116c788 100644 --- a/types/jqueryui/tslint.json +++ b/types/jqueryui/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/js-beautify/js-beautify-tests.ts b/types/js-beautify/js-beautify-tests.ts index f421052503..34cd9d8f13 100644 --- a/types/js-beautify/js-beautify-tests.ts +++ b/types/js-beautify/js-beautify-tests.ts @@ -4,9 +4,9 @@ bCss = js_beautify.css_beautify("body{display:none;}"); let bHtml = js_beautify.html("
          "); bHtml = js_beautify.html_beautify("
          "); -let optHtml = {}; -let optCss = {}; -let optjs = {}; +let optHtml: HTMLBeautifyOptions = {}; +let optCss: CSSBeautifyOptions = {}; +let optjs: JsBeautifyOptions = {}; var simple: string = js_beautify("console.log('Hello world!');"); var full: string = js_beautify( diff --git a/types/js-money/tslint.json b/types/js-money/tslint.json index 3db14f85ea..42522eff7e 100644 --- a/types/js-money/tslint.json +++ b/types/js-money/tslint.json @@ -1 +1,9 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "dt-header": false, + "eofline": false, + "no-unnecessary-qualifier": false + } +} diff --git a/types/js-search/tslint.json b/types/js-search/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/js-search/tslint.json +++ b/types/js-search/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/js-url/index.d.ts b/types/js-url/index.d.ts index d5bf93257d..69583e1553 100644 --- a/types/js-url/index.d.ts +++ b/types/js-url/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for url v1.8.6 // Project: https://github.com/websanova/js-url -// Definitions by: MIZUNE Pine +// Definitions by: Pine Mizune // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped interface UrlStatic { diff --git a/types/jschannel/index.d.ts b/types/jschannel/index.d.ts index 42145531ea..ba1ce6f61d 100644 --- a/types/jschannel/index.d.ts +++ b/types/jschannel/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for jschannel 1.0 // Project: https://github.com/yochannah/jschannel // Definitions by: Yitzchok Gottlieb +// McFlat // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -25,7 +26,7 @@ export interface Message { } export interface ChannelConfiguration { - window: any; + window: Window; origin: string; scope: string; debugOutput?: boolean; diff --git a/types/jschannel/jschannel-tests.ts b/types/jschannel/jschannel-tests.ts index eabd150bf2..c618eea253 100644 --- a/types/jschannel/jschannel-tests.ts +++ b/types/jschannel/jschannel-tests.ts @@ -1,3 +1,3 @@ import { build } from 'jschannel'; -build({ window: null, origin: "*", scope: "testScope"}); +build({ window, origin: "*", scope: "testScope"}); diff --git a/types/jschannel/tsconfig.json b/types/jschannel/tsconfig.json index 58b8ca059e..e8988e8fe1 100644 --- a/types/jschannel/tsconfig.json +++ b/types/jschannel/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, @@ -20,4 +21,4 @@ "index.d.ts", "jschannel-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/jsdom/index.d.ts b/types/jsdom/index.d.ts index 1aa9750fbc..dec74af1ba 100644 --- a/types/jsdom/index.d.ts +++ b/types/jsdom/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for jsdom 11.12 +// Type definitions for jsdom 12.2 // Project: https://github.com/tmpvar/jsdom#readme // Definitions by: Leonard Thieu // Johan Palmfjord @@ -65,7 +65,7 @@ export interface Options { */ includeNodeLocations?: boolean; runScripts?: 'dangerously' | 'outside-only'; - resources?: 'usable'; + resources?: 'usable' | ResourceLoader; virtualConsole?: VirtualConsole; cookieJar?: CookieJar; beforeParse?(window: DOMWindow): void; @@ -287,3 +287,22 @@ export interface ReconfigureSettings { windowTop?: DOMWindow; url?: string; } + +export interface FetchOptions { + cookieJar?: CookieJar; + referrer?: string; + accept?: string; + element?: HTMLScriptElement | HTMLLinkElement | HTMLIFrameElement | HTMLImageElement; +} + +export interface ResourceLoaderConstructorOptions { + strictSSL?: boolean; + proxy?: string; + userAgent?: string; +} + +export class ResourceLoader { + fetch(url: string, options: FetchOptions): Promise | null; + + constructor(obj?: ResourceLoaderConstructorOptions); +} diff --git a/types/jsdom/jsdom-tests.ts b/types/jsdom/jsdom-tests.ts index da82b2db7c..1420723b8d 100644 --- a/types/jsdom/jsdom-tests.ts +++ b/types/jsdom/jsdom-tests.ts @@ -1,4 +1,4 @@ -import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow } from 'jsdom'; +import { JSDOM, VirtualConsole, CookieJar, FromUrlOptions, FromFileOptions, DOMWindow, ResourceLoader, FetchOptions } from 'jsdom'; import { CookieJar as ToughCookieJar, MemoryCookieStore } from 'tough-cookie'; import { Script } from 'vm'; @@ -82,6 +82,7 @@ function test_serialize() { dom.serialize() === 'hello'; // Contrast with: + // tslint:disable-next-line no-unnecessary-type-assertion dom.window.document.documentElement!.outerHTML === 'hello'; } @@ -119,7 +120,7 @@ function test_runVMScript() { dom.runVMScript(s); dom.runVMScript(s); - ( dom.window).ran === 3; + (dom.window as any).ran === 3; } function test_reconfigure() { @@ -168,3 +169,16 @@ function test_fragment_serialization() { } } } + +function test_custom_resource_loader() { + class CustomResourceLoader extends ResourceLoader { + fetch(url: string, options: FetchOptions) { + if (options.element) { + console.log(`Element ${options.element.localName} is requesting the url ${url}`); + } + + return super.fetch(url, options); + } + } + new JSDOM('', { resources: new CustomResourceLoader() }); +} diff --git a/types/jsen/jsen-tests.ts b/types/jsen/jsen-tests.ts index 16cded3688..20264b8818 100644 --- a/types/jsen/jsen-tests.ts +++ b/types/jsen/jsen-tests.ts @@ -2238,7 +2238,7 @@ const doesNotThrow = (func: Function) => { { let schema = { format: 'custom' }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2275,7 +2275,7 @@ const doesNotThrow = (func: Function) => { maximum: 10 }, callCount = 0, - options = { + options = { formats: { custom: () => { callCount++; @@ -2311,7 +2311,7 @@ const doesNotThrow = (func: Function) => { }, format: 'passwordsMatch' }, - options = { + options = { formats: { passwordsMatch: (obj: any) => { callCount++; 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/jsforce/connection.d.ts b/types/jsforce/connection.d.ts index 60716753ae..3bd0ea177b 100644 --- a/types/jsforce/connection.d.ts +++ b/types/jsforce/connection.d.ts @@ -12,6 +12,7 @@ import { Bulk } from './bulk'; import { Cache } from './cache' import { OAuth2, Streaming } from '.'; import { HttpApiOptions } from './http-api' +import { LimitsInfo } from './limits-info'; export type Callback = (err: Error | null, result: T) => void; // The type for these options was determined by looking at the usage @@ -160,9 +161,13 @@ export class Connection extends BaseConnection { login(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginByOAuth2(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; loginBySoap(user: string, password: string, callback?: (err: Error, res: UserInfo) => void): Promise; + logout(revoke: boolean, callback?: (err: Error, res: undefined) => void): Promise; logout(callback?: (err: Error, res: undefined) => void): Promise; + logoutByOAuth2(revoke: boolean, callback?: (err: Error, res: undefined) => void): Promise; logoutByOAuth2(callback?: (err: Error, res: undefined) => void): Promise; + logoutBySoap(revoke: boolean, callback?: (err: Error, res: undefined) => void): Promise; logoutBySoap(callback?: (err: Error, res: undefined) => void): Promise; + limits(callback?: (err: Error, res: undefined) => void): Promise; } export class Tooling extends BaseConnection { diff --git a/types/jsforce/index.d.ts b/types/jsforce/index.d.ts index c36f39095a..65d5159f61 100644 --- a/types/jsforce/index.d.ts +++ b/types/jsforce/index.d.ts @@ -30,3 +30,4 @@ export * from './salesforce-id'; export * from './salesforce-object'; export * from './streaming'; export * from './topic'; +export * from './limits-info'; diff --git a/types/jsforce/limits-info.d.ts b/types/jsforce/limits-info.d.ts new file mode 100644 index 0000000000..bfeeabe0c3 --- /dev/null +++ b/types/jsforce/limits-info.d.ts @@ -0,0 +1,48 @@ +export interface Limit { + Max: number; + Remaining: number; +} + +export interface PermissionSets extends Limit { + CreateCustom: Limit; +} + +export interface DailyApiRequests extends Limit { + 'Chatter Desktop': Limit; + 'Chatter Mobile for BlackBerry': Limit; + 'Salesforce Files': Limit; + 'Salesforce Marketing Cloud': Limit; + 'Salesforce for Android': Limit; + 'Salesforce for iOS': Limit; + 'SalesforceA': Limit; +} + +export interface LimitsInfo { + ConcurrentAsyncGetReportInstances: Limit; + ConcurrentSyncReportRuns: Limit; + DailyAnalyticsDataflowJobExecutions: Limit; + DailyApiRequests: DailyApiRequests; + DailyAsyncApexExecutions: Limit; + DailyBulkApiRequests: DailyApiRequests; + DailyDurableGenericStreamingApiEvents: Limit; + DailyDurableStreamingApiEvents: Limit; + DailyGenericStreamingApiEvents: DailyApiRequests; + DailyStreamingApiEvents: DailyApiRequests; + DailyWorkflowEmails: Limit; + DataStorageMB: Limit; + DurableStreamingApiConcurrentClients: Limit; + FileStorageMB: Limit; + HourlyAsyncReportRuns: Limit; + HourlyDashboardRefreshes: Limit; + HourlyDashboardResults: Limit; + HourlyDashboardStatuses: Limit; + HourlyODataCallout: Limit; + HourlySyncReportRuns: Limit; + HourlyTimeBasedWorkflow: Limit; + MassEmail: Limit; + MonthlyPlatformEvents: Limit; + Package2VersionCreates: Limit; + PermissionSets: PermissionSets; + SingleEmail: Limit; + StreamingApiConcurrentClients: Limit; +} diff --git a/types/jsforce/tslint.json b/types/jsforce/tslint.json index 3b1f082eb2..43829466b8 100644 --- a/types/jsforce/tslint.json +++ b/types/jsforce/tslint.json @@ -2,9 +2,19 @@ "extends": "dtslint/dt.json", "rules": { // TODOs + "array-type": false, "ban-types": false, + "eofline": false, + "max-line-length": false, "no-any-union": false, + "no-empty-interface": false, + "no-redundant-undefined": false, "no-unnecessary-class": false, - "no-unnecessary-generics": false + "no-unnecessary-generics": false, + "semicolon": false, + "space-within-parens": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false, + "whitespace": false } } diff --git a/types/json-rpc-random-id/index.d.ts b/types/json-rpc-random-id/index.d.ts new file mode 100644 index 0000000000..14b5ba0ff0 --- /dev/null +++ b/types/json-rpc-random-id/index.d.ts @@ -0,0 +1,14 @@ +// Type definitions for json-rpc-random-id 1.0 +// Project: https://github.com/kumavis/json-rpc-random-id#readme +// Definitions by: Micah Riggan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +/** + * Returns a function that generates a random number + * This number is to be used with web3 rpc + */ +declare function IdIterator(options?: { + max?: number; + start?: number; +}): () => number; + +export = IdIterator; diff --git a/types/json-rpc-random-id/json-rpc-random-id-tests.ts b/types/json-rpc-random-id/json-rpc-random-id-tests.ts new file mode 100644 index 0000000000..c71a7581e8 --- /dev/null +++ b/types/json-rpc-random-id/json-rpc-random-id-tests.ts @@ -0,0 +1,2 @@ +import jsonRPCRandomID = require("json-rpc-random-id"); +const generateId = jsonRPCRandomID(); diff --git a/types/json-rpc-random-id/tsconfig.json b/types/json-rpc-random-id/tsconfig.json new file mode 100644 index 0000000000..c39a0a4e2b --- /dev/null +++ b/types/json-rpc-random-id/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", + "json-rpc-random-id-tests.ts" + ] +} diff --git a/types/json-rpc-random-id/tslint.json b/types/json-rpc-random-id/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/json-rpc-random-id/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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/json2csv/tslint.json b/types/json2csv/tslint.json index 3db14f85ea..389fc5f08e 100644 --- a/types/json2csv/tslint.json +++ b/types/json2csv/tslint.json @@ -1 +1,15 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "ban-types": false, + "callable-types": false, + "jsdoc-format": false, + "member-access": false, + "no-duplicate-imports": false, + "no-redundant-jsdoc-2": false, + "strict-export-declare-modifiers": false, + "typedef-whitespace": false + } +} 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/jsonquery/index.d.ts b/types/jsonquery/index.d.ts new file mode 100644 index 0000000000..48afcf8d0a --- /dev/null +++ b/types/jsonquery/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for jsonquery 0.1 +// Project: https://github.com/eugeneware/jsonquery +// Definitions by: Jim Buck +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +/// + +declare function jsonquery(query: jsonquery.Query): NodeJS.ReadWriteStream; + +declare namespace jsonquery { + function match(haystack: T, predicate: Query): boolean; + + type Query = BinaryQueryCondition | QueryValue | PathQuery; + + interface OrQueryCondition { + $or: ReadonlyArray>; + } + + interface AndQueryCondition { + $and: ReadonlyArray>; + } + + type BinaryQueryCondition = OrQueryCondition | AndQueryCondition; + + interface BaseCondition

          { + $lt: P; + $lte: P; + $gt: P; + $gte: P; + $mod: [number, number]; + $ne: P; + $in: ReadonlyArray

          ; + $nin: ReadonlyArray

          ; + $all: ReadonlyArray

          ; + $elemMatch: Partial

          ; + } + + interface PathQuery { + [path: string]: any; + } + + type QueryValue = { + [P in keyof T]?: T[P] | BaseCondition; + }; +} + +export = jsonquery; diff --git a/types/jsonquery/jsonquery-tests.ts b/types/jsonquery/jsonquery-tests.ts new file mode 100644 index 0000000000..904f61d01c --- /dev/null +++ b/types/jsonquery/jsonquery-tests.ts @@ -0,0 +1,120 @@ +import jsonquery = require('jsonquery'); + +interface TestData { + name: string; + number: string; + val: number; + favorites: number[]; + awesome: boolean; + nullify: null; + tree: { + a: number; + b: number; + }; +} + +const testDataInstance: TestData = { + name: "Name 1", + number: "Number 1", + val: 10, + favorites: [10, 20], + awesome: true, + nullify: null, + tree: { + a: 1, + b: 2, + } +}; + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7' }); + +// $ExpectType ReadWriteStream +jsonquery({ number: 'Number 7', val: 70 }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { number: 'Number 7' }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { number: 'Number 7' }, { val: 70 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $or: [ { $and: [ { number: 'Number 7' }, { val: 70 } ] }, { val: 50 } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $in: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $in: [ 70, 50 ] }, { $in: [ 60, 20 ] } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lt: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $or: [ { $lt: 20 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $and: [ { $gt: 970 }, { $gt: 950 } ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $ne: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $lte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $gte: 900 } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [50, 60] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: 1, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': 1 }); + +// $ExpectType ReadWriteStream +jsonquery({ 'tree.a': { $in: [1, 5] } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: /er 7$/ }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $in: [ /er 7$/, /er 5$/ ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $all: [/^50$/, /^60$/] } }); + +// $ExpectType ReadWriteStream +jsonquery({ tree: { $elemMatch: { a: /^1$/, b: 2 } } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $nin: [ 70, 50 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ val: { $mod: [ 7, 1 ] } }); + +// $ExpectType ReadWriteStream +jsonquery({ favorites: { $size: 2 } }); + +// $ExpectType ReadWriteStream +jsonquery({ $and: [ { tree: { $exists: true } }, { missing: { $exists: false } } ] }); + +// $ExpectType ReadWriteStream +jsonquery({ $not: { number: 'Number 7', val: 70 } }); + +// $ExpectType ReadWriteStream +jsonquery({ number: { $not: { $nin: ['Number 7'] } } }); + +// $ExpectType ReadWriteStream +jsonquery({ foo: { $all: ['bar'] } }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { val: 7 }); + +// $ExpectType boolean +jsonquery.match(testDataInstance, { 'tree.a': { $in: [1, 5] } }); diff --git a/types/jsonquery/tsconfig.json b/types/jsonquery/tsconfig.json new file mode 100644 index 0000000000..ffb3eb6209 --- /dev/null +++ b/types/jsonquery/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", + "jsonquery-tests.ts" + ] +} diff --git a/types/jsonquery/tslint.json b/types/jsonquery/tslint.json new file mode 100644 index 0000000000..02db66c29b --- /dev/null +++ b/types/jsonquery/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules":{ + "no-unnecessary-generics": false + } +} diff --git a/types/jsonwebtoken/index.d.ts b/types/jsonwebtoken/index.d.ts index f54d3862c9..d1c3aeee5f 100644 --- a/types/jsonwebtoken/index.d.ts +++ b/types/jsonwebtoken/index.d.ts @@ -1,9 +1,10 @@ -// Type definitions for jsonwebtoken 7.2.2 +// Type definitions for jsonwebtoken 8.3 // Project: https://github.com/auth0/node-jsonwebtoken // Definitions by: Maxime LUCE , // Daniel Heim , // Brice BERNARD , -// Veli-Pekka Kestilä +// Veli-Pekka Kestilä , +// Daniel Parker // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -43,9 +44,9 @@ export interface SignOptions { */ algorithm?: string; keyid?: string; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ expiresIn?: string | number; - /** @member {string} - expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ + /** expressed in seconds or a string describing a time span [zeit/ms](https://github.com/zeit/ms.js). Eg: 60, "2 days", "10h", "7d" */ notBefore?: string | number; audience?: string | string[]; subject?: string; @@ -67,8 +68,8 @@ export interface VerifyOptions { jwtid?: string; subject?: string; /** - *@deprecated - *@member {string} - Max age of token + * @deprecated + * Max age of token */ maxAge?: string; } @@ -77,28 +78,45 @@ export interface DecodeOptions { complete?: boolean; json?: boolean; } -export type VerifyErrors=JsonWebTokenError | NotBeforeError | TokenExpiredError; -export interface VerifyCallback { - ( - err: VerifyErrors, - decoded: object | string, - ): void; +export type VerifyErrors= JsonWebTokenError | NotBeforeError | TokenExpiredError; +export type VerifyCallback = ( + err: VerifyErrors, + decoded: object | string, +) => void; + +export type SignCallback = ( + err: Error, encoded: string +) => void; + +export interface JwtHeader { + alg: string; + typ?: string; + kid?: string; + jku?: string; + x5u?: string; + x5t?: string; } -export interface SignCallback { - (err: Error, encoded: string): void; -} +export type SigningKeyCallback = ( + err: any, + signingKey?: Secret, +) => void; + +export type GetPublicKeyOrSecret = ( + header: JwtHeader, + callback: SigningKeyCallback +) => void; export type Secret = string | Buffer | { key: string; passphrase: string }; /** * Synchronously sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @returns {String} The JSON Web Token string + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * returns - The JSON Web Token string */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options?: SignOptions, @@ -106,17 +124,17 @@ export declare function sign( /** * Sign the given payload into a JSON Web Token string - * @param {String|Object|Buffer} payload - Payload to sign, could be an literal, buffer or string - * @param {String|Buffer} secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. - * @param {SignOptions} [options] - Options for the signature - * @param {Function} callback - Callback to get the encoded token on + * payload - Payload to sign, could be an literal, buffer or string + * secretOrPrivateKey - Either the secret for HMAC algorithms, or the PEM encoded private key for RSA and ECDSA. + * [options] - Options for the signature + * callback - Callback to get the encoded token on */ -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, callback: SignCallback, ): void; -export declare function sign( +export function sign( payload: string | Buffer | object, secretOrPrivateKey: Secret, options: SignOptions, @@ -125,16 +143,12 @@ export declare function sign( /** * Synchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @returns The decoded token. + * token - JWT string to verify + * secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. + * [options] - Options for the verification + * returns - The decoded token. */ -export declare function verify( - token: string, - secretOrPublicKey: string | Buffer, -): object | string; -export declare function verify( +export function verify( token: string, secretOrPublicKey: string | Buffer, options?: VerifyOptions, @@ -142,31 +156,32 @@ export declare function verify( /** * Asynchronously verify given token using a secret or a public key to get a decoded token - * @param {String} token - JWT string to verify - * @param {String|Buffer} secretOrPublicKey - Either the secret for HMAC algorithms, or the PEM encoded public key for RSA and ECDSA. - * @param {VerifyOptions} [options] - Options for the verification - * @param {Function} callback - Callback to get the decoded token on + * token - JWT string to verify + * secretOrPublicKey - A string or buffer containing either the secret for HMAC algorithms, + * or the PEM encoded public key for RSA and ECDSA. If jwt.verify is called asynchronous, + * secretOrPublicKey can be a function that should fetch the secret or public key + * [options] - Options for the verification + * callback - Callback to get the decoded token on */ -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, callback?: VerifyCallback, ): void; -export declare function verify( +export function verify( token: string, - secretOrPublicKey: string | Buffer, + secretOrPublicKey: string | Buffer | GetPublicKeyOrSecret, options?: VerifyOptions, callback?: VerifyCallback, ): void; /** * Returns the decoded payload without verifying if the signature is valid. - * @param {String} token - JWT string to decode - * @param {DecodeOptions} [options] - Options for decoding - * @returns {Object} The decoded Token + * token - JWT string to decode + * [options] - Options for decoding + * returns - The decoded Token */ -export declare function decode( +export function decode( token: string, options?: DecodeOptions, ): null | { [key: string]: any } | string; - diff --git a/types/jsonwebtoken/jsonwebtoken-tests.ts b/types/jsonwebtoken/jsonwebtoken-tests.ts index f20fbba5cc..5884ff6d63 100644 --- a/types/jsonwebtoken/jsonwebtoken-tests.ts +++ b/types/jsonwebtoken/jsonwebtoken-tests.ts @@ -7,10 +7,10 @@ import jwt = require("jsonwebtoken"); import fs = require("fs"); -var token: string; -var cert: Buffer; +let token: string; +let cert: Buffer; -interface ITestObject { +interface TestObject { foo: string; } @@ -44,10 +44,10 @@ const secret = { key: privKey.toString(), passphrase: "keypwd" }; token = jwt.sign(testObject, secret, { algorithm: "RS256" }); // the algorithm option is mandatory in this case // sign asynchronously -jwt.sign(testObject, cert, { algorithm: "RS256" }, function( +jwt.sign(testObject, cert, { algorithm: "RS256" }, ( err: Error, token: string, -) { +) => { console.log(token); }); @@ -56,57 +56,70 @@ jwt.sign(testObject, cert, { algorithm: "RS256" }, function( * https://github.com/auth0/node-jsonwebtoken#jwtverifytoken-secretorpublickey-options-callback */ // verify a token symmetric -jwt.verify(token, "shhhhh", function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, "shhhhh", (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // use external time for verifying -jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, function(err, decoded) { - const result = decoded as ITestObject +jwt.verify(token, 'shhhhh', { clockTimestamp: 1 }, (err, decoded) => { + const result = decoded as TestObject; - console.log(result.foo) // bar + console.log(result.foo); // bar }); // invalid token -jwt.verify(token, "wrong-secret", function(err, decoded) { +jwt.verify(token, "wrong-secret", (err, decoded) => { // err // decoded undefined }); // verify a token asymmetric cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, function(err, decoded) { - const result = decoded as ITestObject; +jwt.verify(token, cert, (err, decoded) => { + const result = decoded as TestObject; + + console.log(result.foo); // bar +}); + +// verify a token assymetric with async key fetch function +function getKey(header: jwt.JwtHeader, callback: jwt.SigningKeyCallback) { + cert = fs.readFileSync("public.pem"); + + callback(null, cert); +} + +jwt.verify(token, getKey, (err, decoded) => { + const result = decoded as TestObject; console.log(result.foo); // bar }); // verify audience cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo" }, function(err, decoded) { +jwt.verify(token, cert, { audience: "urn:foo" }, (err, decoded) => { // if audience mismatch, err == invalid audience }); // verify issuer cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, function( +jwt.verify(token, cert, { audience: "urn:foo", issuer: "urn:issuer" }, ( err, decoded, -) { +) => { // if issuer mismatch, err == invalid issuer }); // verify algorithm cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { algorithms: ["RS256"] }, function(err, decoded) { +jwt.verify(token, cert, { algorithms: ["RS256"] }, (err, decoded) => { // if algorithm mismatch, err == invalid algorithm }); // verify without expiration check cert = fs.readFileSync("public.pem"); // get public key -jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { +jwt.verify(token, cert, { ignoreExpiration: true }, (err, decoded) => { // if ignoreExpration == false and token is expired, err == expired token }); @@ -114,7 +127,7 @@ jwt.verify(token, cert, { ignoreExpiration: true }, function(err, decoded) { * jwt.decode * https://github.com/auth0/node-jsonwebtoken#jwtdecodetoken */ -var decoded = jwt.decode(token); +let decoded = jwt.decode(token); decoded = jwt.decode(token, { complete: false }); diff --git a/types/jsonwebtoken/tslint.json b/types/jsonwebtoken/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/jsonwebtoken/tslint.json +++ b/types/jsonwebtoken/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/jspath/index.d.ts b/types/jspath/index.d.ts new file mode 100644 index 0000000000..3c5ae53121 --- /dev/null +++ b/types/jspath/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for jspath 0.4 +// Project: https://github.com/dfilatov/jspath +// Definitions by: Piot Roszatycki +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * @param path path expression + * @param data input JSON document + * @param replacement substitutions + */ +export function apply(path: string, data: any, replacement?: any): any[]; diff --git a/types/jspath/jspath-tests.ts b/types/jspath/jspath-tests.ts new file mode 100644 index 0000000000..84e6f1c0e4 --- /dev/null +++ b/types/jspath/jspath-tests.ts @@ -0,0 +1,62 @@ +import * as JSPath from 'jspath'; + +// tslint:disable:object-literal-key-quotes + +JSPath.apply( + '.automobiles{.maker === "Honda" && .year > 2009}.model', + { + "automobiles" : [ + { "maker" : "Nissan", "model" : "Teana", "year" : 2011 }, + { "maker" : "Honda", "model" : "Jazz", "year" : 2010 }, + { "maker" : "Honda", "model" : "Civic", "year" : 2007 }, + { "maker" : "Toyota", "model" : "Yaris", "year" : 2008 }, + { "maker" : "Honda", "model" : "Accord", "year" : 2011 } + ], + "motorcycles" : [{ "maker" : "Honda", "model" : "ST1300", "year" : 2012 }] + } +); + +const doc = { + "books" : [ + { + "id" : 1, + "title" : "Clean Code", + "author" : { "name" : "Robert C. Martin" }, + "price" : 17.96 + }, + { + "id" : 2, + "title" : "Maintainable JavaScript", + "author" : { "name" : "Nicholas C. Zakas" }, + "price" : 10 + }, + { + "id" : 3, + "title" : "Agile Software Development", + "author" : { "name" : "Robert C. Martin" }, + "price" : 20 + }, + { + "id" : 4, + "title" : "JavaScript: The Good Parts", + "author" : { "name" : "Douglas Crockford" }, + "price" : 15.67 + } + ] +}; + +JSPath.apply('.books.author', doc); + +JSPath.apply('.books.author.name', doc); + +JSPath.apply('.books..name', doc); + +JSPath.apply('.books{.author.name === "Robert C. Martin"}.title', doc); + +JSPath.apply('.books{.price < 17}.title', doc); + +const path = '.books{.author.name === $author}.title'; + +JSPath.apply(path, doc, { author : 'Nicholas C. Zakas' }); + +JSPath.apply(path, doc, { author : ['Robert C. Martin', 'Douglas Crockford'] }); diff --git a/types/jspath/tsconfig.json b/types/jspath/tsconfig.json new file mode 100644 index 0000000000..38ab91e172 --- /dev/null +++ b/types/jspath/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", + "jspath-tests.ts" + ] +} diff --git a/types/jspath/tslint.json b/types/jspath/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/jspath/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/jspdf/index.d.ts b/types/jspdf/index.d.ts index e393e5fba1..63789a7093 100644 --- a/types/jspdf/index.d.ts +++ b/types/jspdf/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for jsPDF v1.1.135 +// Type definitions for jsPDF 1.2 // Project: https://github.com/MrRio/jsPDF // Definitions by: Amber Schühmacher +// Kevin Gonnord +// Jackie Weng // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare module 'jspdf' { @@ -32,7 +34,9 @@ declare module 'jspdf' { 'scaleFactor':number; 'pageSize': { width:number; + getWidth: () => number; height:number; + getHeight: () => number; }; 'output'(type:any, options:any):any; 'getNumberOfPages'():number; @@ -42,7 +46,7 @@ declare module 'jspdf' { 'getPageInfo'(pageNumberOneBased:number):any; 'getCurrentPageInfo'():any; }; - addPage(sizes?: number[]):jsPDF; + addPage(format?: string | number[], orientation?: 'p'|'portrait'|'l'|'landscape'): jsPDF; setPage(n:number):jsPDF; insertPage(beforePage:number):jsPDF; movePage(targetPage:number, beforePage:number):jsPDF; @@ -90,6 +94,7 @@ declare module 'jspdf' { * - split_text_to_size * - SVG * - total_pages + * - vfs */ // jsPDF plugin: addHTML @@ -201,8 +206,13 @@ declare module 'jspdf' { // jsPDF plugin: total_pages putTotalPages(pageExpression:string):jsPDF; + + // jsPDF plugin: vfs + existsFileInVFS(filename:string):boolean; + addFileToVFS(filename:string, filecontent:string):jsPDF; + getFileFromVFS(filename:string):string; } - + namespace jsPDF {} export = jsPDF; diff --git a/types/jspdf/jspdf-tests.ts b/types/jspdf/jspdf-tests.ts index 0f31005af9..ab6dd3a82a 100644 --- a/types/jspdf/jspdf-tests.ts +++ b/types/jspdf/jspdf-tests.ts @@ -13,6 +13,18 @@ function test_simple_two_page_document() { doc.save('Test.pdf'); } +function test_add_pages_with_different_format() { + var doc = new jsPDF(); + doc.text(20, 20, 'Hello world!'); + doc.addPage('a5', 'l'); + doc.text(20, 20, 'Do you like that?'); + doc.addPage('c6'); + doc.text(20, 20, 'Do you like that?'); + doc.addPage([595.28, 841.89]); + doc.text(20, 20, 'Do you like that?'); + doc.save('Test.pdf'); +} + function test_landscape() { var doc = new jsPDF('landscape'); doc.text(20, 20, 'Hello landscape world!'); diff --git a/types/jspdf/tslint.json b/types/jspdf/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/jspdf/tslint.json +++ b/types/jspdf/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/jss/css.d.ts b/types/jss/css.d.ts index 2d5e89139a..9bed74d702 100644 --- a/types/jss/css.d.ts +++ b/types/jss/css.d.ts @@ -3,7 +3,7 @@ import { Observable } from 'indefinite-observable'; import * as csstype from 'csstype'; -type Length = string | number; +export type Length = string | number; export type ObservableProperties

          = { [K in keyof P]: P[K] | Observable diff --git a/types/just-debounce-it/index.d.ts b/types/just-debounce-it/index.d.ts new file mode 100644 index 0000000000..248f6a27f8 --- /dev/null +++ b/types/just-debounce-it/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for just-debounce-it 1.1 +// Project: https://github.com/angus-c/just#readme +// Definitions by: Aziz Khambati +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +type ArgumentTypes = F extends (...args: infer A) => any ? A : never; + +/*~ This declaration specifies that the function + *~ is the exported object from the file + */ +export = debounce; + +declare function debounce( + fn: T, + wait?: 0, + callFirst?: boolean +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst: true +): T; + +declare function debounce( + fn: T, + wait: number, + callFirst?: false +): (...args: ArgumentTypes) => void; diff --git a/types/just-debounce-it/just-debounce-it-tests.ts b/types/just-debounce-it/just-debounce-it-tests.ts new file mode 100644 index 0000000000..32dd33c9e7 --- /dev/null +++ b/types/just-debounce-it/just-debounce-it-tests.ts @@ -0,0 +1,23 @@ +import debounce = require("just-debounce-it"); + +const doThings = () => 1; + +const num: number = debounce(doThings)(); +const num2: number = debounce(doThings, 0)(); +const num3: number = debounce(doThings, 0, true)(); +const num4: number = debounce(doThings, 0, false)(); +const num5: number = debounce(doThings, 1000, true)(); + +// $ExpectType void +debounce(doThings, 1000)(); + +const exclaim = (a: string) => a + '!'; + +const str: string = debounce(exclaim)('hey'); +const str2: string = debounce(exclaim, 0)('hi'); +const str3: string = debounce(exclaim, 0, true)('hi'); +const str4: string = debounce(exclaim, 0, false)('hi'); +const str5: string = debounce(exclaim, 1000, true)('hooray'); + +// $ExpectType void +debounce(exclaim, 1000)('hello'); diff --git a/types/just-debounce-it/tsconfig.json b/types/just-debounce-it/tsconfig.json new file mode 100644 index 0000000000..d1a7dbd8b0 --- /dev/null +++ b/types/just-debounce-it/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", + "just-debounce-it-tests.ts" + ] +} diff --git a/types/just-debounce-it/tslint.json b/types/just-debounce-it/tslint.json new file mode 100644 index 0000000000..5bc412fb1e --- /dev/null +++ b/types/just-debounce-it/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "ban-types": false + } +} diff --git a/types/just-pick/index.d.ts b/types/just-pick/index.d.ts new file mode 100644 index 0000000000..04836648cc --- /dev/null +++ b/types/just-pick/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for just-pick 2.1 +// Project: https://github.com/angus-c/just#readme +// Definitions by: Peter Safranek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare function pick(obj: T, select: U[]): Pick; + +declare function pick(obj: T, select1: U, ...selectn: U[]): Pick; + +export = pick; diff --git a/types/just-pick/just-pick-tests.ts b/types/just-pick/just-pick-tests.ts new file mode 100644 index 0000000000..8f675a010c --- /dev/null +++ b/types/just-pick/just-pick-tests.ts @@ -0,0 +1,26 @@ +import pick = require("just-pick"); + +const a = "a"; +const b = "b"; +const c = "c"; +const obj = { a, b }; + +pick(obj, []); // $ExpectType Pick<{ a: string; b: string; }, never> +pick(obj, [a]); // $ExpectType Pick<{ a: string; b: string; }, "a"> +pick(obj, [a, a]); // $ExpectType Pick<{ a: string; b: string; }, "a"> +pick(obj, [a, b]); // $ExpectType Pick<{ a: string; b: string; }, "a" | "b"> +pick(obj, [a, b, c]); // $ExpectError + +pick(obj, a); // $ExpectType Pick<{ a: string; b: string; }, "a"> +pick(obj, a, a); // $ExpectType Pick<{ a: string; b: string; }, "a"> +pick(obj, a, b); // $ExpectType Pick<{ a: string; b: string; }, "a" | "b"> +pick(obj, a, b, c); // $ExpectError + +pick(); // $ExpectError +pick(obj); // $ExpectError +pick(obj, 0); // $ExpectError +pick(obj, false); // $ExpectError +pick(obj, null); // $ExpectError +pick(obj, undefined); // $ExpectError +pick(obj, {}); // $ExpectError +pick(obj, () => {}); // $ExpectError diff --git a/types/just-pick/tsconfig.json b/types/just-pick/tsconfig.json new file mode 100644 index 0000000000..860c7fa95d --- /dev/null +++ b/types/just-pick/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", + "just-pick-tests.ts" + ] +} diff --git a/types/just-pick/tslint.json b/types/just-pick/tslint.json new file mode 100644 index 0000000000..702f9354fc --- /dev/null +++ b/types/just-pick/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "file-name-casing": false + } +} diff --git a/types/jwt-express/tslint.json b/types/jwt-express/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/jwt-express/tslint.json +++ b/types/jwt-express/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/karma-chai-sinon/index.d.ts b/types/karma-chai-sinon/index.d.ts index 1ce2672b23..0b14373a99 100644 --- a/types/karma-chai-sinon/index.d.ts +++ b/types/karma-chai-sinon/index.d.ts @@ -2,10 +2,10 @@ // Project: https://github.com/tubalmartin/karma-chai-sinon // Definitions by: Václav Ostrožlík // Definitions: https://github.com/borisyankov/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 3.0 /// -import Sinon = require("sinon"); +import Sinon = require('sinon'); declare global { var should: Chai.Should; diff --git a/types/karma-coverage/index.d.ts b/types/karma-coverage/index.d.ts index 50be80d5cf..8382ec7b12 100644 --- a/types/karma-coverage/index.d.ts +++ b/types/karma-coverage/index.d.ts @@ -1,27 +1,22 @@ -// Type definitions for karma-coverage v0.5.3 +// Type definitions for karma-coverage 1.1 // Project: https://github.com/karma-runner/karma-coverage // Definitions by: Tanguy Krotoff +// Yaroslav Admin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as karma from 'karma'; +import 'karma'; import * as istanbul from 'istanbul'; -declare namespace karmaCoverage { - interface Karma extends karma.Karma { } - - interface Config extends karma.Config { - set: (config: ConfigOptions) => void; - } - - interface ConfigOptions extends karma.ConfigOptions { +declare module 'karma' { + interface ConfigOptions { /** * See https://github.com/karma-runner/karma-coverage/blob/master/docs/configuration.md */ - coverageReporter?: (Reporter | Reporter[]); + coverageReporter?: KarmaCoverageReporter & { reporters?: KarmaCoverageReporter[] }; } - interface Reporter { + interface KarmaCoverageReporter { type?: string; dir?: string; subdir?: string | ((browser: string) => string); @@ -33,7 +28,3 @@ declare namespace karmaCoverage { [moreSettings: string]: any; } } - -declare var karmaCoverage: karmaCoverage.Karma; - -export = karmaCoverage; diff --git a/types/karma-coverage/karma-coverage-tests.ts b/types/karma-coverage/karma-coverage-tests.ts index 4f0b187a7a..36d7d85415 100644 --- a/types/karma-coverage/karma-coverage-tests.ts +++ b/types/karma-coverage/karma-coverage-tests.ts @@ -1,6 +1,6 @@ -import * as karma from 'karma-coverage'; +import * as karma from 'karma'; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#basic +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#basic module.exports = function(config: karma.Config) { config.set({ files: [ @@ -20,13 +20,13 @@ module.exports = function(config: karma.Config) { // optionally, configure the reporter coverageReporter: { - type : 'html', - dir : 'coverage/' + type: 'html', + dir: 'coverage/' } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#advanced-multiple-reporters +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#advanced-multiple-reporters module.exports = function(config: karma.Config) { config.set({ files: [ @@ -56,7 +56,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/README.md#dont-minify-instrumenter-output +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/README.md#dont-minify-instrumenter-output module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -67,7 +67,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#subdir +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#subdir module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -93,7 +93,7 @@ module.exports = function(config: karma.Config) { coverageReporter: { dir: 'coverage', subdir: function(browser) { - // normalization process to keep a consistent browser name accross different + // normalization process to keep a consistent browser name across different // OS return browser.toLowerCase().split(/[ /-]/)[0]; } @@ -102,18 +102,18 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#file +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#file module.exports = function(config: karma.Config) { config.set({ coverageReporter: { - type : 'text', - dir : 'coverage/', - file : 'coverage.txt' + type: 'text', + dir: 'coverage/', + file: 'coverage.txt' } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#check +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#check module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -146,7 +146,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#watermarks +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#watermarks module.exports = function(config: karma.Config) { config.set({ coverageReporter: { @@ -160,24 +160,36 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#sourcestore -module.exports = function(config: karma.Config) { +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#includeallsources +module.exports = function (config: karma.Config) { config.set({ coverageReporter: { - type : 'text', - dir : 'coverage/', - file : 'coverage.txt', - sourceStore : require('istanbul').Store.create('fslookup') + type: 'text', + dir: 'coverage/', + file: 'coverage.txt', + includeAllSources: true } }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#reporters +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#sourcestore module.exports = function(config: karma.Config) { config.set({ coverageReporter: { - reporters:[ - {type: 'html', dir:'coverage/'}, + type: 'text', + dir: 'coverage/', + file: 'coverage.txt', + sourceStore: require('istanbul').Store.create('fslookup') + } + }); +}; + +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#reporters +module.exports = function(config: karma.Config) { + config.set({ + coverageReporter: { + reporters: [ + {type: 'html', dir: 'coverage/'}, {type: 'teamcity'}, {type: 'text-summary'} ], @@ -185,7 +197,7 @@ module.exports = function(config: karma.Config) { }); }; -// See https://github.com/karma-runner/karma-coverage/blob/v0.5.3/docs/configuration.md#instrumenter +// See https://github.com/karma-runner/karma-coverage/blob/v1.1.2/docs/configuration.md#instrumenter module.exports = function(config: karma.Config) { config.set({ coverageReporter: { diff --git a/types/karma-fixture/index.d.ts b/types/karma-fixture/index.d.ts index 42af1d5d60..d443359d72 100644 --- a/types/karma-fixture/index.d.ts +++ b/types/karma-fixture/index.d.ts @@ -1,31 +1,28 @@ -// Type definitions for karma-fixture 0.2.7 +// Type definitions for karma-fixture 0.2 // Project: https://github.com/billtrik/karma-fixture // Definitions by: Ezekiel Victor // Afshawn Lotfi // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace fixture { - export var el: HTMLElement; - export var json: any[]; + let el: HTMLElement; + let json: any[]; - export function load(...files: string[]): any; - export function load(file1: string, append?: boolean): any; - export function load(file1: string, file2: string, append?: boolean): any; - export function load(file1: string, file2: string, file3: string, append?: boolean): any; - export function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; - export function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; + function load(...files: string[]): any; + function load(file1: string, append?: boolean): any; + function load(file1: string, file2: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, append?: boolean): any; + function load(file1: string, file2: string, file3: string, file4: string, file5: string, append?: boolean): any; - export function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; - export function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; - export function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; - export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; - export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; - export function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(...htmlStrs: string[]): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, append?: boolean): HTMLElement|HTMLElement[]; + function set(htmlStr1: string, htmlStr2: string, htmlStr3: string, htmlStr4: string, htmlStr5: string, append?: boolean): HTMLElement|HTMLElement[]; - export function cleanup(): void; + function cleanup(): void; - export function setBase(fixtureBasePath: string): void; + function setBase(fixtureBasePath: string): void; } - -export = fixture; -export as namespace fixture; diff --git a/types/karma-fixture/karma-fixture-tests.ts b/types/karma-fixture/karma-fixture-tests.ts index d8ea8c8794..2096298eb9 100644 --- a/types/karma-fixture/karma-fixture-tests.ts +++ b/types/karma-fixture/karma-fixture-tests.ts @@ -1,4 +1,3 @@ - fixture.setBase('fixtures/base/path'); fixture.load('test1.html', 'test1.json', false); fixture.load('test1.html', 'test2.html', 'test1.json'); diff --git a/types/karma-fixture/tslint.json b/types/karma-fixture/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/karma-fixture/tslint.json +++ b/types/karma-fixture/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/karma-jasmine/index.d.ts b/types/karma-jasmine/index.d.ts index ae929c6af3..73ca7a480e 100644 --- a/types/karma-jasmine/index.d.ts +++ b/types/karma-jasmine/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/karma-runner/karma-jasmine // Definitions by: Michel Salib // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 /// diff --git a/types/karma/index.d.ts b/types/karma/index.d.ts index 4b71c0a723..0da2803283 100644 --- a/types/karma/index.d.ts +++ b/types/karma/index.d.ts @@ -1,485 +1,472 @@ -// Type definitions for karma 1.7 +// Type definitions for karma 3.0 // Project: https://github.com/karma-runner/karma // Definitions by: Tanguy Krotoff // James Garbutt +// Yaroslav Admin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 /// -// See Karma public API https://karma-runner.github.io/0.13/dev/public-api.html +// See Karma public API https://karma-runner.github.io/latest/dev/public-api.html import Promise = require('bluebird'); import https = require('https'); +import { Appender } from 'log4js'; -declare namespace karma { - interface Karma { - /** - * `start` method is deprecated since 0.13. It will be removed in 0.14. - * Please use - * - * server = new Server(config, [done]) - * server.start() - * - * instead. - */ - server: DeprecatedServer; - Server: Server; - runner: Runner; - stopper: Stopper; - launcher: Launcher; - VERSION: string; - constants: Constants; - } +/** + * `start` method is deprecated since 0.13. It will be removed in 0.14. + * Please use + * + * server = new Server(config, [done]) + * server.start() + * + * instead. + * + * @deprecated + */ +export const server: DeprecatedServer; - interface Constants { - VERSION: string; - DEFAULT_PORT: number; - DEFAULT_HOSTNAME: string; - DEFAULT_LISTEN_ADDR: string; - LOG_DISABLE: string; - LOG_ERROR: string; - LOG_WARN: string; - LOG_INFO: string; - LOG_DEBUG: string; - LOG_LOG: string; - LOG_PRIORITIES: string[]; - COLOR_PATTERN: string; - NO_COLOR_PATTERN: string; - CONSOLE_APPENDER: { +export const runner: Runner; +export const stopper: Stopper; + +export const VERSION: string; +export const constants: Constants; + +export interface Constants { + VERSION: string; + DEFAULT_PORT: number; + DEFAULT_HOSTNAME: string; + DEFAULT_LISTEN_ADDR: string; + LOG_DISABLE: string; + LOG_ERROR: string; + LOG_WARN: string; + LOG_INFO: string; + LOG_DEBUG: string; + LOG_LOG: string; + LOG_PRIORITIES: string[]; + COLOR_PATTERN: string; + NO_COLOR_PATTERN: string; + CONSOLE_APPENDER: { + type: string; + layout: { type: string; - layout: { - type: string; - pattern: string; - }; + pattern: string; }; - EXIT_CODE: string; - } + }; + EXIT_CODE: string; +} - interface LauncherStatic { - generateId(): string; - //TODO: injector should be of type `di.Injector` - new (emitter: NodeJS.EventEmitter, injector: any): Launcher; - } +export namespace launcher { + class Launcher { + static generateId(): string; - interface Launcher { - Launcher: LauncherStatic; - //TODO: Can this return value ever be typified? + constructor(emitter: NodeJS.EventEmitter, injector: any); + + // TODO: Can this return value ever be typified? launch(names: string[], protocol: string, hostname: string, port: number, urlRoot: string): any[]; - kill(id: string, callback: Function): boolean; + kill(id: string, callback: () => void): boolean; restart(id: string): boolean; - killAll(callback: Function): void; + killAll(callback: () => void): void; areAllCaptured(): boolean; markCaptured(id: string): void; } - - interface DeprecatedServer { - start(options?: any, callback?: ServerCallback): void; - } - - interface Runner { - run(options?: ConfigOptions | ConfigFile, callback?: ServerCallback): void; - } - - - interface Stopper { - /** - * This function will signal a running server to stop. The equivalent of karma stop. - */ - stop(options?: ConfigOptions, callback?: ServerCallback): void; - } - - - interface TestResults { - disconnected: boolean; - error: boolean; - exitCode: number; - failed: number; - success: number; - } - - interface Server extends NodeJS.EventEmitter { - new (options?: ConfigOptions | ConfigFile, callback?: ServerCallback): Server; - /** - * Start the server - */ - start(): void; - /** - * Get properties from the injector - * @param token - */ - get(token: string): any; - /** - * Force a refresh of the file list - */ - refreshFiles(): Promise; - - on(event: string, listener: Function): this; - - /** - * Listen to the 'run_complete' event. - */ - on(event: 'run_complete', listener: (browsers: any, results: TestResults) => void): this; - - ///** - // * Backward-compatibility with karma-intellij bundled with WebStorm. - // * Deprecated since version 0.13, to be removed in 0.14 - // */ - //static start(): void; - } - - interface ServerCallback { - (exitCode: number): void; - } - - interface Config { - set: (config: ConfigOptions) => void; - LOG_DISABLE: string; - LOG_ERROR: string; - LOG_WARN: string; - LOG_INFO: string; - LOG_DEBUG: string; - } - - interface ConfigFile { - configFile: string; - } - - // taken from log4js 1.x typings which are gone... - interface Log4jsAppenderConfigBase { - type: string; - category?: string; - layout?: { - type: string; - [key: string]: any - } - } - - interface ConfigOptions { - /** - * @description Enable or disable watching files and executing the tests whenever one of these files changes. - * @default true - */ - autoWatch?: boolean; - /** - * @description When Karma is watching the files for changes, it tries to batch multiple changes into a single run - * so that the test runner doesn't try to start and restart running tests more than it should. - * The configuration setting tells Karma how long to wait (in milliseconds) after any changes have occurred - * before starting the test process again. - * @default 250 - */ - autoWatchBatchDelay?: number; - /** - * @default '' - * @description The root path location that will be used to resolve all relative paths defined in files and exclude. - * If the basePath configuration is a relative path then it will be resolved to - * the __dirname of the configuration file. - */ - basePath?: string; - /** - * @default 2000 - * @description How long does Karma wait for a browser to reconnect (in ms). - *

          - * With a flaky connection it is pretty common that the browser disconnects, - * but the actual test execution is still running without any problems. Karma does not treat a disconnection - * as immediate failure and will wait browserDisconnectTimeout (ms). - * If the browser reconnects during that time, everything is fine. - *

          - */ - browserDisconnectTimeout?: number; - /** - * @default 0 - * @description The number of disconnections tolerated. - *

          - * The disconnectTolerance value represents the maximum number of tries a browser will attempt - * in the case of a disconnection. Usually any disconnection is considered a failure, - * but this option allows you to define a tolerance level when there is a flaky network link between - * the Karma server and the browsers. - *

          - */ - browserDisconnectTolerance?: number; - /** - * @default 10000 - * @description How long will Karma wait for a message from a browser before disconnecting from it (in ms). - *

          - * If, during test execution, Karma does not receive any message from a browser within - * browserNoActivityTimeout (ms), it will disconnect from the browser - *

          - */ - browserNoActivityTimeout?: number; - /** - * @default [] - * Possible Values: - *
            - *
          • Chrome (launcher comes installed with Karma)
          • - *
          • ChromeCanary (launcher comes installed with Karma)
          • - *
          • PhantomJS (launcher comes installed with Karma)
          • - *
          • Firefox (launcher requires karma-firefox-launcher plugin)
          • - *
          • Opera (launcher requires karma-opera-launcher plugin)
          • - *
          • Internet Explorer (launcher requires karma-ie-launcher plugin)
          • - *
          • Safari (launcher requires karma-safari-launcher plugin)
          • - *
          - * @description A list of browsers to launch and capture. When Karma starts up, it will also start up each browser - * which is placed within this setting. Once Karma is shut down, it will shut down these browsers as well. - * You can capture any browser manually by opening the browser and visiting the URL where - * the Karma web server is listening (by default it is http://localhost:9876/). - */ - browsers?: string[]; - /** - * @default 60000 - * @description Timeout for capturing a browser (in ms). - *

          - * The captureTimeout value represents the maximum boot-up time allowed for a - * browser to start and connect to Karma. If any browser does not get captured within the timeout, Karma - * will kill it and try to launch it again and, after three attempts to capture it, Karma will give up. - *

          - */ - captureTimeout?: number; - client?: ClientOptions; - /** - * @default true - * @description Enable or disable colors in the output (reporters and logs). - */ - colors?: boolean; - /** - * @default 'Infinity' - * @description How many browsers Karma launches in parallel. - * Especially on services like SauceLabs and Browserstack, it makes sense only to launch a limited - * amount of browsers at once, and only start more when those have finished. Using this configuration, - * you can specify how many browsers should be running at once at any given point in time. - */ - concurrency?: number; - customLaunchers?: { [key: string]: CustomLauncher }; - /** - * @default [] - * @description List of files/patterns to exclude from loaded files. - */ - exclude?: string[]; - /** - * @default [] - * @description List of files/patterns to load in the browser. - */ - files?: (FilePattern | string)[]; - /** - * @default [] - * @description List of test frameworks you want to use. Typically, you will set this to ['jasmine'], ['mocha'] or ['qunit']... - * Please note just about all frameworks in Karma require an additional plugin/framework library to be installed (via NPM). - */ - frameworks?: string[]; - /** - * @default 'localhost' - * @description Hostname to be used when capturing browsers. - */ - hostname?: string; - /** - * @default {} - * @description Options object to be used by Node's https class. - * Object description can be found in the - * [NodeJS.org API docs](https://nodejs.org/api/tls.html#tls_tls_createserver_options_secureconnectionlistener) - */ - httpsServerOptions?: https.ServerOptions; - /** - * @default config.LOG_INFO - * Possible values: - *
            - *
          • config.LOG_DISABLE
          • - *
          • config.LOG_ERROR
          • - *
          • config.LOG_WARN
          • - *
          • config.LOG_INFO
          • - *
          • config.LOG_DEBUG
          • - *
          - * @description Level of logging. - */ - logLevel?: string; - /** - * @default [{type: 'console'}] - * @description A list of log appenders to be used. See the documentation for [log4js] for more information. - */ - loggers?: Log4jsAppenderConfigBase[]; - /** - * @default [] - * @description List of names of additional middleware you want the - * Karma server to use. Middleware will be used in the order listed. - * You must have installed the middleware via a plugin/framework - * (either inline or via NPM). Additional information can be found in - * [plugins](http://karma-runner.github.io/2.0/config/plugins.html). - * The plugin must provide an express/connect middleware function - * (details about this can be found in the - * [Express](http://expressjs.com/guide/using-middleware.html) docs). - */ - middleware?: string[]; - /** - * @default {} - * @description Redefine default mapping from file extensions to MIME-type. - * Set property name to required MIME, provide Array of extensions (without dots) as it's value. - */ - mime?: {[type: string]: string[]}; - /** - * @default ['karma-*'] - * @description List of plugins to load. A plugin can be a string (in which case it will be required - * by Karma) or an inlined plugin - Object. - * By default, Karma loads all sibling NPM modules which have a name starting with karma-*. - * Note: Just about all plugins in Karma require an additional library to be installed (via NPM). - */ - plugins?: any[]; - /** - * @default 9876 - * @description The port where the web server will be listening. - */ - port?: number; - /** - * @default {'**\/*.coffee': 'coffee'} - * @description A map of preprocessors to use. - * - * Preprocessors can be loaded through [plugins]. - * - * Note: Just about all preprocessors in Karma (other than CoffeeScript and some other defaults) - * require an additional library to be installed (via NPM). - * - * Be aware that preprocessors may be transforming the files and file types that are available at run time. For instance, - * if you are using the "coverage" preprocessor on your source files, if you then attempt to interactively debug - * your tests, you'll discover that your expected source code is completely changed from what you expected. Because - * of that, you'll want to engineer this so that your automated builds use the coverage entry in the "reporters" list, - * but your interactive debugging does not. - * - */ - preprocessors?: { [name: string]: string | string[] } - /** - * @default 'http:' - * Possible Values: - *
            - *
          • http:
          • - *
          • https:
          • - *
          - * @description Protocol used for running the Karma webserver. - * Determines the use of the Node http or https class. - * Note: Using 'https:' requires you to specify httpsServerOptions. - */ - protocol?: string; - /** - * @default {} - * @description A map of path-proxy pairs. - */ - proxies?: { [path: string]: string } - /** - * @default true - * @description Whether or not Karma or any browsers should raise an error when an inavlid SSL certificate is found. - */ - proxyValidateSSL?: boolean; - /** - * @default 0 - * @description Karma will report all the tests that are slower than given time limit (in ms). - * This is disabled by default (since the default value is 0). - */ - reportSlowerThan?: number; - /** - * @default ['progress'] - * Possible Values: - *
            - *
          • dots
          • - *
          • progress
          • - *
          - * @description A list of reporters to use. - * Additional reporters, such as growl, junit, teamcity or coverage can be loaded through plugins. - * Note: Just about all additional reporters in Karma (other than progress) require an additional library to be installed (via NPM). - */ - reporters?: string[]; - /** - * @default false - * @description Continuous Integration mode. - * If true, Karma will start and capture all configured browsers, run tests and then exit with an exit code of 0 or 1 depending - * on whether all tests passed or any tests failed. - */ - singleRun?: boolean; - /** - * @default ['polling', 'websocket'] - * @description An array of allowed transport methods between the browser and testing server. This configuration setting - * is handed off to [socket.io](http://socket.io/) (which manages the communication - * between browsers and the testing server). - */ - transports?: string[]; - /** - * @default '/' - * @description The base url, where Karma runs. - * All of Karma's urls get prefixed with the urlRoot. This is helpful when using proxies, as - * sometimes you might want to proxy a url that is already taken by Karma. - */ - urlRoot?: string; - } - - interface ClientOptions { - /** - * @default undefined - * @description When karma run is passed additional arguments on the command-line, they - * are passed through to the test adapter as karma.config.args (an array of strings). - * The client.args option allows you to set this value for actions other than run. - * How this value is used is up to your test adapter - you should check your adapter's - * documentation to see how (and if) it uses this value. - */ - args?: string[]; - /** - * @default true - * @description Run the tests inside an iFrame or a new window - * If true, Karma runs the tests inside an iFrame. If false, Karma runs the tests in a new window. Some tests may not run in an - * iFrame and may need a new window to run. - */ - useIframe?: boolean; - /** - * @default true - * @description Capture all console output and pipe it to the terminal. - */ - captureConsole?: boolean; - /** - * @default false - * @description Run the tests on the same window as the client, without using iframe or a new window - */ - runInParent?: boolean; - /** - * @default true - * @description Clear the context window - * If true, Karma clears the context window upon the completion of running the tests. - * If false, Karma does not clear the context window upon the completion of running the tests. - * Setting this to false is useful when embedding a Jasmine Spec Runner Template. - */ - clearContext?: boolean; - } - - interface FilePattern { - /** - * The pattern to use for matching. This property is mandatory. - */ - pattern: string; - /** - * @default true - * @description If autoWatch is true all files that have set watched to true will be watched - * for changes. - */ - watched?: boolean; - /** - * @default true - * @description Should the files be included in the browser using \n' + + "but do b.ca", + { + ignoreTags: ["script", "style"] + } +); + +/* nl2br */ + +/* tagName */ + +linkifyHtml("github.com", { + tagName: "span" +}); + +linkifyHtml("#swag", { + tagName: { + hashtag: "span" + } +}); + +/* target */ + +linkifyHtml("github.com", { + target: "_parent" +}); + +linkifyHtml("test-email@example.com", { + target: { + url: "_parent", + email: null + } +}); + +/* validate */ + +// Don't linkify links that don't begin in a protocol +// e.g., "http://google.com" will be linkified, but "google.com" will not. +linkifyHtml("www.google.com", { + validate: { + url(value) { + return /^(http|ftp)s?:\/\//.test(value); + } + } +}); diff --git a/types/linkifyjs/tsconfig.json b/types/linkifyjs/tsconfig.json new file mode 100644 index 0000000000..52b1940fcd --- /dev/null +++ b/types/linkifyjs/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 + }, + "files": [ + "index.d.ts", + "html.d.ts", + "linkifyjs-tests.ts" + ] +} diff --git a/types/linkifyjs/tslint.json b/types/linkifyjs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/linkifyjs/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/collection.d.ts b/types/lodash/common/collection.d.ts index 2e38422b2d..d8ddc97197 100644 --- a/types/lodash/common/collection.d.ts +++ b/types/lodash/common/collection.d.ts @@ -1658,7 +1658,7 @@ declare module "../index" { orderBy( collection: List | null | undefined, iteratees?: Many>, - orders?: Many + orders?: Many ): T[]; /** @@ -1667,7 +1667,7 @@ declare module "../index" { orderBy( collection: List | null | undefined, iteratees?: Many>, - orders?: Many + orders?: Many ): T[]; /** @@ -1676,7 +1676,7 @@ declare module "../index" { orderBy( collection: T | null | undefined, iteratees?: Many>, - orders?: Many + orders?: Many ): Array; /** @@ -1685,7 +1685,7 @@ declare module "../index" { orderBy( collection: T | null | undefined, iteratees?: Many>, - orders?: Many + orders?: Many ): Array; } @@ -1696,7 +1696,7 @@ declare module "../index" { orderBy( this: LoDashImplicitWrapper | null | undefined>, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashImplicitWrapper; /** @@ -1705,7 +1705,7 @@ declare module "../index" { orderBy( this: LoDashImplicitWrapper | null | undefined>, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashImplicitWrapper; /** @@ -1714,7 +1714,7 @@ declare module "../index" { orderBy( this: LoDashImplicitWrapper, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashImplicitWrapper>; /** @@ -1723,7 +1723,7 @@ declare module "../index" { orderBy( this: LoDashImplicitWrapper, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashImplicitWrapper>; } @@ -1734,7 +1734,7 @@ declare module "../index" { orderBy( this: LoDashExplicitWrapper | null | undefined>, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashExplicitWrapper; /** @@ -1743,7 +1743,7 @@ declare module "../index" { orderBy( this: LoDashExplicitWrapper | null | undefined>, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashExplicitWrapper; /** @@ -1752,7 +1752,7 @@ declare module "../index" { orderBy( this: LoDashExplicitWrapper, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashExplicitWrapper>; /** @@ -1761,7 +1761,7 @@ declare module "../index" { orderBy( this: LoDashExplicitWrapper, iteratees?: Many>, - orders?: Many + orders?: Many ): LoDashExplicitWrapper>; } diff --git a/types/lodash/common/common.d.ts b/types/lodash/common/common.d.ts index 864450b1bd..66dbafafb8 100644 --- a/types/lodash/common/common.d.ts +++ b/types/lodash/common/common.d.ts @@ -127,21 +127,21 @@ declare module "../index" { * @param key The key of the value to remove. * @return Returns `true` if the entry was removed successfully, else `false`. */ - delete(key: string): boolean; + delete(key: any): boolean; /** * Gets the cached value for `key`. * @param key The key of the value to get. * @return Returns the cached value. */ - get(key: string): any; + get(key: any): any; /** * Checks if a cached value for `key` exists. * @param key The key of the entry to check. * @return Returns `true` if an entry for `key` exists, else `false`. */ - has(key: string): boolean; + has(key: any): boolean; /** * Sets `value` to `key` of the cache. @@ -149,12 +149,12 @@ declare module "../index" { * @param value The value to cache. * @return Returns the cache object. */ - set(key: string, value: any): Dictionary; + set(key: any, value: any): this; /** * Removes all key-value entries from the map. */ - clear(): void; + clear?: () => void; } interface MapCacheConstructor { new (): MapCache; 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/fp.d.ts b/types/lodash/fp.d.ts index cdc850d444..9b6cf52ccb 100644 --- a/types/lodash/fp.d.ts +++ b/types/lodash/fp.d.ts @@ -2312,25 +2312,25 @@ declare namespace _ { type LodashOnce = any>(func: T) => T; interface LodashOrderBy { (iteratees: lodash.Many<(value: T) => lodash.NotVoid>): LodashOrderBy1x1; - (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x2; - (iteratees: lodash.Many<(value: T) => lodash.NotVoid>, orders: lodash.Many): LodashOrderBy1x3; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x2; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid>, orders: lodash.Many): LodashOrderBy1x3; (iteratees: lodash.__, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x4; (iteratees: lodash.Many<(value: T) => lodash.NotVoid>, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x5; - (iteratees: lodash.__, orders: lodash.Many, collection: lodash.List | null | undefined): LodashOrderBy1x6; - (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: lodash.List | null | undefined): T[]; + (iteratees: lodash.__, orders: lodash.Many, collection: lodash.List | null | undefined): LodashOrderBy1x6; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: lodash.List | null | undefined): T[]; (iteratees: lodash.Many>): LodashOrderBy2x1; - (iteratees: lodash.Many>, orders: lodash.Many): LodashOrderBy2x3; + (iteratees: lodash.Many>, orders: lodash.Many): LodashOrderBy2x3; (iteratees: lodash.Many>, orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy2x5; (iteratees: lodash.__, orders: lodash.__, collection: T | null | undefined): LodashOrderBy3x4; (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid>, orders: lodash.__, collection: T | null | undefined): LodashOrderBy3x5; - (iteratees: lodash.__, orders: lodash.Many, collection: T | null | undefined): LodashOrderBy3x6; - (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: T | null | undefined): Array; + (iteratees: lodash.__, orders: lodash.Many, collection: T | null | undefined): LodashOrderBy3x6; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many, collection: T | null | undefined): Array; (iteratees: lodash.Many>, orders: lodash.__, collection: T | null | undefined): LodashOrderBy4x5; } interface LodashOrderBy1x1 { - (orders: lodash.Many): LodashOrderBy1x3; + (orders: lodash.Many): LodashOrderBy1x3; (orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy1x5; - (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; + (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; (orders: lodash.__, collection: T1 | null | undefined): LodashOrderBy3x5; } interface LodashOrderBy1x2 { @@ -2347,32 +2347,32 @@ declare namespace _ { } interface LodashOrderBy1x4 { (iteratees: lodash.Many<(value: T) => lodash.NotVoid>): LodashOrderBy1x5; - (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x6; - (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): T[]; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy1x6; + (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): T[]; (iteratees: lodash.Many>): LodashOrderBy2x5; } - type LodashOrderBy1x5 = (orders: lodash.Many) => T[]; + type LodashOrderBy1x5 = (orders: lodash.Many) => T[]; type LodashOrderBy1x6 = (iteratees: lodash.Many<(value: T) => lodash.NotVoid> | lodash.Many>) => T[]; interface LodashOrderBy2x1 { - (orders: lodash.Many): LodashOrderBy2x3; + (orders: lodash.Many): LodashOrderBy2x3; (orders: lodash.__, collection: lodash.List | null | undefined): LodashOrderBy2x5; - (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; + (orders: lodash.Many, collection: lodash.List | object | null | undefined): T[]; (orders: lodash.__, collection: T1 | null | undefined): LodashOrderBy4x5; } interface LodashOrderBy2x3 { (collection: lodash.List | null | undefined): T[]; (collection: object | null | undefined): object[]; } - type LodashOrderBy2x5 = (orders: lodash.Many) => T[]; + type LodashOrderBy2x5 = (orders: lodash.Many) => T[]; interface LodashOrderBy3x4 { (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid>): LodashOrderBy3x5; - (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy3x6; - (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): Array; + (iteratees: lodash.__, orders: lodash.Many): LodashOrderBy3x6; + (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>, orders: lodash.Many): Array; (iteratees: lodash.Many>): LodashOrderBy4x5; } - type LodashOrderBy3x5 = (orders: lodash.Many) => Array; + type LodashOrderBy3x5 = (orders: lodash.Many) => Array; type LodashOrderBy3x6 = (iteratees: lodash.Many<(value: T[keyof T]) => lodash.NotVoid> | lodash.Many>) => Array; - type LodashOrderBy4x5 = (orders: lodash.Many) => Array; + type LodashOrderBy4x5 = (orders: lodash.Many) => Array; interface LodashOverArgs { (func: (...args: any[]) => any): LodashOverArgs1x1; (func: lodash.__, transforms: lodash.Many<(...args: any[]) => any>): LodashOverArgs1x2; diff --git a/types/lodash/lodash-tests.ts b/types/lodash/lodash-tests.ts index 0515136714..9d2547dcf4 100644 --- a/types/lodash/lodash-tests.ts +++ b/types/lodash/lodash-tests.ts @@ -3467,7 +3467,7 @@ fp.now(); // $ExpectType number delete(key: string) { return true; }, get(key: string): any { return 1; }, has(key: string) { return true; }, - set(key: string, value: any): _.Dictionary { return {}; }, + set(key: string, value: any): _.MapCache { return this; }, clear() { }, }; @@ -3484,6 +3484,11 @@ fp.now(); // $ExpectType number // $ExpectType MapCache new _.memoize.Cache(); + _.memoize.Cache = WeakMap; + _.memoize.Cache = Map; + const memoizedFn = _.memoize(memoizeFn); + memoizedFn.cache = new WeakMap(); + memoizedFn.cache = new Map(); } // _.overArgs @@ -4200,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/looks-same/index.d.ts b/types/looks-same/index.d.ts new file mode 100644 index 0000000000..6423e5fe4c --- /dev/null +++ b/types/looks-same/index.d.ts @@ -0,0 +1,138 @@ +// Type definitions for looks-same 4.0 +// Project: https://github.com/gemini-testing/looks-same/releases +// Definitions by: xcatliu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +type LooksSameCallback = (error: Error | null, equal: boolean) => any; + +/** + * The options passed to looksSame function + */ +interface LooksSameOptions { + /** + * By default, it will detect only noticeable differences. If you wish to detect any difference, use strict options. + */ + strict?: boolean; + /** + * You can also adjust the ΔE value that will be treated as error in non-strict mode. + */ + tolerance?: number; + /** + * Some devices can have different proportion between physical and logical screen resolutions also known as pixel ratio. + * Default value for this proportion is 1. + * This param also affects the comparison result, so it can be set manually with pixelRatio option. + */ + pixelRatio?: number; + /** + * For visual regression tasks it may be useful to ignore text caret in text input elements. You can do it with ignoreCaret option. + */ + ignoreCaret?: boolean; + /** + * Some images has difference while comparing because of antialiasing. + * These diffs will be ignored by default. You can use ignoreAntialiasing option with false value to disable ignoring such diffs. + * In that way antialiased pixels will be marked as diffs. + */ + ignoreAntialiasing?: boolean; + /** + * Sometimes the antialiasing algorithm can work incorrectly due to some features of the browser rendering engine. + * Use the option antialiasingTolerance to make the algorithm less strict. + * With this option you can specify the minimum difference in brightness (zero by default) + * between the darkest/lightest pixel (which is adjacent to the antialiasing pixel) and theirs adjacent pixels. + * + * We recommend that you don't increase this value above 10. If you need to increase more than 10 then this is definitely not antialiasing. + */ + antialiasingTolerance?: number; +} + +/** + * The options passed to looksSame.createDiff function without diff + */ +interface CreateDiffAsBufferOptions { + /** + * The baseline image path + */ + reference: string; + /** + * The current image path + */ + current: string; + /** + * Color to highlight the differences + * e.g. '#ff00ff' + */ + highlightColor: string; + /** + * strict comparsion + */ + strict: boolean; + /** + * ΔE value that will be treated as error in non-strict mode + */ + tolerance: number; +} + +/** + * The options passed to looksSame.createDiff function + */ +interface CreateDiffOptions extends CreateDiffAsBufferOptions { + /** + * The diff image path to store + */ + diff: string; +} + +/** + * Pass to looksSame.colors function + */ +interface LooksSameColor { + /** + * Red + */ + R: number; + /** + * Green + */ + G: number; + /** + * Blue + */ + B: number; +} + +/** + * Compare two images with options + * @param image1 The first image path + * @param image2 The second image path + * @param options The options passed to looksSame function + * @param callback Call when finish compare + */ +declare function looksSame(image1: string, image2: string, options: LooksSameOptions, callback: LooksSameCallback): void; +/** + * Compare two images + * @param image1 The first image path + * @param image2 The second image path + * @param callback Call when finish compare + */ +declare function looksSame(image1: string, image2: string, callback: LooksSameCallback): void; + +// https://stackoverflow.com/questions/44058101/typescript-declare-third-party-modules +declare namespace looksSame { + function createDiff(options: CreateDiffOptions, callback: (error: Error | null) => any): void; + function createDiff(options: CreateDiffAsBufferOptions, callback: (error: Error | null, buffer: Buffer) => any): void; + + /** + * Compare two colors + * @param color1 The first color + * @param color2 The second color + * @param options The options passed to looksSame.colors function + */ + function colors(color1: LooksSameColor, color2: LooksSameColor, options: { tolerance: number }): void; +} + +/** + * Node.js library for comparing PNG-images, taking into account human color perception. + * It is created specially for the needs of visual regression testing for gemini utility, but can be used for other purposes. + */ +export = looksSame; diff --git a/types/looks-same/looks-same-tests.ts b/types/looks-same/looks-same-tests.ts new file mode 100644 index 0000000000..f788d2119e --- /dev/null +++ b/types/looks-same/looks-same-tests.ts @@ -0,0 +1,56 @@ +import looksSame = require('looks-same'); + +looksSame('image1.png', 'image2.png', (error, equal) => { + // equal will be true, if images looks the same +}); + +looksSame('image1.png', 'image2.png', {strict: true}, (error, equal) => { + // ... +}); + +looksSame('image1.png', 'image2.png', {tolerance: 5}, (error, equal) => { + // ... +}); + +looksSame('image1.png', 'image2.png', {pixelRatio: 2}, (error, equal) => { + // ... +}); + +looksSame('image1.png', 'image2.png', {ignoreCaret: true}, (error, equal) => { + // ... +}); + +looksSame('image1.png', 'image2.png', {ignoreAntialiasing: true}, (error, equal) => { + // ... +}); + +looksSame('image1.png', 'image2.png', {ignoreAntialiasing: true, antialiasingTolerance: 3}, (error, equal) => { + // ... +}); + +looksSame.createDiff({ + reference: '/path/to/reference/image.png', + current: '/path/to/current/image.png', + diff: '/path/to/save/diff/to.png', + highlightColor: '#ff00ff', // color to highlight the differences + strict: false, // strict comparsion + tolerance: 2.5 +}, (error) => { +}); + +looksSame.createDiff({ + // exactly same options as above, but without diff + reference: '/path/to/reference/image.png', + current: '/path/to/current/image.png', + highlightColor: '#ff00ff', // color to highlight the differences + strict: false, // strict comparsion + tolerance: 2.5 +}, (error, buffer) => { + // ... +}); + +looksSame.colors( + {R: 255, G: 0, B: 0}, + {R: 254, G: 1, B: 1}, + {tolerance: 2.5} +); diff --git a/types/looks-same/tsconfig.json b/types/looks-same/tsconfig.json new file mode 100644 index 0000000000..a6aa3dbfd2 --- /dev/null +++ b/types/looks-same/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", + "looks-same-tests.ts" + ] +} diff --git a/types/looks-same/tslint.json b/types/looks-same/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/looks-same/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/loopback/index.d.ts b/types/loopback/index.d.ts index 9d8563a810..58f5901a86 100644 --- a/types/loopback/index.d.ts +++ b/types/loopback/index.d.ts @@ -3193,9 +3193,10 @@ declare namespace l { /** * The Role model * @class Role + * @inherits {PersistedModel} * @header Role objec */ - class Role { + class Role extends PersistedModel { /** * List roles for a given principal. * @param {any} context The security context. diff --git a/types/lowdb/_lodash.d.ts b/types/lowdb/_lodash.d.ts index ca8aace259..7267aab0d9 100644 --- a/types/lowdb/_lodash.d.ts +++ b/types/lowdb/_lodash.d.ts @@ -631,22 +631,22 @@ declare module "./index" { orderBy( this: LoDashExplicitSyncWrapper<_.List | null | undefined>, iteratees?: _.Many<_.ListIterator>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitSyncWrapper; orderBy( this: LoDashExplicitSyncWrapper<_.List | null | undefined>, iteratees?: _.Many<_.ListIteratee>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitSyncWrapper; orderBy( this: LoDashExplicitSyncWrapper, iteratees?: _.Many<_.ObjectIterator>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitSyncWrapper>; orderBy( this: LoDashExplicitSyncWrapper, iteratees?: _.Many<_.ObjectIteratee>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitSyncWrapper>; partition( this: LoDashExplicitSyncWrapper<_.List | null | undefined>, @@ -2227,22 +2227,22 @@ declare module "./index" { orderBy( this: LoDashExplicitAsyncWrapper<_.List | null | undefined>, iteratees?: _.Many<_.ListIterator>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitAsyncWrapper; orderBy( this: LoDashExplicitAsyncWrapper<_.List | null | undefined>, iteratees?: _.Many<_.ListIteratee>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitAsyncWrapper; orderBy( this: LoDashExplicitAsyncWrapper, iteratees?: _.Many<_.ObjectIterator>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitAsyncWrapper>; orderBy( this: LoDashExplicitAsyncWrapper, iteratees?: _.Many<_.ObjectIteratee>, - orders?: _.Many + orders?: _.Many ): LoDashExplicitAsyncWrapper>; partition( this: LoDashExplicitAsyncWrapper<_.List | null | undefined>, diff --git a/types/lowdb/tslint.json b/types/lowdb/tslint.json index dfea11be1a..c56e92eedb 100644 --- a/types/lowdb/tslint.json +++ b/types/lowdb/tslint.json @@ -1,6 +1,10 @@ { "extends": "dtslint/dt.json", "rules": { - "no-misused-new": false + // All are TODOs + "max-line-length": false, + "no-misused-new": false, + "no-unnecessary-generics": false, + "unified-signatures": false } } 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 3db14f85ea..f93cf8562a 100644 --- a/types/ltx/tslint.json +++ b/types/ltx/tslint.json @@ -1 +1,3 @@ -{ "extends": "dtslint/dt.json" } +{ + "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/luxon/index.d.ts b/types/luxon/index.d.ts index e96e389894..8d5b17d697 100644 --- a/types/luxon/index.d.ts +++ b/types/luxon/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for luxon 1.2 +// Type definitions for luxon 1.4 // Project: https://github.com/moment/luxon#readme // Definitions by: Colby DeHart // Hyeonseok Yang // Jonathan Siebern +// Matt R. Wilson // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -22,6 +23,11 @@ declare module 'luxon' { round?: boolean; }; + type ToSQLOptions = { + includeOffset?: boolean; + includeZone?: boolean; + }; + type ISOTimeOptions = { suppressMilliseconds?: boolean; suppressSeconds?: boolean; @@ -65,6 +71,17 @@ declare module 'luxon' { conversionAccuracy?: string; }; + type ExplainedFormat = { + input: string; + tokens: Array<{ literal: boolean, val: string }>, + regex?: RegExp; + rawMatches?: RegExpMatchArray | null; + matches?: {[k: string]: any}; + result?: {[k: string]: any} | null; + zone?: Zone | null; + invalidReason?: string; + }; + class DateTime { static readonly DATETIME_FULL: DateTimeFormatOptions; static readonly DATETIME_FULL_WITH_SECONDS: DateTimeFormatOptions; @@ -108,7 +125,7 @@ declare module 'luxon' { text: string, format: string, opts?: DateTimeOptions - ): object; + ): ExplainedFormat; /** * @deprecated since 0.3.0. Use fromFormat instead */ @@ -124,7 +141,7 @@ declare module 'luxon' { text: string, format: string, options?: DateTimeOptions - ): object; + ): ExplainedFormat; static invalid(reason: any): DateTime; static local( year?: number, @@ -154,6 +171,7 @@ declare module 'luxon' { hour: number; invalidReason: string; isInDST: boolean; + isInLeapYear: boolean; isOffsetFixed: boolean; isValid: boolean; locale: string; @@ -212,9 +230,9 @@ declare module 'luxon' { toMillis(): number; toObject(options?: { includeConfig?: boolean }): DateObject; toRFC2822(): string; - toSQL(options?: Object): string; + toSQL(options?: ToSQLOptions): string; toSQLDate(): string; - toSQLTime(options?: Object): string; + toSQLTime(options?: ToSQLOptions): string; toString(): string; toUTC(offset?: number, options?: ZoneOptions): DateTime; until(other: DateTime): Interval; diff --git a/types/luxon/luxon-tests.ts b/types/luxon/luxon-tests.ts index 017f07b0c6..587210815c 100644 --- a/types/luxon/luxon-tests.ts +++ b/types/luxon/luxon-tests.ts @@ -33,11 +33,17 @@ getters.zoneName; getters.offset; getters.daysInMonth; getters.ordinal; +getters.isInLeapYear; dt.toLocaleString(); dt.toLocaleString(DateTime.DATE_MED); dt.toISO(); dt.toISO({includeOffset: true}); +dt.toSQL(); +dt.toSQL({includeOffset: false, includeZone: true}); +dt.toSQLDate(); +dt.toSQLTime(); +dt.toSQLTime({includeOffset: false, includeZone: true}); dt.plus({ hours: 3, minutes: 2 }); dt.minus({ days: 7 }); @@ -61,6 +67,8 @@ DateTime.utc().toLocal(); DateTime.fromMillis(1527780819458).toMillis(); +const {input, result, zone} = DateTime.fromFormatExplain("Aug 6 1982", "MMMM d yyyy"); + /* Duration */ const dur = Duration.fromObject({ hours: 2, minutes: 7 }); dt.plus(dur); diff --git a/types/luxon/tslint.json b/types/luxon/tslint.json index 764ebe0c97..bc0a6d599a 100644 --- a/types/luxon/tslint.json +++ b/types/luxon/tslint.json @@ -1,7 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { - "ban-types": false, "no-single-declare-module": false, "interface-over-type-literal": false, "no-declare-current-package": false diff --git a/types/lzma-native/index.d.ts b/types/lzma-native/index.d.ts new file mode 100644 index 0000000000..33165885da --- /dev/null +++ b/types/lzma-native/index.d.ts @@ -0,0 +1,129 @@ +// Type definitions for lzma-native 4.0 +// Project: https://github.com/addaleax/lzma-native +// Definitions by: Evan Cameron +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 +/// + +import { Stream } from "stream"; +export interface LzmaOptions { + synchronous?: boolean; + bufsize?: number; + memlimit?: number; + check?: Check; + preset?: Preset; + flags?: + | "TELL_NO_CHECK" + | "TELL_UNSUPPORTED_CHECK" + | "TELL_ANY_CHECK" + | "CONCATENATED"; + threads?: number; + blockSize?: number; + timeout?: number; +} + +export type Check = + | "CHECK_CRC32" + | "CHECK_CRC64" + | "CHECK_NONE" + | "CHECK_SHA256"; + +export type Coders = + | "easyEncoder" + | "aloneDecoder" + | "rawEncoder" + | "autoDecoder" + | "aloneEncoder" + | "streamEncoder" + | "streamDecoder"; + +export type Preset = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9; + +export interface FileOptions { + fileSize: number; + memlimit?: number; + read: ( + count: number, + offset: number, + cb: (err: any, buffer: Buffer) => void + ) => void; +} + +export interface StreamInfo { + streamPadding: number; + memlimit: number; + streams: number; + blocks: number; + fileSize: number; + uncompressedSize: number; + checks: number; +} + +export function createStream( + coder: Coders, + options?: LzmaOptions +): JSLzmaStream; + +export function createCompressor(options?: LzmaOptions): JSLzmaStream; +export function createDecompressor(options?: LzmaOptions): JSLzmaStream; +export function crc32( + input: string, + encoding?: string, + previous?: number +): string; +export function isXZ(buf: Buffer | string): boolean; +export function versionString(): string; +export function versionNumber(): number; +export function checkSize(check: Check): number; +export function easyDecoderMemusage(preset: Preset): number; +export function easyEncoderMemusage(preset: Preset): number; +export function rawDecoderMemusage(preset: Preset): number; +export function rawEncoderMemusage(preset: Preset): number; + +export function Compressor( + preset?: Preset, + options?: LzmaOptions +): JSLzmaStream; +export function Decompressor(options?: LzmaOptions): JSLzmaStream; + +export function parseFileIndex( + options: FileOptions, + callback?: (err: any, info?: StreamInfo) => void +): void; +export function parseFileIndexFD( + fileDescriptor: number, + callback?: (err: any, info?: StreamInfo) => void +): void; + +export function compress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function decompress( + buf: Buffer | string, + options?: LzmaOptions | Preset, + on_finish?: (result: Buffer) => void +): void; +export function LZMA(): { + compress( + buf: Buffer | string, + mode: Preset, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; + decompress( + buf: Buffer | string, + on_finish: (result: Buffer) => void, + on_progress?: (progress: number) => void + ): void; +}; + +export class JSLzmaStream extends Stream.Transform { + constructor(nativeStream: Stream, options: LzmaOptions); + bufsize(): number; + bufsize(size: number): void; + totalInt(): number; + totalOut(): number; + cleanUp(): void; +} diff --git a/types/lzma-native/lzma-native-tests.ts b/types/lzma-native/lzma-native-tests.ts new file mode 100644 index 0000000000..44a5eab221 --- /dev/null +++ b/types/lzma-native/lzma-native-tests.ts @@ -0,0 +1,55 @@ +import * as lzma from "lzma-native"; +import * as fs from "fs"; + +const compressor = lzma.createCompressor(); +const input = fs.createReadStream("tsconfig.json"); +const output = fs.createWriteStream("tsconfig.json.xz"); + +input.pipe(compressor).pipe(output); + +lzma.compress("Banana", undefined, result => { + console.log(result); // +}); + +lzma.compress("Bananas", 6, result => { + lzma.decompress(result, undefined, decompressedResult => { + console.log(decompressedResult.toString() === "Bananas"); + }); +}); + +lzma.LZMA().compress("Bananas", 4, result => { + lzma.LZMA().decompress(result, decompressedResult => { + console.log("Bananas" === decompressedResult.toString()); + }); +}); + +const comp = lzma.Compressor(); + +process.stdin.pipe(comp).pipe(process.stdout); +lzma.crc32("Banana"); // => 69690105 +lzma.checkSize("CHECK_SHA256"); // => 16 +lzma.checkSize("CHECK_CRC32"); // => 4 +lzma.easyDecoderMemusage(6); // => 8454192 +lzma.easyEncoderMemusage(6); // => 97620499 +lzma.versionString(); // => '5.2.3' +lzma.versionNumber(); // => 50020012 +lzma.isXZ("Banana"); // => false + +fs.open("test/hamlet.txt.xz", "r", (err: any, fd: number) => { + if (err) return; + // handle error + lzma.parseFileIndexFD(fd, (err, info) => { + // handle error + if (err) { + console.log(err); + } + // do something with e.g. info.uncompressedSize + + fs.close(fd, (err: any) => { + /* handle error */ + if (err) { + console.log(err); + } + }); + }); +}); diff --git a/types/lzma-native/tsconfig.json b/types/lzma-native/tsconfig.json new file mode 100644 index 0000000000..fa7667f123 --- /dev/null +++ b/types/lzma-native/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitThis": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "lzma-native-tests.ts"] +} diff --git a/types/lzma-native/tslint.json b/types/lzma-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/lzma-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mailgun-js/index.d.ts b/types/mailgun-js/index.d.ts index 0ab5efcf45..7c6284059e 100644 --- a/types/mailgun-js/index.d.ts +++ b/types/mailgun-js/index.d.ts @@ -1,13 +1,14 @@ // Type definitions for mailgun-js 0.16 // Project: https://github.com/bojand/mailgun-js // Definitions by: Sampson Oliver +// Andi Pätzold // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 /// -declare const out: Mailgun.MailgunExport; -export = out; +declare const Mailgun: Mailgun.MailgunExport; +export = Mailgun; declare namespace Mailgun { interface ConstructorParams { @@ -41,8 +42,7 @@ declare namespace Mailgun { contentType?: string; } - class Attachment { - constructor(params: AttachmentParams); + interface Attachment { data: string | Buffer | NodeJS.ReadWriteStream; filename?: string; knownLength?: number; @@ -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 { @@ -126,30 +129,54 @@ declare namespace Mailgun { unparseable: string[]; } + type ValidationCallback = (error: Error, body: ValidateResponse) => void; + + interface ValidationOptionsPublic { + api_key?: string; + mailbox_verification?: boolean | "true" | "false"; + } + + interface ValidationOptionsPrivate { + mailbox_verification?: boolean | "true" | "false"; + } + interface ValidateResponse { + address: string; + did_you_mean: string | null; + is_disposable_address: boolean; + is_role_address: boolean; is_valid: boolean; + mailbox_verification: "true" | "false" | "unknown" | null; + parts: { + display_name: string | null; + domain: string; + local_part: string; + }; } } interface Mailgun { messages(): Messages; lists(list: string): Lists; - Attachment: typeof Attachment; + Attachment: new (params: AttachmentParams) => Attachment; validateWebhook( bodyTimestamp: number, bodyToken: string, bodySignature: string ): boolean; - parse( - addressList: string[], - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + parse(addressList: string[], callback?: validation.ValidationCallback): Promise; - validate( - address: string, - callback?: (error: Error, body: validation.ValidateResponse) => void - ): Promise; + validate(address: string, callback: validation.ValidationCallback): void; + validate(address: string, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; + // tslint:disable-next-line unified-signatures + validate(address: string, isPrivate: boolean, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: false, opts: validation.ValidationOptionsPublic, callback: validation.ValidationCallback): void; + validate(address: string, isPrivate: true, opts: validation.ValidationOptionsPrivate, callback: validation.ValidationCallback): void; + + validate(address: string, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: false, opts?: validation.ValidationOptionsPublic): Promise; + validate(address: string, isPrivate: true, opts?: validation.ValidationOptionsPrivate): Promise; } interface Lists { diff --git a/types/mailgun-js/mailgun-js-tests.ts b/types/mailgun-js/mailgun-js-tests.ts index dfbe8ab4a1..0d830308d1 100644 --- a/types/mailgun-js/mailgun-js-tests.ts +++ b/types/mailgun-js/mailgun-js-tests.ts @@ -20,13 +20,44 @@ mailgun.messages().send( } ); -mailgun.messages().send( - { - to: "someone@email.com", - attachment: new mailgun.Attachment({ +const exampleSendData: mailgunFactory.messages.SendData = { + to: "someone@email.com", + attachment: new mailgun.Attachment({ + data: "filepath", + filename: "my_custom_name.png" + }), + inline: [ + new mailgun.Attachment({ data: "filepath", - filename: "my_custom_name.png" - }) - }, - (err, body) => {} -); + filename: "my_custom_name_2.png" + }), + "my_custom_file_3.png", + Buffer.from("plain text") + ] + }; + +mailgun.messages().send(exampleSendData, (err, body) => {}); + +let validationResultPromise: Promise; +validationResultPromise = mailgun.validate("foo@mailgun.net"); +validationResultPromise = mailgun.validate("foo@mailgun.net", true); +validationResultPromise = mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }); +validationResultPromise = mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }); +mailgun.validate("foo@mailgun.net", (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, (error, body) => {}); +mailgun.validate("foo@mailgun.net", true, { mailbox_verification: true }, (error, body) => {}); +mailgun.validate("foo@mailgun.net", { mailbox_verification: false, api_key: "..." }, (error, body) => {}); + +const validationResult6: mailgunFactory.validation.ValidateResponse = { + address: "foo@mailgun.net", + did_you_mean: "bar@mailgun.net", + is_disposable_address: false, + is_role_address: true, + is_valid: true, + mailbox_verification: "true", + parts: { + display_name: "foo", + domain: "mailgun.net", + local_part: "foo" + } +}; diff --git a/types/maker.js/maker.js-tests.ts b/types/maker.js/maker.js-tests.ts index f5f9d9db16..ba02fdef89 100644 --- a/types/maker.js/maker.js-tests.ts +++ b/types/maker.js/maker.js-tests.ts @@ -100,9 +100,9 @@ function test() { function testKit() { makerjs.kit.construct(null, null); makerjs.kit.getParameterValues(null); - ({}).max; - ({}).metaParameters; - ({}).notes; + ({} as MakerJs.IMetaParameter).max; + ({} as MakerJs.IKit).metaParameters; + ({} as MakerJs.IKit).notes; } function testMeasure() { diff --git a/types/makeup-expander/index.d.ts b/types/makeup-expander/index.d.ts new file mode 100644 index 0000000000..90bd660581 --- /dev/null +++ b/types/makeup-expander/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for makeup-expander 0.4 +// Project: https://github.com/makeup-js/makeup-expander +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +declare namespace Expander { + interface Options { + autoCollapse?: boolean; + collapseOnClickOut?: boolean; + collapseOnFocusOut?: boolean; + collapseOnMouseOut?: boolean; + contentSelector?: string; + expandOnClick?: boolean; + expandOnFocus?: boolean; + expandOnHover?: boolean; + focusManagement?: string | null; + hostSelector?: string; + } +} + +declare class Expander { + constructor(el: HTMLElement, selectedOptions?: Expander.Options); + + collapseOnClickOut: boolean; + + collapseOnFocusOut: boolean; + + collapseOnMouseOut: boolean; + + expandOnClick: boolean; + + expandOnFocus: boolean; + + expandOnHover: boolean; + + collapse(): void; + + expand(isKeyboard: boolean): void; + + isExpanded(): boolean; + + toggle(): void; +} + +export = Expander; diff --git a/types/makeup-expander/makeup-expander-tests.ts b/types/makeup-expander/makeup-expander-tests.ts new file mode 100644 index 0000000000..f35d7cd3bd --- /dev/null +++ b/types/makeup-expander/makeup-expander-tests.ts @@ -0,0 +1,21 @@ +import Expander = require('makeup-expander'); + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +const options: Expander.Options = { + expandOnClick: true +}; + +if (widgetEl) { + // $ExpectType Expander + new Expander(widgetEl); + + // $ExpectType Expander + const widget = new Expander(widgetEl, options); + + // $ExpectType void + widget.expand(true); + + // $ExpectType boolean + const expanded = widget.isExpanded(); +} diff --git a/types/makeup-expander/tsconfig.json b/types/makeup-expander/tsconfig.json new file mode 100644 index 0000000000..f247e79d82 --- /dev/null +++ b/types/makeup-expander/tsconfig.json @@ -0,0 +1,22 @@ +{ + "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", + "makeup-expander-tests.ts" + ] +} diff --git a/types/makeup-expander/tslint.json b/types/makeup-expander/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-expander/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-floating-label/index.d.ts b/types/makeup-floating-label/index.d.ts new file mode 100644 index 0000000000..7b35349554 --- /dev/null +++ b/types/makeup-floating-label/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for makeup-floating-label 0.0 +// Project: https://github.com/makeup-js/makeup-floating-label#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +declare class FloatingLabel { + constructor(el: any, userOptions?: any); + refresh(): void; +} + +export = FloatingLabel; diff --git a/types/makeup-floating-label/makeup-floating-label-tests.ts b/types/makeup-floating-label/makeup-floating-label-tests.ts new file mode 100644 index 0000000000..3883e4135f --- /dev/null +++ b/types/makeup-floating-label/makeup-floating-label-tests.ts @@ -0,0 +1,9 @@ +import FloatingLabel = require('makeup-floating-label'); + +const widgetEls = document.querySelectorAll('.floating-label'); + +widgetEls.forEach((el: Element) => { + const widget = new FloatingLabel(el); + + widget.refresh(); +}); diff --git a/types/makeup-floating-label/tsconfig.json b/types/makeup-floating-label/tsconfig.json new file mode 100644 index 0000000000..c7fed3a8c4 --- /dev/null +++ b/types/makeup-floating-label/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom", + "dom.iterable" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "makeup-floating-label-tests.ts" + ] +} diff --git a/types/makeup-floating-label/tslint.json b/types/makeup-floating-label/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-floating-label/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-keyboard-trap/index.d.ts b/types/makeup-keyboard-trap/index.d.ts new file mode 100644 index 0000000000..4645d57e2c --- /dev/null +++ b/types/makeup-keyboard-trap/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for makeup-keyboard-trap 0.1 +// Project: https://github.com/makeup-js/makeup-keyboard-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function refresh(): any; + +export function trap(el: any): any; + +export function untrap(): any; diff --git a/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts b/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts new file mode 100644 index 0000000000..0f7687d750 --- /dev/null +++ b/types/makeup-keyboard-trap/makeup-keyboard-trap-tests.ts @@ -0,0 +1,7 @@ +import { trap, untrap } from 'makeup-keyboard-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +trap(widgetEl); + +untrap(); diff --git a/types/makeup-keyboard-trap/tsconfig.json b/types/makeup-keyboard-trap/tsconfig.json new file mode 100644 index 0000000000..0e4c00274f --- /dev/null +++ b/types/makeup-keyboard-trap/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", + "makeup-keyboard-trap-tests.ts" + ] +} diff --git a/types/makeup-keyboard-trap/tslint.json b/types/makeup-keyboard-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-keyboard-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-prevent-scroll-keys/index.d.ts b/types/makeup-prevent-scroll-keys/index.d.ts new file mode 100644 index 0000000000..bb59ece615 --- /dev/null +++ b/types/makeup-prevent-scroll-keys/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-prevent-scroll-keys 0.0 +// Project: https://github.com/makeup-js/makeup-prevent-scroll-keys#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function add(el: any): void; + +export function remove(el: any): void; diff --git a/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts b/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts new file mode 100644 index 0000000000..c889c6299a --- /dev/null +++ b/types/makeup-prevent-scroll-keys/makeup-prevent-scroll-keys-tests.ts @@ -0,0 +1,9 @@ +import * as scrollKeyPreventer from 'makeup-prevent-scroll-keys'; + +const widgetEl: HTMLElement | null = document.querySelector('.widget'); + +if (widgetEl) { + scrollKeyPreventer.add(widgetEl); + + scrollKeyPreventer.remove(widgetEl); +} diff --git a/types/makeup-prevent-scroll-keys/tsconfig.json b/types/makeup-prevent-scroll-keys/tsconfig.json new file mode 100644 index 0000000000..d48ada0be6 --- /dev/null +++ b/types/makeup-prevent-scroll-keys/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", + "makeup-prevent-scroll-keys-tests.ts" + ] +} diff --git a/types/makeup-prevent-scroll-keys/tslint.json b/types/makeup-prevent-scroll-keys/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-prevent-scroll-keys/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/makeup-screenreader-trap/index.d.ts b/types/makeup-screenreader-trap/index.d.ts new file mode 100644 index 0000000000..0995b62a3c --- /dev/null +++ b/types/makeup-screenreader-trap/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for makeup-screenreader-trap 0.0 +// Project: https://github.com/makeup-js/makeup-screenreader-trap#readme +// Definitions by: Timur Manyanov +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.6 + +export function trap(el: HTMLElement): void; + +export function untrap(): void; diff --git a/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts new file mode 100644 index 0000000000..48b198ab2d --- /dev/null +++ b/types/makeup-screenreader-trap/makeup-screenreader-trap-tests.ts @@ -0,0 +1,9 @@ +import { trap, untrap } from 'makeup-screenreader-trap'; + +const widgetEl: HTMLElement | null = document.querySelector('.expander'); + +if (widgetEl) { + trap(widgetEl); +} + +untrap(); diff --git a/types/makeup-screenreader-trap/tsconfig.json b/types/makeup-screenreader-trap/tsconfig.json new file mode 100644 index 0000000000..08df420e11 --- /dev/null +++ b/types/makeup-screenreader-trap/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", + "makeup-screenreader-trap-tests.ts" + ] +} diff --git a/types/makeup-screenreader-trap/tslint.json b/types/makeup-screenreader-trap/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/makeup-screenreader-trap/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mali-compose/index.d.ts b/types/mali-compose/index.d.ts index 87b23087d3..c70ee7557b 100644 --- a/types/mali-compose/index.d.ts +++ b/types/mali-compose/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/malijs/mali-compose // Definitions by: Daniel Byrne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import { Context } from "mali"; diff --git a/types/mali-compose/package.json b/types/mali-compose/package.json new file mode 100644 index 0000000000..76d151fcec --- /dev/null +++ b/types/mali-compose/package.json @@ -0,0 +1,8 @@ +{ + "private": true, + "dependencies": { + "grpc": "^1.16.1", + "mali": "^0.10.2", + "protobufjs": "^6.8.8" + } +} diff --git a/types/mali-onerror/index.d.ts b/types/mali-onerror/index.d.ts index c9600d50f0..6fa37b9862 100644 --- a/types/mali-onerror/index.d.ts +++ b/types/mali-onerror/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/malijs/onerror // Definitions by: Daniel Byrne // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 import { Context } from "mali"; diff --git a/types/mali-onerror/package.json b/types/mali-onerror/package.json new file mode 100644 index 0000000000..76d151fcec --- /dev/null +++ b/types/mali-onerror/package.json @@ -0,0 +1,8 @@ +{ + "private": true, + "dependencies": { + "grpc": "^1.16.1", + "mali": "^0.10.2", + "protobufjs": "^6.8.8" + } +} diff --git a/types/mali/index.d.ts b/types/mali/index.d.ts deleted file mode 100644 index 8e536d5330..0000000000 --- a/types/mali/index.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Type definitions for mali 0.9 -// Project: https://github.com/malijs/mali -// Definitions by: Daniel Byrne -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -/// - -import { EventEmitter } from 'events'; -import { Stream } from 'stream'; - -declare class Mali extends EventEmitter { - constructor(path: any, name?: string | ReadonlyArray, options?: any); - name: string; - env: string; - ports: ReadonlyArray; - silent: boolean; - - addService(path: any, name: string | ReadonlyArray, options?: any): void; - use(service?: any, name?: any, fns?: any): void; - start(port: number | string, creds?: any, options?: any): any; // gnarly type inferring for these functions so Im just gonna let them handle it. - toJSON(): any; - close(): Promise; - inspect(): any; -} - -declare namespace Mali { - interface Context { - name: string; - fullName: string; - service: string; - package: string; - app: any; // ? app - call: any; - request: Request; - response: Response; - req: any; // ? - res: any; // ? - type: string; - metadata: string; - get(field: string): any; - set(field: any, val?: any): void; // do I need `?:` if its of type `any`? - sendMetadata(md: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ - } - - class Request { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - req: any; // ? - - getMetadata(): any; - get(field: string): any; - } - - class Response { - constructor(call: any, type: string); - call: any; - type: string; - metadata: any; - status: any; - res: any; // ? - set(field: any, val?: any): void; // is `val?:` necessary when its of type `any`? - get(field: string): any; - getMetadata(): any; - sendMetadata(md?: any): void; - getStatus(field: string): any; - setStatus(field: any, val?: any): void; // ^ same as above - } - - function exec(ctx: Context, handler: any, cb?: any): void; -} - -export = Mali; diff --git a/types/mali/mali-tests.ts b/types/mali/mali-tests.ts deleted file mode 100644 index d6d33a263f..0000000000 --- a/types/mali/mali-tests.ts +++ /dev/null @@ -1,16 +0,0 @@ -// example from https://github.com/malijs/mali#example - -import Mali = require('mali'); -import path = require('path'); - -const PROTO_PATH = path.resolve(__dirname, '../protos/helloworld.proto'); - -async function sayHello(ctx: Mali.Context) { - ctx.res = { message: 'Hello '.concat(ctx.req.name) }; -} - -const app = new Mali(PROTO_PATH); -// $ExpectType void -app.use({sayHello}); -// $ExpectType any -app.start('127.0.0.1:50051'); diff --git a/types/mapbox-gl/index.d.ts b/types/mapbox-gl/index.d.ts index 1aad087460..f3389876b9 100644 --- a/types/mapbox-gl/index.d.ts +++ b/types/mapbox-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mapbox GL JS v0.49.0 +// Type definitions for Mapbox GL JS v0.51.0 // Project: https://github.com/mapbox/mapbox-gl-js // Definitions by: Dominik Bruderer , Patrick Reames // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -17,7 +17,7 @@ declare namespace mapboxgl { export function setRTLTextPlugin(pluginURL: string, callback: (error: Error) => void): void; - type LngLatLike = LngLat | { lng: number; lat: number; } | [number, number]; + type LngLatLike = LngLat | { lng: number; lat: number; } | { lon: number; lat: number; } | [number, number]; type LngLatBoundsLike = LngLatBounds | [LngLatLike, LngLatLike] | [number, number, number, number]; type PointLike = Point | [number, number]; type Expression = any[]; @@ -692,6 +692,8 @@ declare namespace mapboxgl { clusterMaxZoom?: number; lineMetrics?: boolean; + + generateId?: boolean; } /** @@ -1069,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; diff --git a/types/mapbox-gl/mapbox-gl-tests.ts b/types/mapbox-gl/mapbox-gl-tests.ts index d55cf592e5..d119c76bd5 100644 --- a/types/mapbox-gl/mapbox-gl-tests.ts +++ b/types/mapbox-gl/mapbox-gl-tests.ts @@ -417,6 +417,7 @@ function expectType(value: T) { /* let the compiler handle things */ } expectType(new mapboxgl.LngLat(0, 0)); expectType([0, 0]); expectType({ lng: 0, lat: 0 }); +expectType({ lon: 0, lat: 0 }); /* * LngLat @@ -464,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/mapbox/index.d.ts b/types/mapbox/index.d.ts index 334d644e21..97da469e4a 100644 --- a/types/mapbox/index.d.ts +++ b/types/mapbox/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Mapbox 1.6 // Project: https://www.mapbox.com/mapbox.js/ // Definitions by: Maxime Fabre +// Florian Luccioni // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -153,6 +154,20 @@ declare global { getGeoJSON(): any; } + // StyleLayer + ////////////////////////////////////////////////////////////////////// + + /** + * L.mapbox.styleLayer provides a way to integrate styles created with Mapbox Studio into your map. + */ + function styleLayer(url: string, options?: StyleLayerOptions): StyleLayer; + + interface StyleLayerOptions extends Leaflet.TileLayerOptions { + sanitizer?(template: string): string; + } + + type StyleLayer = Leaflet.TileLayer; + ////////////////////////////////////////////////////////////////////// ////////////////////////////// GEOCODING ///////////////////////////// ////////////////////////////////////////////////////////////////////// diff --git a/types/mapbox/mapbox-tests.ts b/types/mapbox/mapbox-tests.ts index ab9ad6c5de..a9610ba5c4 100644 --- a/types/mapbox/mapbox-tests.ts +++ b/types/mapbox/mapbox-tests.ts @@ -4,6 +4,8 @@ const mapboxTiles = L.tileLayer('https://{s}.tiles.mapbox.com/v3/examples.map-i8 const map = L.map('map').addLayer(mapboxTiles).setView(new L.LatLng([42.3610, -71.0587]), 15); +const lightTiles = L.mapbox.styleLayer('mapbox://styles/mapbox/light-v9').addTo(map); + const coordinates = document.getElementById('coordinates'); const marker = L.marker(new L.LatLng([0, 0]), { diff --git a/types/markdown-it-anchor/index.d.ts b/types/markdown-it-anchor/index.d.ts index 045082abf1..39cb91be45 100644 --- a/types/markdown-it-anchor/index.d.ts +++ b/types/markdown-it-anchor/index.d.ts @@ -2,9 +2,11 @@ // Project: https://github.com/valeriangalliat/markdown-it-anchor // Definitions by: Josh Toft // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 -import { MarkdownIt, Core, Token } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Core = require('markdown-it/lib/parser_core'); +import Token = require('markdown-it/lib/token'); declare namespace anchor { interface AnchorInfo { diff --git a/types/markdown-it-anchor/markdown-it-anchor-tests.ts b/types/markdown-it-anchor/markdown-it-anchor-tests.ts index 3570ba764b..a9a865a469 100644 --- a/types/markdown-it-anchor/markdown-it-anchor-tests.ts +++ b/types/markdown-it-anchor/markdown-it-anchor-tests.ts @@ -1,4 +1,4 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); import anchor = require("markdown-it-anchor"); const md = new MarkdownIt(); diff --git a/types/markdown-it-container/index.d.ts b/types/markdown-it-container/index.d.ts index f2d3722a3d..2920f38f91 100644 --- a/types/markdown-it-container/index.d.ts +++ b/types/markdown-it-container/index.d.ts @@ -2,9 +2,11 @@ // Project: https://github.com/markdown-it/markdown-it-container // Definitions by: Vyacheslav Demot // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 -import { MarkdownIt, Token, Renderer } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); +import Renderer = require('markdown-it/lib/renderer'); +import Token = require('markdown-it/lib/token'); declare namespace markdownItContainer { interface ContainerOpts { diff --git a/types/markdown-it-container/markdown-it-container-tests.ts b/types/markdown-it-container/markdown-it-container-tests.ts index 3c8f3bf980..e6754f82f3 100644 --- a/types/markdown-it-container/markdown-it-container-tests.ts +++ b/types/markdown-it-container/markdown-it-container-tests.ts @@ -1,11 +1,13 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Token = require("markdown-it/lib/token"); + import MarkdownItContainer = require("markdown-it-container"); const md = new MarkdownIt(); md.use(MarkdownItContainer, 'spoiler', { validate: (params: any) => params.trim().match(/^spoiler\s+(.*)$/), - render: (tokens: MarkdownIt.Token[], index: number) => { + render: (tokens: Token[], index: number) => { const match = tokens[index].info.trim().match(/^spoiler\s+(.*)$/); const onClick = "this.parentNode.classList.toggle('_expanded');" + diff --git a/types/markdown-it-lazy-headers/index.d.ts b/types/markdown-it-lazy-headers/index.d.ts index 9eb8a54cf1..43ac828764 100644 --- a/types/markdown-it-lazy-headers/index.d.ts +++ b/types/markdown-it-lazy-headers/index.d.ts @@ -2,9 +2,9 @@ // Project: https://github.com/Galadirith/markdown-it-lazy-headers // Definitions by: Knom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.2 +// TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); declare function lazyheaders(md: MarkdownIt): void; diff --git a/types/markdown-it/index.d.ts b/types/markdown-it/index.d.ts index 24513c3e56..e7d0ffa6e7 100644 --- a/types/markdown-it/index.d.ts +++ b/types/markdown-it/index.d.ts @@ -2,128 +2,7 @@ // Project: https://github.com/markdown-it/markdown-it // Definitions by: York Yao , Robert Coie // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 -interface MarkdownItStatic { - new (): MarkdownIt.MarkdownIt; - new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - new (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (): MarkdownIt.MarkdownIt; - (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt.MarkdownIt; - (options: MarkdownIt.Options): MarkdownIt.MarkdownIt; -} - -declare var MarkdownIt: MarkdownItStatic; +import MarkdownIt = require("./lib"); export = MarkdownIt; -export as namespace markdownit; - -declare module MarkdownIt { - interface MarkdownIt { - render(md: string, env?: any): string; - renderInline(md: string, env?: any): string; - parse(src: string, env: any): Token[]; - parseInline(src: string, env: any): Token[]; - use(plugin: any, ...params: any[]): MarkdownIt; - utils: { - assign(obj: any): any; - isString(obj: any): boolean; - has(object: any, key: string): boolean; - unescapeMd(str: string): string; - unescapeAll(str: string): string; - isValidEntityCode(str: any): boolean; - fromCodePoint(str: string): string; - escapeHtml(str: string): string; - arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] - isSpace(str: any): boolean; - isWhiteSpace(str: any): boolean - isMdAsciiPunct(str: any): boolean; - isPunctChar(str: any): boolean; - escapeRE(str: string): string; - normalizeReference(str: string): string; - } - disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; - set(options: Options): MarkdownIt; - normalizeLink(url: string): string; - normalizeLinkText(url: string): string; - validateLink(url: string): boolean; - block: ParserBlock; - core: Core; - helpers: any; - inline: ParserInline; - linkify: LinkifyIt; - renderer: Renderer; - } - interface Options { - html?: boolean; - xhtmlOut?: boolean; - breaks?: boolean; - langPrefix?: string; - linkify?: boolean; - typographer?: boolean; - quotes?: string; - highlight?: (str: string, lang: string) => void; - } - interface LinkifyIt { - tlds(lang: string, linkified: boolean): void; - } - interface Renderer { - rules: { [name: string]: TokenRender }; - render(tokens: Token[], options: any, env: any): string; - renderAttrs(token: Token): string; - renderInline(tokens: Token[], options: any, env: any): string; - renderToken(tokens: Token[], idx: number, options: any): string; - } - interface Token { - attrGet: (name: string) => string | null; - attrIndex: (name: string) => number; - attrJoin: (name: string, value: string) => void; - attrPush: (attrData: string[]) => void; - attrSet: (name: string, value: string) => void; - attrs: string[][]; - block: boolean; - children: Token[]; - content: string; - hidden: boolean; - info: string; - level: number; - map: number[]; - markup: string; - meta: any; - nesting: number; - tag: string; - type: string; - } - - type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; - - interface Rule { - (state: any, silent?: boolean): void; - } - - interface Ruler { - after(afterName: string, ruleName: string, rule: Rule, options?: any): void; - at(name: string, rule: Rule, options?: any): void; - before(beforeName: string, ruleName: string, rule: Rule, options?: any): void; - disable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enable(rules: string | string[], ignoreInvalid?: boolean): string[]; - enableOnly(rule: string, ignoreInvalid?: boolean): void; - getRules(chain: string): Rule[]; - push(ruleName: string, rule: Rule, options?: any): void; - } - - interface ParserBlock { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: Ruler; - } - - interface Core { - process(state: any): void; - ruler: Ruler; - } - - interface ParserInline { - parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; - ruler: Ruler; - ruler2: Ruler; - } -} diff --git a/types/markdown-it/lib/index.d.ts b/types/markdown-it/lib/index.d.ts new file mode 100644 index 0000000000..9a9caf37b6 --- /dev/null +++ b/types/markdown-it/lib/index.d.ts @@ -0,0 +1,113 @@ +import { LinkifyIt } from 'linkify-it' + +import State = require('./rules_core/state_core'); +import StateBlock = require('./rules_block/state_block'); +import StateInline = require('./rules_inline/state_inline'); + +import Core = require('./parser_core'); +import ParserBlock = require('./parser_block'); +import ParserInline = require('./parser_inline'); + +import Renderer = require('./renderer'); +import Ruler = require('./ruler'); +import Token = require('./token'); + +export = MarkdownIt; +export as namespace markdownit; + +declare const MarkdownIt: MarkdownItConstructor; + +interface MarkdownItConstructor { + new (): MarkdownIt; + new (presetName: "commonmark" | "zero" | "default", options?: MarkdownIt.Options): MarkdownIt; + new (options: MarkdownIt.Options): MarkdownIt; + (): MarkdownIt; + (presetName: "commonmark" | "zero" | "default", options ?: MarkdownIt.Options): MarkdownIt; + (options: MarkdownIt.Options): MarkdownIt; +} + +interface MarkdownIt { + render(md: string, env?: any): string; + renderInline(md: string, env?: any): string; + parse(src: string, env: any): Token[]; + parseInline(src: string, env: any): Token[]; + + /* + // The following only works in 3.0 + // Since it's still not allowed to target 3.0, i'll leave the code commented out + + use = any[]>( + plugin: (md: MarkdownIt, ...params: T) => void, + ...params: T + ): MarkdownIt; + */ + + use(plugin: (md: MarkdownIt, ...params: any[]) => void, ...params: any[]): MarkdownIt; + + utils: { + assign(obj: any): any; + isString(obj: any): boolean; + has(object: any, key: string): boolean; + unescapeMd(str: string): string; + unescapeAll(str: string): string; + isValidEntityCode(str: any): boolean; + fromCodePoint(str: string): string; + escapeHtml(str: string): string; + arrayReplaceAt(src: any[], pos: number, newElements: any[]): any[] + isSpace(str: any): boolean; + isWhiteSpace(str: any): boolean + isMdAsciiPunct(str: any): boolean; + isPunctChar(str: any): boolean; + escapeRE(str: string): string; + normalizeReference(str: string): string; + } + + disable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + enable(rules: string[] | string, ignoreInvalid?: boolean): MarkdownIt; + set(options: MarkdownIt.Options): MarkdownIt; + normalizeLink(url: string): string; + normalizeLinkText(url: string): string; + validateLink(url: string): boolean; + block: ParserBlock; + core: Core; + helpers: any; + inline: ParserInline; + linkify: LinkifyIt; + renderer: Renderer; +} + +declare module MarkdownIt { + interface Options { + html?: boolean; + xhtmlOut?: boolean; + breaks?: boolean; + langPrefix?: string; + linkify?: boolean; + typographer?: boolean; + quotes?: string; + highlight?: (str: string, lang: string) => void; + } + + interface Rule { + (state: S, silent?: boolean): boolean | void; + } + + interface RuleInline extends Rule {} + interface RuleBlock extends Rule {} + + interface RulerInline extends Ruler {} + interface RulerBlock extends Ruler {} + + type TokenRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => void; + + interface Delimiter { + close: boolean; + end: number; + jump: number; + length: number; + level: number; + marker: number; + open: boolean; + token: number; + } +} diff --git a/types/markdown-it/lib/parser_block.d.ts b/types/markdown-it/lib/parser_block.d.ts new file mode 100644 index 0000000000..2efc76b858 --- /dev/null +++ b/types/markdown-it/lib/parser_block.d.ts @@ -0,0 +1,9 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = ParserBlock; + +declare class ParserBlock { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + ruler: MarkdownIt.RulerBlock; +} diff --git a/types/markdown-it/lib/parser_core.d.ts b/types/markdown-it/lib/parser_core.d.ts new file mode 100644 index 0000000000..a6559bdfef --- /dev/null +++ b/types/markdown-it/lib/parser_core.d.ts @@ -0,0 +1,10 @@ +import MarkdownIt = require("."); +import Ruler = require("./ruler"); +import Token = require("./token"); + +export = ParserCore; + +declare class ParserCore { + process(state: any): void; + ruler: Ruler; +} diff --git a/types/markdown-it/lib/parser_inline.d.ts b/types/markdown-it/lib/parser_inline.d.ts new file mode 100644 index 0000000000..ad7aa26d93 --- /dev/null +++ b/types/markdown-it/lib/parser_inline.d.ts @@ -0,0 +1,13 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); +import Token = require("./token"); + +export = ParserInline; + +declare class ParserInline { + parse(src: string, md: MarkdownIt, env: any, outTokens: Token[]): void; + tokenize(state: State): void; + skipToken(state: State): void; + ruler: MarkdownIt.RulerInline; + ruler2: MarkdownIt.RulerInline; +} diff --git a/types/markdown-it/lib/renderer.d.ts b/types/markdown-it/lib/renderer.d.ts new file mode 100644 index 0000000000..0231dad0f9 --- /dev/null +++ b/types/markdown-it/lib/renderer.d.ts @@ -0,0 +1,12 @@ +import MarkdownIt = require("."); +import Token = require("./token"); + +export = Renderer; + +declare class Renderer { + rules: { [name: string]: MarkdownIt.TokenRender }; + render(tokens: Token[], options: any, env: any): string; + renderAttrs(token: Token): string; + renderInline(tokens: Token[], options: any, env: any): string; + renderToken(tokens: Token[], idx: number, options: any): string; +} diff --git a/types/markdown-it/lib/ruler.d.ts b/types/markdown-it/lib/ruler.d.ts new file mode 100644 index 0000000000..62ab55e3de --- /dev/null +++ b/types/markdown-it/lib/ruler.d.ts @@ -0,0 +1,15 @@ +import MarkdownIt = require("."); +import State = require("./rules_core/state_core"); + +export = Ruler; + +declare class Ruler { + after(afterName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + at(name: string, rule: MarkdownIt.Rule, options?: any): void; + before(beforeName: string, ruleName: string, rule: MarkdownIt.Rule, options?: any): void; + disable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enable(rules: string | string[], ignoreInvalid?: boolean): string[]; + enableOnly(rule: string, ignoreInvalid?: boolean): void; + getRules(chain: string): MarkdownIt.Rule[]; + push(ruleName: string, rule: MarkdownIt.Rule, options?: any): void; +} diff --git a/types/markdown-it/lib/rules_block/state_block.d.ts b/types/markdown-it/lib/rules_block/state_block.d.ts new file mode 100644 index 0000000000..6eebab4202 --- /dev/null +++ b/types/markdown-it/lib/rules_block/state_block.d.ts @@ -0,0 +1,23 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateBlock; + +declare class StateBlock extends State { + /** Used in lists to determine if they interrupt a paragraph */ + parentType: 'blockquote' | 'list' | 'root' | 'paragraph' | 'reference'; + + eMarks: number[]; + bMarks: number[]; + bsCount: number[]; + sCount: number[]; + tShift: number[]; + + blkIndent: number; + ddIndent: number; + + line: number; + lineMax: number; + tight: boolean; +} diff --git a/types/markdown-it/lib/rules_core/state_core.d.ts b/types/markdown-it/lib/rules_core/state_core.d.ts new file mode 100644 index 0000000000..7cf73134aa --- /dev/null +++ b/types/markdown-it/lib/rules_core/state_core.d.ts @@ -0,0 +1,20 @@ +import MarkdownIt = require(".."); +import Token = require("../token"); + +export = StateCore; + +declare class StateCore { + env: any; + level: number; + + /** Link to parser instance */ + md: MarkdownIt; + + /** The markdown source code that is being parsed. */ + src: string; + + tokens: Token[]; + + /** Return any for a yet untyped property */ + [undocumented: string]: any; +} diff --git a/types/markdown-it/lib/rules_inline/state_inline.d.ts b/types/markdown-it/lib/rules_inline/state_inline.d.ts new file mode 100644 index 0000000000..27938d99da --- /dev/null +++ b/types/markdown-it/lib/rules_inline/state_inline.d.ts @@ -0,0 +1,46 @@ +import MarkdownIt = require(".."); +import State = require("../rules_core/state_core"); +import Token = require("../token"); + +export = StateInline; + +declare class StateInline extends State { + /** + * Stores `{ start: end }` pairs. Useful for backtrack + * optimization of pairs parse (emphasis, strikes). + */ + cache: { [start: number]: number }; + + /** Emphasis-like delimiters */ + delimiters: MarkdownIt.Delimiter[]; + + pending: string; + pendingLevel: number; + + /** Index of the first character of this token. */ + pos: number; + + /** Index of the last character that can be used (for example the one before the end of this line). */ + posMax: number; + + /** + * Push new token to "stream". + * If pending text exists, flush it as text token. + */ + push(type: string, tag: string, nesting: number): Token; + + /** Flush pending text */ + pushPending(): Token; + + /** + * Scan a sequence of emphasis-like markers and determine whether + * it can start an emphasis sequence or end an emphasis sequence. + * @param start - position to scan from (it should point to a valid marker) + * @param canSplitWord - determine if these markers can be found inside a word + */ + scanDelims(start: number, canSplitWord: boolean): { + can_open: boolean, + can_close: boolean, + length: number + }; +} diff --git a/types/markdown-it/lib/token.d.ts b/types/markdown-it/lib/token.d.ts new file mode 100644 index 0000000000..1f71d54bfd --- /dev/null +++ b/types/markdown-it/lib/token.d.ts @@ -0,0 +1,23 @@ +export = Token; + +declare class Token { + constructor(type: string, tag: string, nesting: number); + attrGet: (name: string) => string | null; + attrIndex: (name: string) => number; + attrJoin: (name: string, value: string) => void; + attrPush: (attrData: string[]) => void; + attrSet: (name: string, value: string) => void; + attrs: string[][]; + block: boolean; + children: Token[]; + content: string; + hidden: boolean; + info: string; + level: number; + map: number[]; + markup: string; + meta: any; + nesting: number; + tag: string; + type: string; +} diff --git a/types/markdown-it/markdown-it-tests.ts b/types/markdown-it/markdown-it-tests.ts index f22fc5cb2d..343661ad87 100644 --- a/types/markdown-it/markdown-it-tests.ts +++ b/types/markdown-it/markdown-it-tests.ts @@ -1,4 +1,6 @@ -import * as MarkdownIt from "markdown-it"; +import MarkdownIt = require("markdown-it"); +import Renderer = require("markdown-it/lib/renderer"); +import Token = require("markdown-it/lib/token"); { const md = new MarkdownIt(); @@ -141,7 +143,7 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { return ""; }, }); - md.renderer.rules["image"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["image"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { const token = tokens[index]; const aIndex = token.attrIndex("src"); token.attrs[aIndex][1]; @@ -154,11 +156,11 @@ function myToken(tokens: any, idx: number, options: any, env: any, self: any) { if (md.renderer.rules["link_open"]) { defaultLinkRender = md.renderer.rules["link_open"]; } else { - defaultLinkRender = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + defaultLinkRender = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { return self.renderToken(tokens, index, options); }; } - md.renderer.rules["link_open"] = (tokens: MarkdownIt.Token[], index: number, options: any, env: any, self: MarkdownIt.Renderer) => { + md.renderer.rules["link_open"] = (tokens: Token[], index: number, options: any, env: any, self: Renderer) => { tokens[index].attrPush(["target", "_blank"]); tokens[index].attrPush(["rel", "nofollow"]); return defaultLinkRender(tokens, index, options, env, self); 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/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/carousel.d.ts b/types/materialize-css/carousel.d.ts index fd660694d1..6c762ec830 100644 --- a/types/materialize-css/carousel.d.ts +++ b/types/materialize-css/carousel.d.ts @@ -110,8 +110,6 @@ declare namespace M { interface JQuery { carousel(method: keyof Pick): JQuery; - carousel(method: keyof Pick, n?: number): JQuery; - carousel(method: keyof Pick, n?: number): JQuery; - carousel(method: keyof Pick, n?: number): JQuery; + carousel(method: keyof Pick | keyof Pick | keyof Pick, n?: number): JQuery; carousel(options?: Partial): JQuery; } diff --git a/types/materialize-css/character-counter.d.ts b/types/materialize-css/character-counter.d.ts index 4d34ac170e..7634075a9b 100644 --- a/types/materialize-css/character-counter.d.ts +++ b/types/materialize-css/character-counter.d.ts @@ -20,6 +20,5 @@ declare namespace M { } interface JQuery { - characterCounter(method: keyof Pick): JQuery; - characterCounter(): JQuery; + characterCounter(method?: keyof Pick): JQuery; } diff --git a/types/materialize-css/collapsible.d.ts b/types/materialize-css/collapsible.d.ts index 649a59e9bb..d69e958730 100644 --- a/types/materialize-css/collapsible.d.ts +++ b/types/materialize-css/collapsible.d.ts @@ -77,7 +77,6 @@ declare namespace M { interface JQuery { collapsible(method: keyof Pick): JQuery; - collapsible(method: keyof Pick, n: number): JQuery; - collapsible(method: keyof Pick, n: number): JQuery; + collapsible(method: keyof Pick | keyof Pick, n: number): JQuery; collapsible(options?: Partial): JQuery; } diff --git a/types/materialize-css/range.d.ts b/types/materialize-css/range.d.ts index dac7a7edf2..a1de53baa9 100644 --- a/types/materialize-css/range.d.ts +++ b/types/materialize-css/range.d.ts @@ -20,6 +20,5 @@ declare namespace M { } interface JQuery { - range(): JQuery; - range(method: keyof Pick): JQuery; + range(method?: keyof Pick): JQuery; } diff --git a/types/mathjax/index.d.ts b/types/mathjax/index.d.ts index aaf4a6109c..9e3c94f418 100644 --- a/types/mathjax/index.d.ts +++ b/types/mathjax/index.d.ts @@ -193,6 +193,10 @@ declare namespace MathJax { * below. The options and their default values are given in the Core Options reference page. */ config?: Config; + /*The pause (in milliseconds) between input and output phases of MathJax’s processing. Set this to 0 to avoid + * jitter when updating output frequently (e.g., in a live preview environment). + */ + processSectionDelay?: number; /*The minimum time (in milliseconds) between updates of the “Processing Math” message. After this amount of time * has passed, and after the next equation has finished being processed, MathJax will stop processing momentarily * so that the update message can be displayed, and so that the browser can handle user interaction. diff --git a/types/mathjax/mathjax-tests.ts b/types/mathjax/mathjax-tests.ts index 755e3bc4bd..d044fafaec 100644 --- a/types/mathjax/mathjax-tests.ts +++ b/types/mathjax/mathjax-tests.ts @@ -65,3 +65,5 @@ MathJax.Hub.Config({ useGlobalCache: true } }) + +MathJax.Hub.processSectionDelay = 5; diff --git a/types/mathjs/index.d.ts b/types/mathjs/index.d.ts index 71f89b3e1a..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 @@ -1345,7 +1346,7 @@ declare namespace math { * the Matrix/array being traversed. * @returns Transformed map of x */ - map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => Matrix | MathArray)): Matrix | MathArray; + map(x: Matrix | MathArray, callback: ((value: any, index: any, matrix: Matrix | MathArray) => MathType | string)): Matrix | MathArray; /** * Create a matrix filled with ones. The created matrix can have one or @@ -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 { @@ -2876,6 +2894,7 @@ declare namespace math { interface Parser { eval(expr: string): any; get(variable: string): any; + getAll(): { [key: string]: any; }; set: (variable: string, value: any) => void; clear: () => void; } @@ -4541,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 7c3dfaec35..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 */ @@ -179,6 +182,7 @@ Expressions examples const x = parser.get('x'); const f = parser.get('f'); + const y = parser.getAll(); const g = f(3, 3); parser.set('h', 500); @@ -270,6 +274,13 @@ Matrices examples math.range('2:-1:-3'); math.factorial(math.range('1:6')); } + + // map matrix + { + math.map([1, 2, 3], function(value) { + return value * value; + }); // returns [1, 4, 9] + } } /* @@ -384,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/matter-js/index.d.ts b/types/matter-js/index.d.ts index 4275785191..04ed8bd898 100644 --- a/types/matter-js/index.d.ts +++ b/types/matter-js/index.d.ts @@ -882,6 +882,14 @@ declare namespace Matter { * @default false */ isStatic: boolean; + /** + * A flag that indicates whether a body is a sensor. Sensor triggers collision events, but doesn't react with colliding body physically. + * + * @property isSensor + * @type boolean + * @default false + */ + isSensor: boolean; /** * An arbitrary `String` name to help the user identify and manage bodies. * diff --git a/types/maxmind/index.d.ts b/types/maxmind/index.d.ts deleted file mode 100644 index dd0a8ee63d..0000000000 --- a/types/maxmind/index.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -// Type definitions for maxmind v2.0 -// Project: https://github.com/runk/node-maxmind -// Definitions by: Joshua DeVinney -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export declare function open(database: string, cb: (err: Error, reader: Reader) => void): void; -export declare function open(database: string, opts: Options, cb: (err: Error, reader: Reader) => void): void; -export declare function openSync(database: string, opts?: Options): Reader; -export declare function validate(ip: string): boolean; - -export declare interface Reader { - get(ip: string): Response | null; - readonly metadata: Metadata; -} - -export declare interface Options { - cache?: { - max?: number; - maxAge?: number; - }; - watchForUpdates?: boolean; - watchForUpdatesNonPersistent?: boolean; - watchForUpdatesHook?: () => void; -} - -export declare interface Metadata { - readonly binaryFormatMajorVersion: number; - readonly binaryFormatMinorVersion: number; - readonly buildEpoch: Date; - readonly databaseType: string; - readonly languages: string[]; - readonly description: Translations; - readonly ipVersion: number; - readonly nodeCount: number; - readonly recordSize: number; - readonly nodeByteSize: number; - readonly searchTreeSize: number; - readonly treeDepth: number; -} - -export declare interface Response { - readonly continent?: { - readonly geoname_id: number; - readonly names: Translations; - readonly code: string; - }; - readonly country?: { - readonly geoname_id: number; - readonly names: Translations; - readonly iso_code: string; - }; - readonly registered_country?: { - readonly geoname_id: number; - readonly names: Translations; - readonly iso_code: string; - }; - readonly location?: { - readonly accuracy_radius: number; - readonly latitude: number; - readonly longitude: number; - readonly metro_code?: number; - readonly time_zone?: string; - }; - readonly subdivisions?: { - readonly geoname_id: number; - readonly names: Translations; - readonly iso_code: string; - }[]; - readonly city?: { - readonly geoname_id: number; - readonly names: Translations; - }; - readonly postal?: { code: string }; - readonly isp?: { - readonly isp: string; - readonly autonomous_system_number: number; - }; - readonly connection?: { connection_type: string }; -} - -export declare interface Translations { - readonly [index: string]: string; -} diff --git a/types/maxmind/maxmind-tests.ts b/types/maxmind/maxmind-tests.ts deleted file mode 100644 index 943cd9a5d1..0000000000 --- a/types/maxmind/maxmind-tests.ts +++ /dev/null @@ -1,30 +0,0 @@ -import * as maxmind from 'maxmind'; - -// Examples from https://github.com/runk/node-maxmind/blob/master/README.md - -// Example 1 -var cityLookup = maxmind.openSync('/path/to/GeoLite2-City.mmdb'); -var city = cityLookup.get('66.6.44.4'); - -var orgLookup = maxmind.openSync('/path/to/GeoOrg.mmdb'); -var organization = orgLookup.get('66.6.44.4'); - -// Example 2 -var lookup = maxmind.openSync('/path/to/GeoLite2.mmdb'); -var location = lookup.get('2001:4860:0:1001::3004:ef68'); - -// Example 3 -var lookup = maxmind.openSync('/path/to/GeoLite2.mmdb', { - cache: { - max: 1000, // max items in cache - maxAge: 1000 * 60 * 60 // life time in milliseconds - } -}) -lookup.get('1.1.1.1'); - -// Example 4 -maxmind.validate('66.6.44.4'); // returns true -maxmind.validate('66.6.44.boom!'); // returns false - -maxmind.validate('2001:4860:0:1001::3004:ef68'); // returns true -maxmind.validate('2001:4860:0:1001::3004:boom!'); // returns false 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/md5-file/index.d.ts b/types/md5-file/index.d.ts new file mode 100644 index 0000000000..1af46bb4a8 --- /dev/null +++ b/types/md5-file/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for md5-file 4.0 +// Project: https://github.com/roryrjb/md5-file#readme +// Definitions by: BamButz +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare var module: { + (filename: string, cb: (err: Error, hash: string) => void): void; + sync: (filename: string) => string; +}; + +export = module; diff --git a/types/md5-file/md5-file-tests.ts b/types/md5-file/md5-file-tests.ts new file mode 100644 index 0000000000..1c4bea62eb --- /dev/null +++ b/types/md5-file/md5-file-tests.ts @@ -0,0 +1,9 @@ +import * as md5 from "md5-file"; + +// $ExpectType void +md5("test.txt", (err, hash) => { + return; +}); + +// $ExpectType string +md5.sync("text.txt"); diff --git a/types/md5-file/tsconfig.json b/types/md5-file/tsconfig.json new file mode 100644 index 0000000000..71029d70f4 --- /dev/null +++ b/types/md5-file/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", + "md5-file-tests.ts" + ] +} diff --git a/types/md5-file/tslint.json b/types/md5-file/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/md5-file/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mdast/index.d.ts b/types/mdast/index.d.ts new file mode 100644 index 0000000000..c1fcadec97 --- /dev/null +++ b/types/mdast/index.d.ts @@ -0,0 +1,217 @@ +// Type definitions for Mdast 3.0 +// Project: https://github.com/syntax-tree/mdast +// Definitions by: Jun Lu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import { Parent as UnistParent, Literal as UnistLiteral, Node } from 'unist'; + +export type AlignType = 'left' | 'right' | 'center' | null; + +export type ReferenceType = 'shortcut' | 'collapsed' | 'full'; + +export type Content = + | TopLevelContent + | ListContent + | TableContent + | RowContent + | PhrasingContent; + +export type TopLevelContent = + | BlockContent + | FrontmatterContent + | DefinitionContent; + +export type BlockContent = + | Paragraph + | Heading + | ThematicBreak + | Blockquote + | List + | Table + | HTML + | Code; + +export type FrontmatterContent = YAML; + +export type DefinitionContent = Definition | FootnoteDefinition; + +export type ListContent = ListItem; + +export type TableContent = TableRow; + +export type RowContent = TableCell; + +export type PhrasingContent = StaticPhrasingContent | Link | LinkReference; + +export type StaticPhrasingContent = + | Text + | Emphasis + | Strong + | Delete + | HTML + | InlineCode + | Break + | Image + | ImageReference + | Footnote + | FootnoteReference; + +export interface Parent extends UnistParent { + children: Content[]; +} + +export interface Literal extends UnistLiteral { + value: string; +} + +export interface Root extends Parent { + type: 'root'; +} + +export interface Paragraph extends Parent { + type: 'paragraph'; + children: PhrasingContent[]; +} + +export interface Heading extends Parent { + type: 'heading'; + depth: 1 | 2 | 3 | 4 | 5 | 6; + children: PhrasingContent[]; +} + +export interface ThematicBreak extends Node { + type: 'thematicBreak'; +} + +export interface Blockquote extends Parent { + type: 'blockquote'; + children: BlockContent[]; +} + +export interface List extends Parent { + type: 'list'; + ordered?: boolean; + start?: number; + spread?: boolean; + children: ListContent[]; +} + +export interface ListItem extends Parent { + type: 'listItem'; + checked?: boolean; + spread?: boolean; + children: BlockContent[]; +} + +export interface Table extends Parent { + type: 'table'; + align?: AlignType[]; + children: TableContent[]; +} + +export interface TableRow extends Parent { + type: 'tableRow'; + children: RowContent[]; +} + +export interface TableCell extends Parent { + type: 'tableCell'; + children: PhrasingContent[]; +} + +export interface HTML extends Literal { + type: 'html'; +} + +export interface Code extends Literal { + type: 'code'; + lang?: string; + meta?: string; +} + +export interface YAML extends Literal { + type: 'yaml'; +} + +export interface Definition extends Node, Association, Resource { + type: 'definition'; +} + +export interface FootnoteDefinition extends Parent, Association { + type: 'footnoteDefinition'; + children: BlockContent[]; +} + +export interface Text extends Literal { + type: 'text'; +} + +export interface Emphasis extends Parent { + type: 'emphasis'; + children: PhrasingContent[]; +} + +export interface Strong extends Parent { + type: 'strong'; + children: PhrasingContent[]; +} + +export interface Delete extends Parent { + type: 'delete'; + children: PhrasingContent[]; +} + +export interface InlineCode extends Literal { + type: 'inlineCode'; +} + +export interface Break extends Node { + type: 'break'; +} + +export interface Link extends Parent, Resource { + type: 'link'; + children: StaticPhrasingContent[]; +} + +export interface Image extends Node, Resource, Alternative { + type: 'image'; +} + +export interface LinkReference extends Parent, Reference { + type: 'linkReference'; + children: StaticPhrasingContent[]; +} + +export interface ImageReference extends Node, Reference, Alternative { + type: 'imageReference'; +} + +export interface Footnote extends Parent { + type: 'footnote'; + children: PhrasingContent[]; +} + +export interface FootnoteReference extends Node, Association { + type: 'footnoteReference'; +} + +// Mixin +export interface Resource { + url: string; + title?: string; +} + +export interface Association { + identifier: string; + label?: string; +} + +export interface Reference { + referenceType: ReferenceType; +} + +export interface Alternative { + alt?: string; +} diff --git a/types/mdast/mdast-tests.ts b/types/mdast/mdast-tests.ts new file mode 100644 index 0000000000..b584f498a6 --- /dev/null +++ b/types/mdast/mdast-tests.ts @@ -0,0 +1,66 @@ +import * as Mdast from 'mdast'; + +const text: Mdast.Text = { + type: 'text', + value: 'text' +}; + +const cell: Mdast.TableCell = { + type: 'tableCell', + children: [text] +}; + +const row: Mdast.TableRow = { + type: 'tableRow', + children: [cell] +}; + +const table: Mdast.Table = { + type: 'table', + align: ['left', 'center', 'right'], + children: [row] +}; + +const header: Mdast.Heading = { + type: 'heading', + depth: 1, + children: [text] +}; + +const code: Mdast.Code = { + type: 'code', + lang: 'javascript', + value: 'let n = 42;' +}; + +const paragraph: Mdast.Paragraph = { + type: 'paragraph', + children: [text] +}; + +const item: Mdast.ListItem = { + type: 'listItem', + children: [paragraph] +}; + +const list: Mdast.List = { + type: 'list', + children: [item] +}; + +const footNote: Mdast.FootnoteReference = { + type: 'footnoteReference', + identifier: 'ref1', + label: 'Referfence 1' +}; + +const image: Mdast.Image = { + type: 'image', + url: 'https://github.com/syntax-tree/mdast', + alt: 'image alternative' +}; + +const root: Mdast.Root = { + type: 'root', + children: [header, table, code, image] +}; diff --git a/types/mdast/tsconfig.json b/types/mdast/tsconfig.json new file mode 100644 index 0000000000..2df6fdcfd0 --- /dev/null +++ b/types/mdast/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", "mdast-tests.ts"] +} diff --git a/types/mdast/tslint.json b/types/mdast/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mdast/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mdurl/format.d.ts b/types/mdurl/format.d.ts index 2638c76007..a7cc04cd48 100644 --- a/types/mdurl/format.d.ts +++ b/types/mdurl/format.d.ts @@ -1,4 +1,4 @@ -import { Url } from './' +import { Url } from './'; declare function format(url: Url): string; diff --git a/types/mdurl/parse.d.ts b/types/mdurl/parse.d.ts index cd2c012caa..30c377f35a 100644 --- a/types/mdurl/parse.d.ts +++ b/types/mdurl/parse.d.ts @@ -1,4 +1,4 @@ -import { Url } from './' +import { Url } from './'; declare function parse(input: string, slashesDenoteHost?: boolean): Url; diff --git a/types/meow/index.d.ts b/types/meow/index.d.ts index db3d697691..0ba420bf04 100644 --- a/types/meow/index.d.ts +++ b/types/meow/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for meow 4.x +// Type definitions for meow 5.x // Project: https://github.com/sindresorhus/meow // Definitions by: KnisterPeter // Lindsey Smith @@ -26,6 +26,11 @@ declare namespace meow { flags?: buildOptions.Options; autoHelp?: boolean; autoVersion?: boolean; + /** + * Caution: Explicitly specifying undefined for booleanDefault + * has different meaning from omitting key itself. + */ + booleanDefault?: boolean | null; } interface Result { diff --git a/types/meow/meow-tests.ts b/types/meow/meow-tests.ts index 1b044881b5..c2059eefe6 100644 --- a/types/meow/meow-tests.ts +++ b/types/meow/meow-tests.ts @@ -1,6 +1,7 @@ import meow = require('meow'); const cli = meow('Help text', { + booleanDefault: undefined, flags: { unicorn: { type: 'boolean', @@ -29,6 +30,7 @@ const cli3 = meow({ inferType: true, autoHelp: true, autoVersion: true, + booleanDefault: false, flags: { unicorn: { type: 'boolean', diff --git a/types/merge-env/index.d.ts b/types/merge-env/index.d.ts new file mode 100644 index 0000000000..3318b8328f --- /dev/null +++ b/types/merge-env/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for merge-env 1.0 +// Project: https://github.com/bholloway/merge-env +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +export = mergeEnv; + +declare function mergeEnv(target: object, ...sources: any[]): any; diff --git a/types/merge-env/merge-env-tests.ts b/types/merge-env/merge-env-tests.ts new file mode 100644 index 0000000000..26ad7ecc05 --- /dev/null +++ b/types/merge-env/merge-env-tests.ts @@ -0,0 +1,3 @@ +import mergeEnv = require("merge-env"); + +const mergedConfiguration = mergeEnv({}, {}, {}); diff --git a/types/merge-env/tsconfig.json b/types/merge-env/tsconfig.json new file mode 100644 index 0000000000..a058625dcb --- /dev/null +++ b/types/merge-env/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", + "merge-env-tests.ts" + ] +} diff --git a/types/merge-env/tslint.json b/types/merge-env/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/merge-env/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/meteor-astronomy/index.d.ts b/types/meteor-astronomy/index.d.ts new file mode 100644 index 0000000000..e23834963c --- /dev/null +++ b/types/meteor-astronomy/index.d.ts @@ -0,0 +1,145 @@ +// Type definitions for meteor-astronomy 2.6 +// Project: https://github.com/jagi/meteor-astronomy/ +// Definitions by: Igor Golovin +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +declare namespace MeteorAstronomy { + type NonFunctionPropertyNames = { [K in keyof T]: T[K] extends Function ? never : K }[keyof T]; // tslint:disable-line:ban-types + type NonFunctionProperties = Pick>; + type FunctionPropertyNames = { [K in keyof T]: T[K] extends Function ? K : never }[keyof T]; // tslint:disable-line:ban-types + type FunctionProperties = Pick>; + + type TypeOptionsPrimitives = typeof String | typeof Date | typeof Boolean | typeof Object | typeof Number; + type TypeOptions = TypeOptionsPrimitives | TypeOptionsPrimitives[] | Class | Enum; + + interface SaveAndValidateOptions { + fields?: K[]; + stopOnFirstError?: boolean; + simulation?: boolean; + cast?: boolean; + } + + type SaveAndValidateCallback = (err: any, id: any) => void; + type RemoveCallback = (err: any, result: any) => void; + + interface Validator { + type: string; + param: any; + } + + interface ModelFullField { + type: TypeOptions; + optional?: boolean; + transient?: boolean; + immutable?: boolean; + default?: () => Field | Field; + index?: string | number; + validators?: Validator[]; + resolve?: (doc: Doc) => Field; + } + + type ModelField = ModelFullField | TypeOptions; + + type Fields = { + [P in keyof NonFunctionProperties]: ModelField; + }; + + type Helpers = { + [P in keyof FunctionProperties]: (this: T, ...args: any[]) => any; + }; + + interface ClassModel { + name: string; + collection?: Mongo.Collection; + fields: Fields; + behaviors?: object; + secured?: { + insert: boolean, + update: boolean, + remove: boolean, + } | boolean; + helpers?: Helpers; + events?: object; + meteorMethods?: object; + indexes?: object; + } + + interface EnumModel { + name: string; + identifiers: string[] | T; + } + + type Model = T & { + set(fields: Partial, options?: {cast?: boolean; clone?: boolean; merge?: boolean}): void; + set(field: string, value: any): void; + get(field: string): any; + get(fields: string[]): any[]; + isModified(field?: string): boolean; + getModified(): any; + getModifiedValues(options?: {old?: boolean, raw?: boolean}): Partial; + getModifier(): any; + raw(): T; + raw(field: string): any; + raw(fields: string[]): any[]; + save(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + save(callback?: SaveAndValidateCallback): void; + copy(save: boolean): any; + validate(options?: SaveAndValidateOptions, callback?: SaveAndValidateCallback): void; + validate(callback?: SaveAndValidateCallback): void; + remove(callback?: RemoveCallback): void; + }; + + interface FindOneOptions { + sort?: Mongo.SortSpecifier; + skip?: number; + fields?: Mongo.FieldSpecifier; + reactive?: boolean; + transform?: (...args: any[]) => any; + disableEvents?: boolean; + children?: number; + defaults?: boolean; + } + + interface FindOptions extends FindOneOptions { + limit?: number; + } + + interface UpsertOptions { + multi?: boolean; + } + + interface UpdateOptions extends UpsertOptions { + upsert?: boolean; + } + + type MongoQuery = Mongo.Selector | Mongo.ObjectID | string; + + interface Class { + new(data?: Partial): Model; + + findOne(selector?: MongoQuery, options?: FindOneOptions): Model; + find(selector?: MongoQuery, options?: FindOptions): Mongo.Cursor>; + insert(doc: T, callback?: () => void): string; + update(selector: MongoQuery, modifier: Mongo.Modifier, options?: UpdateOptions, callback?: () => void): number; + upsert(selector: MongoQuery, modifier: Mongo.Modifier, options?: UpsertOptions, callback?: () => void): number; + remove(selector: MongoQuery, callback?: () => void): number; + } + + type Enum = T & { + getValues(): any[]; + getIdentifier(identifier: any): string; + }; +} + +declare module 'meteor/jagi:astronomy' { // tslint:disable-line:no-single-declare-module + namespace Class { + function create(model: MeteorAstronomy.ClassModel): MeteorAstronomy.Class; + } + + namespace Enum { + function create(model: MeteorAstronomy.EnumModel): MeteorAstronomy.Enum; + } +} diff --git a/types/meteor-astronomy/meteor-astronomy-tests.ts b/types/meteor-astronomy/meteor-astronomy-tests.ts new file mode 100644 index 0000000000..2c6fe7d34c --- /dev/null +++ b/types/meteor-astronomy/meteor-astronomy-tests.ts @@ -0,0 +1,200 @@ +import { Class, Enum } from 'meteor/jagi:astronomy'; +import { Meteor } from 'meteor/meteor'; +import { Mongo } from 'meteor/mongo'; + +interface PostInterface { + title: string; + name: string; + userId: string; + publishedAt: Date; + tags?: string[]; +} + +const Posts = new Mongo.Collection('posts'); + +const Post = Class.create({ + name: 'Post', + collection: Posts, + fields: { + name: String, + title: { + type: String, + validators: [{ + type: 'minLength', + param: 3 + }], + }, + userId: String, + publishedAt: Date, + tags: { + type: [String], + default(): string[] { + return []; + }, + }, + }, + behaviors: { + timestamp: {} + }, +}); + +let post = new Post({ + title: 'text', +}); + +// Validate length of the "title" field. +post.save(); + +// Notice that we call the "findOne" method +// from the "Post" class not from the "Posts" collection. +post = Post.findOne('id'); +// Auto convert a string input value to a number. +post.title = 'input[name=title]'; +post.publishedAt = new Date(); +// Check if all fields are valid and update document +// with only the fields that have changed. +post.save({fields: ['title']}); + +interface UserProfileInterface { + nickname: string; + firstName: string; + createdAt: Date; + age: number; +} + +const UserProfile = Class.create({ + name: 'UserProfile', + fields: { + nickname: String, + firstName: String, + createdAt: Date, + age: Number, + } +}); + +interface UserInterface extends Meteor.User { + address: object; + firstName: string; + lastName: string; + phone: string; + phoneNumber: string; + fullName: (param: string) => string; +} + +const User = Class.create({ + name: 'User', + collection: Meteor.users as Mongo.Collection, + fields: { + createdAt: Number, + firstName: String, + lastName: String, + emails: { + type: [Object], + default: (): Meteor.UserEmail[] => [], + }, + profile: { + type: UserProfile, + default: () => {}, + }, + address: { + type: Object, + optional: true + }, + phoneNumber: { + type: String, + }, + phone: { + type: String, + resolve(doc: UserInterface) { + return doc.phoneNumber; + }, + }, + }, + helpers: { + fullName(param: string): string { + const fullName = `${this.firstName} ${this.lastName}`; + + if (param === 'lower') { + return fullName.toLowerCase(); + } else if (param === 'upper') { + return fullName.toUpperCase(); + } + + return fullName; + }, + }, + indexes: { + fullName: { // Index name. + fields: { // List of fields. + phoneNumber: 1, + createdAt: 1 + }, + options: {} + } + } +}); + +const user = User.findOne(); +user.set({username: 'user1'}); +user.save(); + +interface StatusInterface { + OPENED: number; + CLOSED: number; + DONE: number; + CANCELED: number; +} + +const Status = Enum.create({ + name: 'Status', + identifiers: ['OPENED', 'CLOSED', 'DONE', 'CANCELED'], +}); + +const Issue = Class.create({ + name: 'Issue', + fields: { + status: { + type: Status + } + } +}); + +Status.getValues(); // [0, 1, 2, 3] + +interface StatusBisInterface { + OPENED: string; + CLOSED: string; + DONE: string; + CANCELED: string; +} + +const StatusBis = Enum.create({ + name: 'Status', + identifiers: { + OPENED: 'OPENED', + CLOSED: 'CLOSED', + DONE: 'DONE', + CANCELED: 'CANCELED', + } +}); + +StatusBis.getValues(); // [5, 6, 15, 16] + +const statusNumber = Status.OPENED; + +Status.getIdentifier(statusNumber); // "OPENED" + +// server.js +Meteor.publish('posts', () => { + Post.find({}, {fields: {title: 1}}); +}); + +Meteor.subscribe('posts'); +const post1 = Post.findOne({}, {defaults: false}); +post1.name = 'New name'; +post1.getModifier(); // {$set: {name: 'New name'}} - it will not override tags +post1.save(); + +const user1 = User.findOne({}, { + disableEvents: true +}); diff --git a/types/vega/tsconfig.json b/types/meteor-astronomy/tsconfig.json similarity index 92% rename from types/vega/tsconfig.json rename to types/meteor-astronomy/tsconfig.json index f49e5e811b..90412b0069 100644 --- a/types/vega/tsconfig.json +++ b/types/meteor-astronomy/tsconfig.json @@ -19,6 +19,6 @@ }, "files": [ "index.d.ts", - "vega-tests.ts" + "meteor-astronomy-tests.ts" ] -} \ No newline at end of file +} diff --git a/types/meteor-astronomy/tslint.json b/types/meteor-astronomy/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/meteor-astronomy/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/meteor-collection-hooks/meteor-mongo.d.ts b/types/meteor-collection-hooks/meteor-mongo.d.ts index d45bd7582a..45092a89fd 100644 --- a/types/meteor-collection-hooks/meteor-mongo.d.ts +++ b/types/meteor-collection-hooks/meteor-mongo.d.ts @@ -151,4 +151,4 @@ declare module 'meteor/mongo' { all?: LocalHookOptions; } } -} \ No newline at end of file +} diff --git a/types/meteor/react-meteor-data.d.ts b/types/meteor/react-meteor-data.d.ts new file mode 100644 index 0000000000..517c10ff8f --- /dev/null +++ b/types/meteor/react-meteor-data.d.ts @@ -0,0 +1,5 @@ +import * as React from 'react'; + +export function withTracker( + options: (props: TOwnProps) => TDataProps | {getMeteorData: (props: TOwnProps) => TDataProps, pure?: boolean} +): (reactComponent: React.ComponentType) => React.ComponentClass; diff --git a/types/meteor/test/globals/meteor-tests.ts b/types/meteor/test/globals/meteor-tests.ts index c2145be0a6..e3a3e750bb 100644 --- a/types/meteor/test/globals/meteor-tests.ts +++ b/types/meteor/test/globals/meteor-tests.ts @@ -371,19 +371,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); -Comments.find({ inlineLinks: { $exists: true, $type: "array" } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ $query: {inlineLinks: { $exists: true, $type: "array" } } }); +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); @@ -697,7 +697,7 @@ Accounts.onPageLoadLogin(function () { }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts = { +var loginOpts = { requestPermissions: ["a", "b"], requestOfflineToken: true, loginUrlParameters: { asdf: 1, qwer: "1234" }, @@ -705,7 +705,7 @@ var loginOpts = { loginStyle: "Bold and powerful", redirectUrl: "popup", profile: "asdfasdf" -}; +} as Meteor.LoginWithExternalServiceOptions; Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; @@ -748,7 +748,7 @@ const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetti // Covers https://github.com/meteor-typings/meteor/issues/9 -const username = (Template.instance().find('#username')).value; +const username = (Template.instance().find('#username') as HTMLInputElement).value; // Covers https://github.com/meteor-typings/meteor/issues/3 diff --git a/types/meteor/test/meteor-tests.ts b/types/meteor/test/meteor-tests.ts index c7fde5b8be..63f83ef79d 100644 --- a/types/meteor/test/meteor-tests.ts +++ b/types/meteor/test/meteor-tests.ts @@ -383,19 +383,19 @@ Comments.find({ viewNumber: { $gt: 100 } }); Comments.find({ viewNumber: { $not: { $lt: 100, $gt: 1000 } } }); Comments.find({ tags: { $in: [ "tag-1", "tag-2", "tag-3" ] } }); Comments.find({ $or: [ { text: "hello" }, { text: "world" } ] }); -Comments.find({ $or: [ - { text: "hello" }, - { text: "world", viewNumber: { $gt: 0 } } +Comments.find({ $or: [ + { text: "hello" }, + { text: "world", viewNumber: { $gt: 0 } } ], authorId: "test-author-id" }); -Comments.find({ $and: [ - { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, +Comments.find({ $and: [ + { $or: [{ authorId: "author-id-1" }, { authorId: "author-id-2" }] }, { $or: [{ tags: "tag-1" }, { tags: "tag-2" }] } ]}); -Comments.find({ inlineLinks: { $exists: true, $type: "array" } }); -Comments.find({ inlineLinks: { $elemMatch: { - objectType: InlineObjectType.Image, - objectUrl: { $regex: "https://(www\.?)youtube\.com" } +Comments.find({ $query: { inlineLinks: { $exists: true, $type: "array" } } }); +Comments.find({ inlineLinks: { $elemMatch: { + objectType: InlineObjectType.Image, + objectUrl: { $regex: "https://(www\.?)youtube\.com" } } } }); Comments.find({ "inlineLinks.objectType": InlineObjectType.Person }); Comments.find({ tags: "tag-1" }); @@ -709,7 +709,7 @@ Accounts.onPageLoadLogin(function () { }); // Covers this PR: https://github.com/DefinitelyTyped/DefinitelyTyped/pull/8065 -var loginOpts = { +var loginOpts = { requestPermissions: ["a", "b"], requestOfflineToken: true, loginUrlParameters: { asdf: 1, qwer: "1234" }, @@ -717,7 +717,7 @@ var loginOpts = { loginStyle: "Bold and powerful", redirectUrl: "popup", profile: "asdfasdf" -}; +} as Meteor.LoginWithExternalServiceOptions; Meteor.loginWithMeteorDeveloperAccount(loginOpts, function (error: Meteor.Error) { }); Accounts.emailTemplates.siteName = "AwesomeSite"; @@ -760,7 +760,7 @@ const deeperPrivateSetting = Meteor.settings['somePrivateSettings']['deeperSetti // Covers https://github.com/meteor-typings/meteor/issues/9 -const username = (Template.instance().find('#username')).value; +const username = (Template.instance().find('#username') as HTMLInputElement).value; // Covers https://github.com/meteor-typings/meteor/issues/3 diff --git a/types/meteor/test/react-meteor-data-tests.tsx b/types/meteor/test/react-meteor-data-tests.tsx new file mode 100644 index 0000000000..cea13d6030 --- /dev/null +++ b/types/meteor/test/react-meteor-data-tests.tsx @@ -0,0 +1,27 @@ +import * as React from 'react'; +import { withTracker } from 'meteor/react-meteor-data'; + +interface DemoComponentContainerProps { + status: string; +} + +interface DemoComponentData { + data: string; + result: string; +} + +const DemoComponent: React.SFC = (props) => ( +
          {props.data}
          +); + +const DemoComponentContainer: React.ComponentClass = withTracker< + DemoComponentData, + DemoComponentContainerProps +>(() => ({ + data: 'some data', + result: 'success', +}))(DemoComponent); + +const RootComponent = () => ( + +); diff --git a/types/meteor/tsconfig.json b/types/meteor/tsconfig.json index ed6a9e0e77..42295d06e1 100644 --- a/types/meteor/tsconfig.json +++ b/types/meteor/tsconfig.json @@ -63,6 +63,8 @@ "test/meteor-tests.ts", "test/globals/meteor-tests.ts", "test/meteor-tests-module-only.ts", - "test/server-render.tsx" + "test/server-render.tsx", + "react-meteor-data.d.ts", + "test/react-meteor-data-tests.tsx" ] } diff --git a/types/micro/index.d.ts b/types/micro/index.d.ts index f3787b1010..251e42ee46 100644 --- a/types/micro/index.d.ts +++ b/types/micro/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +/// + import { IncomingMessage, ServerResponse, Server } from 'http'; export type RequestHandler = (req: IncomingMessage, res: ServerResponse) => any; diff --git a/types/minio/index.d.ts b/types/minio/index.d.ts index 1bb407529d..e81661c506 100644 --- a/types/minio/index.d.ts +++ b/types/minio/index.d.ts @@ -61,6 +61,7 @@ export interface IncompleteUploadedBucketItem { export interface BucketStream extends Stream { on(event: 'data', listener: (item: T) => void): this; + on(event: 'error', listener: (error: Error) => void): this; } export interface PostPolicyResult { 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/mjml-react/index.d.ts b/types/mjml-react/index.d.ts new file mode 100644 index 0000000000..decb895010 --- /dev/null +++ b/types/mjml-react/index.d.ts @@ -0,0 +1,413 @@ +// Type definitions for mjml-react 1.0 +// Project: https://github.com/wix-incubator/mjml-react +// Definitions by: Henri Normak +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export namespace extensions { + class MjmlComment extends React.Component<{ children: string }> { } + class MjmlConditionalComment extends React.Component<{ children: string; condition: string }> { } + class MjmlTrackingPixel extends React.Component<{ src: string }> { } + class MjmlYahooStyle extends React.Component<{ children: string }> { } +} + +export namespace utils { + function namedEntityToHexCode(html: string): string; + function fixConditionalComment(html: string, havingContent: string, newCondition: string): string; + function useHttps(url?: string): string | undefined; + function toMobileFontSize(sizeWithUnit: string): number; + function addQueryParams(url: string, params: { [key: string]: any }): string; + + type TextAlignment = 'left' | 'right' | 'center' | 'justify' | 'inherit'; + function getTextAlign(value: string, fallback?: TextAlignment): TextAlignment; +} + +export function renderToMjml(email: React.ReactElement): string; + +export interface Mjml2HtmlOptions { + fonts?: { [key: string]: string }; + keepComments?: boolean; + beautify?: boolean; + minify?: boolean; + validationLevel?: 'strict' | 'soft' | 'skip'; + filePath?: string; +} + +export function render(email: React.ReactElement, options?: Mjml2HtmlOptions): { html: string; errors: Error[] }; + +// Components + +export interface RequiredChildrenProps { + children: React.ReactNode; +} + +export interface PaddingProps { + padding?: string | number; + paddingTop?: string | number; + paddingRight?: string | number; + paddingBottom?: string | number; + paddingLeft?: string | number; +} + +export interface BorderProps { + border?: string; + borderBottom?: string; + borderLeft?: string; + borderTop?: string; + borderRight?: string; + borderRadius?: string | number; +} + +export interface ClassNameProps { + cssClass?: string; +} + +export interface HrefProps { + href?: string; + target?: string; + rel?: string; +} + +// mjml +export interface MjmlProps { + lang?: string; + owa?: string; +} + +export class Mjml extends React.Component { } + +// mj-head +export class MjmlHead extends React.Component { } + +// mj-attributes +export class MjmlAttributes extends React.Component { } +export class MjmlAll extends React.Component<{ [key: string]: any; children?: React.ReactNode }> { } +export class MjmlClass extends React.Component<{ [key: string]: any; children?: React.ReactNode; name: string }> { } + +// mj-breakpoint +export interface MjmlBreakpointProps { + width?: string | number; +} + +export class MjmlBreakpoint extends React.Component { } + +// mj-body +export interface MjmlBodyProps { + width ?: number; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlBody extends React.Component { } + +// mj-font +export interface MjmlFontProps { + href?: string; + name?: string; +} + +export class MjmlFont extends React.Component { } + +// mj-preview +export class MjmlPreview extends React.Component<{ children: string }> { } + +// mj-style +export class MjmlStyle extends React.Component<{ children: string, inline?: boolean }> { } + +// mj-title +export class MjmlTitle extends React.Component<{ children: string }> { } + +// mj-accordion +export class MjmlAccordion extends React.Component { } + +export interface MjmlAccordionElementProps { + fontFamily?: string; + iconAlign?: string; + iconWrappedUrl?: string; + iconWrappedAlt?: string; + iconUnwrappedAlt?: string; + iconUnwrappedUrl?: string; + iconPosition?: 'left' | 'right'; + iconHeight?: string; + iconWidth?: string; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlAccordionElement extends React.Component { } + +export interface MjmlAccordionTextProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlAccordionText extends React.Component { } + +export interface MjmlAccordionTitleProps { + color?: React.CSSProperties['color']; + backgroundColor?: React.CSSProperties['backgroundColor']; + fontFamily?: string; + fontSize?: string | number; +} + +export class MjmlAccordionTitle extends React.Component { } + +// mj-button +export interface MjmlButtonProps { + backgroundColor?: React.CSSProperties['backgroundColor']; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + fontStyle?: string; + fontSize?: string | number; + fontWeight?: number; + fontFamily?: string; + color?: React.CSSProperties['color']; + textAlign?: React.CSSProperties['textAlign']; + textDecoration?: string; + textTransform?: string; + align?: string; + verticalAlign?: React.CSSProperties['verticalAlign']; + lineHeight?: string | number; + innerPadding?: string; + width?: string | number; + height?: string | number; +} + +export class MjmlButton extends React.Component { } + +// mj-carousel +export interface MjmlCarouselProps { + backgroundColor?: React.CSSProperties['backgroundColor']; + align?: string; + borderRadius?: string | number; + thumbnails?: 'hidden' | 'visible'; + tbBorder?: React.CSSProperties['border']; + tbBorderRadius?: React.CSSProperties['borderRadius']; + tbHoverBorderColor?: string; + tbSelectedBorderColor?: string; + tbWidth?: string; + leftIcon?: string; + rightIcon?: string; + iconWidth?: string; +} + +export class MjmlCarousel extends React.Component {} + +export interface MjmlCarouselImageProps { + src?: string; + thumbnailsSrc?: string; + alt?: string; + title?: string; +} + +export class MjmlCarouselImage extends React.Component { } + +// mj-carousel +export interface MjmlColumnProps { + width?: string | number; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlColumn extends React.Component { } + +// mj-divider +export interface MjmlDividerProps { + borderColor?: React.CSSProperties['borderColor']; + borderStyle?: React.CSSProperties['borderStyle']; + borderWidth?: string | number; + width?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlDivider extends React.Component { } + +// mj-group +export interface MjmlGroupProps { + width?: string | number; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlGroup extends React.Component { } + +// mj-hero +export interface MjmlHeroProps { + width?: string | number; + height?: string | number; + mode?: 'fluid-height' | 'fixed-height'; + backgroundWidth?: string; + backgroundHeight?: string; + backgroundUrl?: string; + backgroundPosition?: React.CSSProperties['backgroundPosition']; + verticalAlign?: React.CSSProperties['verticalAlign']; + backgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlHero extends React.Component { } + +// mj-image +export interface MjmlImageProps { + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + border?: React.CSSProperties['border']; + borderRadius?: string | number; + width?: string | number; + height?: string | number; + src?: string; + srcset?: string; + alt?: string; + align?: string; + title?: string; + fluidOnMobile?: string; +} + +export class MjmlImage extends React.Component { } + +// mj-navbar +export interface MjmlNavbarProps { + baseUrl?: string; + hamburger?: 'hamburger'; + align?: string; + icoOpen?: string; + icoClose?: string; + icoPadding?: string; + icoPaddingTop?: string; + icoPaddingRight?: string; + icoPaddingBottom?: string; + icoPaddingLeft?: string; + icoAlign?: string; + icoColor?: React.CSSProperties['color']; + icoFontSize?: string; + icoTextTransform?: string; + icoTextDecoration?: string; + icoLineHeight?: string; +} + +export class MjmlNavbar extends React.Component { } + +export interface MjmlNavbarLinkProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + fontWeight?: number; + lineHeight?: string | number; + textDecoration?: string; + textTransform?: string; +} + +export class MjmlNavbarLink extends React.Component { } + +// mj-raw +export class MjmlRaw extends React.Component { } + +// mj-section +export interface MjmlSectionProps { + fullWidth?: boolean; + backgroundColor?: React.CSSProperties['backgroundColor']; + backgroundUrl?: string; + backgroundRepeat?: React.CSSProperties['backgroundRepeat']; + backgroundSize?: React.CSSProperties['backgroundSize']; + verticalAlign?: React.CSSProperties['verticalAlign']; + textAlign?: React.CSSProperties['textAlign']; + direction?: 'ltr' | 'rtl'; +} + +export class MjmlSection extends React.Component { } + +// mj-social +export interface MjmlSocialProps { + borderRadius?: string | number; + fontFamily?: string; + fontSize?: string | number; + iconSize?: string; + iconHeight?: string; + lineHeight?: string | number; + mode?: 'vertical' | 'horizontal'; + textDecoration?: string; + align?: string; + color?: React.CSSProperties['color']; + innerPadding?: string; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlSocial extends React.Component { } + +export interface MjmlSocialElementProps { + borderRadius?: string | number; + backgroundColor?: React.CSSProperties['backgroundColor']; + fontFamily?: string; + fontSize?: string | number; + iconSize?: string; + iconHeight?: string; + lineHeight?: string | number; + mode?: 'vertical' | 'horizontal'; + textDecoration?: string; + align?: string; + color?: React.CSSProperties['color']; + name?: 'facebook' | 'facebook-noshare' | 'twitter' | 'twitter-noshare' | 'google' | 'google-noshare' | 'pinterest' | 'pinterest-noshare' | + 'linkedin' | 'linkedin-noshare' | 'tumblr' | 'tumblr-noshare' | 'xing' | 'xing-noshare' | + 'github' | 'instagram' | 'web' | 'snapchat' | 'youtube' | 'vimeo' | 'medium' | 'soundcloud' | 'dribbble'; + src?: string; + alt?: string; +} + +export class MjmlSocialElement extends React.Component { } + +// mj-spacer +export interface MjmlSpacerProps { + height?: string | number; + width?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + verticalAlign?: React.CSSProperties['verticalAlign']; +} + +export class MjmlSpacer extends React.Component { } + +// mj-table +export interface MjmlTableProps { + color?: React.CSSProperties['color']; + cellpadding?: string; + cellspacing?: string; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + lineHeight?: string | number; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; + width?: string | number; + tableLayout?: 'auto' | 'fixed' | 'initial' | 'inherit'; +} + +export class MjmlTable extends React.Component { } + +// mj-text +export interface MjmlTextProps { + color?: React.CSSProperties['color']; + fontFamily?: string; + fontSize?: string | number; + fontStyle?: string; + fontWeight?: number; + lineHeight?: string; + letterSpacing?: string; + height?: string | number; + textDecoration?: string; + textTransform?: string; + align?: string; + containerBackgroundColor?: React.CSSProperties['backgroundColor']; +} + +export class MjmlText extends React.Component { } + +// mj-wrapper +export interface MjmlWrapperProps { + fullWidth?: boolean; + backgroundColor?: React.CSSProperties['backgroundColor']; + backgroundUrl?: string; + backgroundRepeat?: React.CSSProperties['backgroundRepeat']; + backgroundSize?: React.CSSProperties['backgroundSize']; + verticalAlign?: React.CSSProperties['verticalAlign']; + textAlign?: React.CSSProperties['textAlign']; +} + +export class MjmlWrapper extends React.Component { } diff --git a/types/mjml-react/mjml-react-tests.tsx b/types/mjml-react/mjml-react-tests.tsx new file mode 100644 index 0000000000..7ff38e21f8 --- /dev/null +++ b/types/mjml-react/mjml-react-tests.tsx @@ -0,0 +1,40 @@ +import * as React from 'react'; +import { + render, + Mjml, + MjmlHead, + MjmlTitle, + MjmlPreview, + MjmlBody, + MjmlSection, + MjmlColumn, + MjmlButton, + MjmlImage +} from 'mjml-react'; + +function renderOutTestEmail() { + // $ExpectType { html: string; errors: Error[]; } + const result = render(( + + + Last Minute Offer + Last Minute Offer... + + + + + + + + + + + + I like it! + + + + + + ), { validationLevel: 'soft' }); +} diff --git a/types/mjml-react/tsconfig.json b/types/mjml-react/tsconfig.json new file mode 100644 index 0000000000..11cabc646f --- /dev/null +++ b/types/mjml-react/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "mjml-react-tests.tsx" + ] +} diff --git a/types/mjml-react/tslint.json b/types/mjml-react/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mjml-react/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mobx-apollo/index.d.ts b/types/mobx-apollo/index.d.ts index 54818cd846..fe976af2d2 100644 --- a/types/mobx-apollo/index.d.ts +++ b/types/mobx-apollo/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/sonaye/mobx-apollo#readme // Definitions by: Paul Selden // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.6 import { ApolloClient, diff --git a/types/mobx-apollo/tsconfig.json b/types/mobx-apollo/tsconfig.json index cff69dc655..c7ab33e386 100644 --- a/types/mobx-apollo/tsconfig.json +++ b/types/mobx-apollo/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "target": "es5", "noImplicitAny": true, diff --git a/types/mochaccino/index.d.ts b/types/mochaccino/index.d.ts index 3f0a2e9688..4dbc62b7d9 100644 --- a/types/mochaccino/index.d.ts +++ b/types/mochaccino/index.d.ts @@ -2,8 +2,8 @@ // Project: https://github.com/pawelgalazka/mochaccino#readme // Definitions by: Thomas-P // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 -import * as Sinon from "sinon"; +// TypeScript Version: 3.0 +import * as Sinon from 'sinon'; export interface Expect { not: Expect; toBe(arg: any): void; diff --git a/types/mock-aws-s3/index.d.ts b/types/mock-aws-s3/index.d.ts index 754629f5a2..437c785f98 100644 --- a/types/mock-aws-s3/index.d.ts +++ b/types/mock-aws-s3/index.d.ts @@ -4,6 +4,8 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/mock-aws-s3 // TypeScript Version: 2.2 +/// + // This is a mocking library, types should reflect that of the actual library. export * from "aws-sdk"; import { GlobalConfigInstance } from "aws-sdk/lib/config"; 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/mockjs/index.d.ts b/types/mockjs/index.d.ts index 9be645b791..25d6cac833 100644 --- a/types/mockjs/index.d.ts +++ b/types/mockjs/index.d.ts @@ -198,7 +198,7 @@ declare namespace mockjs { city(prefix?: B): S; // Random.county - country(prefix?: B): S; + county(prefix?: B): S; // Random.zip zip(prefix?: B): S; diff --git a/types/module-deps/index.d.ts b/types/module-deps/index.d.ts new file mode 100644 index 0000000000..94706542a1 --- /dev/null +++ b/types/module-deps/index.d.ts @@ -0,0 +1,181 @@ +// Type definitions for module-deps 6.1 +// Project: https://github.com/browserify/module-deps +// Definitions by: TeamworkGuy2 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +import * as browserResolve from "browser-resolve"; + +/** + * Return an object transform stream 'd' that expects entry filenames or '{ id: ..., file: ... }' objects + * as input and produces objects for every dependency from a recursive module traversal as output. + */ +declare function moduleDeps(opts?: moduleDeps.Options): moduleDeps.ModuleDepsObject; + +/** + * Walk the dependency graph to generate json output that can be fed into browser-pack + */ +declare namespace moduleDeps { + /** + * module-deps constructor options + */ + interface Options { + /** + * A string or array of string transforms + */ + transform?: string | string[]; + + /** + * An array path of strings showing where to look in the package.json + * for source transformations. If falsy, don't look at the package.json at all + */ + transformKey?: string[]; + + /** + * Custom resolve function using the opts.resolve(id, parent, cb) signature that browser-resolve has + */ + resolve?: (id: string, opts: browserResolve.SyncOpts, cb: (err?: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => void) => void; + + /** + * A custom dependency detection function. opts.detect(source) should return an array of dependency module names. By default detective is used + */ + detect?: (source: string) => string[]; + + /** + * A function (id) to skip resolution of some module id strings. If defined, + * opts.filter(id) should return truthy for all the ids to include and falsey for all the ids to skip. + */ + filter?: (id: string) => boolean; + + /** + * A function (id, file, pkg) that gets called after id has been resolved. + * Return false to skip this file + */ + postFilter?: (id: string, file: string, pkg: PackageObject) => (void | boolean); // tslint:disable-line:void-return + + /** + * Transform the parsed package.json contents before using the values. + * opts.packageFilter(pkg, dir) should return the new pkg object to use. + */ + packageFilter?: (pkg: PackageObject, dir: string) => PackageObject; + + /** + * An array of absolute paths to not parse for dependencies. + * Use this for large dependencies like jquery or threejs which take forever to parse. + */ + noParse?: boolean | string[]; + + /** + * An object mapping filenames to file objects to skip costly io + */ + cache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to their parent package.json contents + * for browser fields, main entries, and transforms + */ + packageCache?: { [fileName: string]: any }; + + /** + * An object mapping filenames to raw source to avoid reading from disk. + */ + fileCache?: { [fileName: string]: string }; + + /** + * A complex cache handler that allows async and persistent caching of data. + */ + persistentCache?: (file: string, id: string, pkg: PackageObject, fallback: (dataAsString: string, cb: CacheCallback) => void, cb: CacheCallback) => void; + + /** + * Array of global paths to search. Defaults to splitting on ':' in process.env.NODE_PATH + */ + paths?: string[]; + + /** + * Ignore files that failed to resolve + */ + ignoreMissing?: boolean; + + // un-documented options used by module-deps + basedir?: string; + globalTransform?: any[]; + extensions?: string[]; + modules?: { [name: string]: any }; + expose?: { [name: string]: string }; + + [prop: string]: any; + } + + interface ModuleDepsObject extends NodeJS.ReadWriteStream { + resolve(id: string, parent: { id: string }, cb: (err: Error | null, file?: string, pkg?: PackageObject, fakePath?: any) => any): any; + + readFile(file: string, id?: any, pkg?: PackageObject): NodeJS.ReadableStream; + + getTransforms(file: string, pkg: PackageObject, opts?: { builtin?: boolean; inNodeModules?: boolean }): NodeJS.ReadWriteStream; + + walk(id: string | { file: string; id: string; entry?: boolean; expose?: string; noparse?: boolean; source?: string }, + parent: { modules: any }, + cb: (err: Error | null, file?: string) => void): void; + + parseDeps(file: string, src: string, cb: any): any[]; + + lookupPackage(file: string, cb: (a: any, b: any, c?: any) => any): void; + + _isTopLevel(file: string): boolean; + _transform(row: string | InputRow | InputTransform, enc: string, next: () => void): void; + _flush(): void; + + /** + * Every time a transform is applied to a file, a 'transform' event fires with the instantiated transform stream tr. + */ + on(event: "transform", listener: (tr: any, file: string) => any): this; + /** + * Every time a file is read, this event fires with the file path. + */ + on(event: "file", listener: (file: string, id: string) => any): this; + /** + * When opts.ignoreMissing is enabled, this event fires for each missing package. + */ + on(event: "missing", listener: (id: string, parent: { id: string; filename: string; [prop: string]: any }) => any): this; + /** + * Every time a package is read, this event fires. The directory name of the package is available in pkg.__dirname. + */ + on(event: "package", listener: (package: PackageObject) => any): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + } + + type CacheCallback = (err: Error | null, res?: { source: string; package: any; deps: { [dep: string]: boolean } }) => void; + + interface InputRow { + file: string; + id: string; + entry?: boolean; + expose: string; + noparse?: boolean; + } + + interface InputTransform { + transform: string | (() => any); + options: any; + global?: boolean; + } + + interface TransformObject { + id: string; + file: string; + entry: boolean; + expose: string; + source: string; + deps: { [requireName: string]: any }; + } + + /** + * Placeholder, feel free to redefine or put in a pull request to improve + */ + interface PackageObject { + [prop: string]: any; + } +} + +export = moduleDeps; diff --git a/types/module-deps/module-deps-tests.ts b/types/module-deps/module-deps-tests.ts new file mode 100644 index 0000000000..e0930f8f88 --- /dev/null +++ b/types/module-deps/module-deps-tests.ts @@ -0,0 +1,95 @@ +import moduleDeps = require("module-deps"); + +function coreDepsTest() { + const coreDeps: { [prop: string]: any } = {}; + const coreModules = { + assert: "./assert.js", + buffer: "./buffer.js", + path: "./path.js" + }; + + const opts = { + resolve: () => { }, + modules: coreModules, + extensions: [".js", ".json"] + }; + + const s = moduleDeps(opts); + + s.on("data", (obj) => { + for (const dep of Object.keys(obj.deps)) { + if (dep in coreModules) { + coreDeps[dep] = true; + } + } + }); +} + +function rifiTest() { + const md = moduleDeps({ + resolve: (id, parent, cb) => { + const dependency = id.substr(1); + }, + transform: [], + globalTransform: [], + cache: {} + }); + + md.once("error", (err) => { + console.error(err); + }); +} + +function browserifyTest(opts: moduleDeps.Options) { + const packOpts: moduleDeps.Options = { + basedir: opts.basedir || "./", + externalRequireName: opts["externalRequireName"] || "require", + hasExports: opts["hasExports"] || false, + prelude: opts["prelude"] || undefined, + preludePath: opts["preludePath"] || undefined, + raw: opts["raw"] || false, + sourceMapPrefix: opts["sourceMapPrefix"] || "//#", + standalone: opts["standalone"] || undefined, + standaloneModule: opts["standaloneModule"] || undefined, + }; + + const res = moduleDeps(); // 'opts' are optional + const res2 = moduleDeps(packOpts); + + // ensure return value is a stream + const res3 = res.pipe(res2); + + res.on("error", (err: any) => { + console.error("module-deps error: ", err); + }); + + const inst: moduleDeps.ModuleDepsObject = moduleDeps({ + expose: { id: "file.txt" }, + extensions: [ ".js", ".json" ], + transform: [], + transformKey: ["browserify", "transform"], + filter: (id) => { + if (opts.filter && !opts.filter(id)) return false; + if (["name"].indexOf(id) >= 0) return false; + return true; + }, + postFilter: (id, file, pkg) => { + console.log("postFilter", id, file, pkg); + }, + globalTransform: [], + modules: {}, + resolve: (id, parent, cb) => { + cb(null, "", {}); + } + }); + + inst.on("file", (file, id) => { + console.log("file", file, id); + }); + inst.on("package", (pkg) => { + console.log("package", pkg); + }); + inst.on("transform", (tr, file) => { + console.log("transform", tr, file); + }); +} diff --git a/types/module-deps/tsconfig.json b/types/module-deps/tsconfig.json new file mode 100644 index 0000000000..5dd4af3cc1 --- /dev/null +++ b/types/module-deps/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", + "module-deps-tests.ts" + ] +} \ No newline at end of file diff --git a/types/module-deps/tslint.json b/types/module-deps/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/module-deps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mongodb/index.d.ts b/types/mongodb/index.d.ts index 03ff37a76d..feb12923aa 100644 --- a/types/mongodb/index.d.ts +++ b/types/mongodb/index.d.ts @@ -18,6 +18,8 @@ // Angela-1 // Mikael Lirbank // Hector Ribes +// Florian Richter +// Erik Christensen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -43,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 */ @@ -78,7 +77,7 @@ export interface ClientSession extends EventEmitter { /** The server id associated with this session */ id: any; /** - * Aborts the currently active transaction in this session. + * Aborts the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ abortTransaction(cb?: MongoCallback): Promise; @@ -88,7 +87,7 @@ export interface ClientSession extends EventEmitter { */ advanceOperationTime(operamtionTime: Timestamp): void; /** - * Commits the currently active transaction in this session. + * Commits the currently active transaction in this session. * @param {MongoCallback} [cb] Optional callback for completion of this operation */ commitTransaction(cb?: MongoCallback): Promise; @@ -109,7 +108,7 @@ export interface ClientSession extends EventEmitter { * Used to determine if this session equals another * * @param {ClientSession} session A class representing a client session on the server - * @returns {boolean} if the sessions are equal + * @returns {boolean} if the sessions are equal */ equals(session: ClientSession): boolean; @@ -117,13 +116,13 @@ export interface ClientSession extends EventEmitter { incrementTransactionNumber(): void; /** - * @returns {boolean} this session is currently in a transaction or not + * @returns {boolean} this session is currently in a transaction or not */ inTransaction(): boolean; /** * Starts a new transaction with the given options. - * @param {TransactionOptions} options + * @param {TransactionOptions} options * @memberof ClientSession */ startTransaction(options?: TransactionOptions): void; @@ -218,10 +217,10 @@ export class MongoError extends Error { * client/user (eg. "Email address must be unique" instead of "Both email * address and username must be unique") - which caters for a better (app) * user experience. - * + * * Details: https://github.com/Automattic/mongoose/issues/2129 (issue for * mongoose, but the same applies for the native mongodb driver) - * + * * Note that in mongoose (the link above) the prop in question is called * 'message' while in mongodb it is called 'errmsg'. This can be seen in * multiple places in the source code, for example here: @@ -230,6 +229,7 @@ export class MongoError extends Error { errmsg?: string; } + /** http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html#.connect */ export interface MongoClientOptions extends DbCreateOptions, @@ -239,57 +239,120 @@ export interface MongoClientOptions extends SocketOptions, SSLOptions, HighAvailabilityOptions { - // The logging level (error/warn/info/debug) + + /** + * The logging level (error/warn/info/debug) + */ loggerLevel?: string; - // Custom logger object - logger?: Object; - // Default: false; + + /** + * Custom logger object + */ + logger?: Object | log; + + /** + * Validate MongoClient passed in options for correctness. + * Default: false + */ validateOptions?: Object; - // The name of the application that created this MongoClient instance. + + /** + * The name of the application that created this MongoClient instance. + */ appname?: string; + + /** + * Authentifikation credentials + */ auth?: { + /** + * The username for auth + */ user: string; + /** + * The password for auth + */ password: string; - }, - // Determines whether or not to use the new url parser - useNewUrlParser?: boolean + }; + + /** + * Determines whether or not to use the new url parser + */ + useNewUrlParser?: boolean; + + /** + * Mechanism for authentication: DEFAULT, GSSAPI, PLAIN, MONGODB-X509, 'MONGODB-CR', SCRAM-SHA-1 or SCRAM-SHA-256 + */ + authMechanism?: 'DEFAULT' | 'GSSAPI' | 'PLAIN' | 'MONGODB-X509' | 'MONGODB-CR' | 'SCRAM-SHA-1' | 'SCRAM-SHA-256' | string; } export interface SSLOptions { - // Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + /** + * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + */ ciphers?: string; - // Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + /** + * Passed directly through to tls.createSecureContext. See https://nodejs.org/dist/latest-v9.x/docs/api/tls.html#tls_tls_createsecurecontext_options for more info. + */ ecdhCurve?: string; - // Default:5; Number of connections for each server instance + /** + * Default:5; Number of connections for each server instance + */ poolSize?: number; - // If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + /** + * If present, the connection pool will be initialized with minSize connections, and will never dip below minSize connections + */ minSize?: number; - // Use ssl connection (needs to have a mongod server with ssl support) + /** + * Use ssl connection (needs to have a mongod server with ssl support) + */ ssl?: boolean; - // Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required) + /** + * Default: true; Validate mongod server certificate against ca (mongod server >=2.4 with ssl support required) + */ sslValidate?: boolean; - // Default: true; Server identity checking during SSL + /** + * Default: true; Server identity checking during SSL + */ checkServerIdentity?: boolean | Function; - // Array of valid certificates either as Buffers or Strings + /** + * Array of valid certificates either as Buffers or Strings + */ sslCA?: Array; - // SSL Certificate revocation list binary buffer + /** + * SSL Certificate revocation list binary buffer + */ sslCRL?: Array; - // SSL Certificate binary buffer + /** + * SSL Certificate binary buffer + */ sslCert?: Buffer | string; - // SSL Key file binary buffer + /** + * SSL Key file binary buffer + */ sslKey?: Buffer | string; - // SSL Certificate pass phrase + /** + * SSL Certificate pass phrase + */ sslPass?: Buffer | string; - // String containing the server name requested via TLS SNI. + /** + * String containing the server name requested via TLS SNI. + */ servername?: string; } export interface HighAvailabilityOptions { - // Default: true; Turn on high availability monitoring. + /** + * Default: true; Turn on high availability monitoring. + */ ha?: boolean; - // Default: 10000; The High availability period for replicaset inquiry + /** + * Default: 10000; The High availability period for replicaset inquiry + */ haInterval?: number; - // Default: false; + /** + * Default: false; + */ domainsEnabled?: boolean; } @@ -298,7 +361,12 @@ export class ReadPreference { constructor(mode: string, tags: Object); mode: string; tags: any; - options: { maxStalenessSeconds?: number }; // Max Secondary Read Stalleness in Seconds + options: { + /** + * Max Secondary Read Stalleness in Seconds + */ + maxStalenessSeconds?: number + }; static PRIMARY: string; static PRIMARY_PREFERRED: string; static SECONDARY: string; @@ -310,86 +378,156 @@ export class ReadPreference { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html */ export interface DbCreateOptions extends CommonOptions { - // If the database authentication is dependent on another databaseName. + /** + * If the database authentication is dependent on another databaseName. + */ authSource?: string; - // Default: false; Force server to create _id fields instead of client. + /** + * Default: false; Force server to create _id fields instead of client. + */ forceServerObjectId?: boolean; - // Default: false; Use c++ bson parser. + /** + * Default: false; Use c++ bson parser. + */ native_parser?: boolean; - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - // Specify if the BSON serializer should ignore undefined fields. + /** + * Specify if the BSON serializer should ignore undefined fields. + */ ignoreUndefined?: boolean; - // Return document results as raw BSON buffers. + /** + * Return document results as raw BSON buffers. + */ raw?: boolean; - // Default: true; Promotes Long values to number if they fit inside the 53 bits resolution. + /** + * Default: true; Promotes Long values to number if they fit inside the 53 bits resolution. + */ promoteLongs?: boolean; - // Default: false; Promotes Binary BSON values to native Node Buffers + /** + * Default: false; Promotes Binary BSON values to native Node Buffers + */ promoteBuffers?: boolean; - // the prefered read preference. use 'ReadPreference' class. + /** + * the prefered read preference. use 'ReadPreference' class. + */ readPreference?: ReadPreference | string; - // Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. + /** + * Default: true; Promotes BSON values to native types where possible, set to false to only receive wrapper types. + */ promoteValues?: Object; - // Custom primary key factory to generate _id values (see Custom primary keys). + /** + * Custom primary key factory to generate _id values (see Custom primary keys). + */ pkFactory?: Object; - // ES6 compatible promise constructor + /** + * ES6 compatible promise constructor + */ promiseLibrary?: Object; - /** https://docs.mongodb.com/manual/reference/read-concern/#read-concern */ + /** + * https://docs.mongodb.com/manual/reference/read-concern/#read-concern + **/ readConcern?: ReadConcern; - // Sets a cap on how many operations the driver will buffer up before giving up on getting a - // working connection, default is -1 which is unlimited. + /** + * Sets a cap on how many operations the driver will buffer up before giving up on getting a + * working connection, default is -1 which is unlimited. + */ bufferMaxEntries?: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */ export interface SocketOptions { - // Reconnect on error. default:false + /** + * Reconnect on error. default:false + */ autoReconnect?: boolean; - // TCP Socket NoDelay option. default:true + /** + * TCP Socket NoDelay option. default:true + */ noDelay?: boolean; - // TCP KeepAlive enabled on the socket. default:true + /** + * TCP KeepAlive enabled on the socket. default:true + */ keepAlive?: boolean; - // TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + /** + * TCP KeepAlive initial delay before sending first keep-alive packet when idle. default:300000 + */ keepAliveInitialDelay?: number; - // TCP Connection timeout setting. default 0 + /** + * TCP Connection timeout setting. default 0 + */ connectTimeoutMS?: number; - // Version of IP stack. Can be 4, 6 or null. default: null. - // If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure - // refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + /** + * Version of IP stack. Can be 4, 6 or null. default: null. + * + * If null, will attempt to connect with IPv6, and will fall back to IPv4 on failure + * refer to http://mongodb.github.io/node-mongodb-native/3.1/api/MongoClient.html + */ family?: 4 | 6 | null; - // TCP Socket timeout setting. default 0 + /** + * TCP Socket timeout setting. default 0 + */ socketTimeoutMS?: number; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html */ export interface ServerOptions extends SSLOptions { - // Default: 30; + /** + * Default: 30; + */ reconnectTries?: number; - // Default: 1000; + /** + * Default: 1000; + */ reconnectInterval?: number; - // Default: true; + /** + * Default: true; + */ monitoring?: boolean + + /** + * Socket Options + */ socketOptions?: SocketOptions; - // Default: 10000; The High availability period for replicaset inquiry + + /** + * Default: 10000; The High availability period for replicaset inquiry + */ haInterval?: number; - // Default: false; + /** + * Default: false; + */ domainsEnabled?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html */ export interface MongosOptions extends SSLOptions, HighAvailabilityOptions { - // Default: 15; Cutoff latency point in MS for MongoS proxy selection + /** + * Default: 15; Cutoff latency point in MS for MongoS proxy selection + */ acceptableLatencyMS?: number; + + /** + * Socket Options + */ socketOptions?: SocketOptions; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html */ export interface ReplSetOptions extends SSLOptions, HighAvailabilityOptions { - // The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + /** + * The max staleness to secondary reads (values under 10 seconds cannot be guaranteed); + */ maxStalenessSeconds?: number; - // The name of the replicaset to connect to. + /** + * The name of the replicaset to connect to. + */ replicaSet?: string; - // Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + /** + * Default: 15 ; Range of servers to pick when using NEAREST (lowest ping ms + the latency fence, ex: range of 1 to (1 + 15) ms) + */ secondaryAcceptableLatencyMS?: number; connectWithNoPrimary?: boolean; socketOptions?: SocketOptions; @@ -449,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; @@ -481,28 +619,40 @@ export interface CommonOptions extends WriteConcern { session?: ClientSession; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Server.html + */ export class Server extends EventEmitter { constructor(host: string, port: number, options?: ServerOptions); connections(): Array; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html + */ export class ReplSet extends EventEmitter { constructor(servers: Array, options?: ReplSetOptions); connections(): Array; } -// Deprecated http://mongodb.github.io/node-mongodb-native/3.1/api/ReplSet.html +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Mongos.html + */ export class Mongos extends EventEmitter { constructor(servers: Array, options?: MongosOptions); connections(): Array; } -/** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser */ +/** + * @deprecated + * @see http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#addUser + */ export interface DbAddUserOptions extends CommonOptions { customData?: Object; roles?: Object[]; @@ -527,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 */ @@ -542,29 +692,50 @@ export interface DbCollectionOptions extends CommonOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Db.html#createIndex */ export interface IndexOptions extends CommonOptions { - // Creates an unique index. + /** + * Creates an unique index. + */ unique?: boolean; - // Creates a sparse index. + /** + * Creates a sparse index. + */ sparse?: boolean; - // Creates the index in the background, yielding whenever possible. + /** + * Creates the index in the background, yielding whenever possible. + */ background?: boolean; - // A unique index cannot be created on a key that has pre-existing duplicate values. - // If you would like to create the index anyway, keeping the first document the database indexes and - // deleting all subsequent documents that have duplicate value + /** + * A unique index cannot be created on a key that has pre-existing duplicate values. + * + * If you would like to create the index anyway, keeping the first document the database indexes and + * deleting all subsequent documents that have duplicate value + */ dropDups?: boolean; - // For geo spatial indexes set the lower bound for the co-ordinates. + /** + * For geo spatial indexes set the lower bound for the co-ordinates. + */ min?: number; - // For geo spatial indexes set the high bound for the co-ordinates. + /** + * For geo spatial indexes set the high bound for the co-ordinates. + */ max?: number; - // Specify the format version of the indexes. + /** + * Specify the format version of the indexes. + */ v?: number; - // Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + /** + * Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher) + */ expireAfterSeconds?: number; - // Override the auto generated index name (useful if the resulting name is larger than 128 bytes) + /** + * Override the auto generated index name (useful if the resulting name is larger than 128 bytes) + */ name?: string; - // Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + /** + * Creates a partial index based on the given filter object (MongoDB 3.2 or higher) + */ partialFilterExpression?: any; - collation?: Object; + collation?: CollationDocument; default_language?: string } @@ -618,17 +789,27 @@ export interface FSyncOptions extends CommonOptions { fsync?: boolean } -// Documentation : http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html */ export interface Collection { - // Get the collection name. + /** + * Get the collection name. + */ collectionName: string; - // Get the full collection namespace. + /** + * Get the full collection namespace. + */ namespace: string; - // The current write concern values. + /** + * The current write concern values. + */ writeConcern: any; - // The current read concern values. + /** + * The current read concern values. + */ readConcern: ReadConcern; - // Get current index hint for collection. + /** + * Get current index hint for collection. + */ hint: any; /** http://mongodb.github.io/node-mongodb-native/3.0/api/Collection.html#aggregate */ aggregate(callback: MongoCallback>): AggregationCursor; @@ -656,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; @@ -705,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?: FindOneAndReplaceOption): Promise>; - findOneAndUpdate(filter: FilterQuery, update: Object, options: FindOneAndReplaceOption, 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; @@ -803,107 +984,146 @@ export interface Collection { /** @deprecated use updateOne, updateMany or bulkWrite */ update(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; /** @deprecated use updateOne, updateMany or bulkWrite */ - update(filter: FilterQuery, update: UpdateQuery | TSchema, options?: ReplaceOneOptions & { multi?: boolean }): Promise; + update(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions & { multi?: boolean }): Promise; /** @deprecated use updateOne, updateMany or bulkWrite */ - update(filter: FilterQuery, update: UpdateQuery | TSchema, options: ReplaceOneOptions & { multi?: boolean }, callback: MongoCallback): void; + update(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions & { multi?: boolean }, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; - updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options?: CommonOptions & { upsert?: boolean }): Promise; - updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options: CommonOptions & { upsert?: boolean }, callback: MongoCallback): void; + updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateManyOptions): Promise; + updateMany(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateManyOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, callback: MongoCallback): void; - updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: ReplaceOneOptions): Promise; - updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: ReplaceOneOptions, callback: MongoCallback): void; + updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options?: UpdateOneOptions): Promise; + updateOne(filter: FilterQuery, update: UpdateQuery | TSchema, options: UpdateOneOptions, callback: MongoCallback): void; /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#watch */ watch(pipeline?: Object[], options?: ChangeStreamOptions & { startAtClusterTime?: Timestamp, session?: ClientSession }): ChangeStream; } +type Condition = { + $eq?: T[P]; + $gt?: T[P]; + $gte?: T[P]; + $in?: T[P][]; + $lt?: T[P]; + $lte?: T[P]; + $ne?: T[P]; + $nin?: T[P][]; + $and?: (FilterQuery | T[P])[]; + $or?: (FilterQuery | T[P])[]; + $not?: (FilterQuery | T[P])[] | T[P]; + $expr?: any; + $jsonSchema?: any; + $mod?: [number, number]; + $regex?: RegExp; + $options?: string; + $text?: { + $search: string; + $language?: string; + $caseSensitive?: boolean; + $diacraticSensitive?: boolean; + }; + $where: Object; + $geoIntersects?: Object; + $geoWithin?: Object; + $near?: Object; + $nearSphere?: Object; + $elemMatch?: Object; + $size?: number; + $bitsAllClear?: Object; + $bitsAllSet?: Object; + $bitsAnyClear?: Object; + $bitsAnySet?: Object; + [key: string]: any; +}; + /** https://docs.mongodb.com/manual/reference/operator/update */ export type UpdateQuery = { - $inc: { [P in keyof T]?: number } | { [key: string]: number }, - $min: { [P in keyof T]?: number } | { [key: string]: number }, - $max: { [P in keyof T]?: number } | { [key: string]: number }, - $mul: { [P in keyof T]?: number } | { [key: string]: number }, - $set: Partial | { [key: string]: any }, - $setOnInsert: Partial | { [key: string]: any }, - $unset: { [P in keyof T]?: '' } | { [key: string]: '' }, - $rename: { [key: string]: keyof T } | { [key: string]: string }, - $currentDate: { [P in keyof T]?: (true | { $type: 'timestamp' }) } | { [key: string]: (true | { $type: 'timestamp' }) }, + $inc?: { [P in keyof T]?: number } | { [key: string]: number }; + $min?: { [P in keyof T]?: number } | { [key: string]: number }; + $max?: { [P in keyof T]?: number } | { [key: string]: number }; + $mul?: { [P in keyof T]?: number } | { [key: string]: number }; + $set?: Partial | { [key: string]: any }; + $setOnInsert?: Partial | { [key: string]: any }; + $unset?: { [P in keyof T]?: '' } | { [key: string]: '' }; + $rename?: { [key: string]: keyof T } | { [key: string]: string }; + $currentDate?: { [P in keyof T]?: (true | { $type: 'date' | 'timestamp' }) } | { [key: string]: (true | { $type: 'date' | 'timestamp' }) }; + $addToSet?: Partial | { [key: string]: any }; + $pop?: { [P in keyof T]?: -1 | 1 } | { [key: string]: -1 | 1 }; + $pull?: Partial | { [key: string]: Condition }; + $push?: Partial | { [key: string]: any }; + $pushAll?: Partial | { [key: string]: Array }; + $each?: Partial | { [key: string]: Array }; + $bit?: { [P in keyof T]?: any } | { [key: string]: any }; }; export type FilterQuery = { - [P in keyof T]?: T[P] | { - $eq?: T[P]; - $gt?: T[P]; - $gte?: T[P]; - $in?: T[P][]; - $lt?: T[P]; - $lte?: T[P]; - $ne?: T[P]; - $nin?: T[P][]; - $and?: (FilterQuery | T[P])[]; - $or?: (FilterQuery | T[P])[]; - $not?: (FilterQuery | T[P])[] | T[P]; - $expr?: any; - $jsonSchema?: any; - $mod?: [number, number]; - $regex?: RegExp; - $options?: string; - $text?: { - $search: string; - $language?: string; - $caseSensitive?: boolean; - $diacraticSensitive?: boolean; - }; - $where: Object; - $geoIntersects?: Object; - $geoWithin?: Object; - $near?: Object; - $nearSphere?: Object; - $elemMatch?: Object; - $size?: number; - $bitsAllClear?: Object; - $bitsAllSet?: Object; - $bitsAnyClear?: Object; - $bitsAnySet?: Object; - [key: string]: any; - }; + [P in keyof T]?: T[P] | Condition; } | { [key: string]: any }; -// Documentation: http://docs.mongodb.org/manual/reference/command/collStats/ +/** http://docs.mongodb.org/manual/reference/command/collStats/ */ export interface CollStats { - // Namespace. + /** + * Namespace. + */ ns: string; - // Number of documents. + /** + * Number of documents. + */ count: number; - // Collection size in bytes. + /** + * Collection size in bytes. + */ size: number; - // Average object size in bytes. + /** + * Average object size in bytes. + */ avgObjSize: number; - // (Pre)allocated space for the collection in bytes. + /** + * (Pre)allocated space for the collection in bytes. + */ storageSize: number; - // Number of extents (contiguously allocated chunks of datafile space). + /** + * Number of extents (contiguously allocated chunks of datafile space). + */ numExtents: number; - // Number of indexes. + /** + * Number of indexes. + */ nindexes: number; - // Size of the most recently created extent in bytes. + /** + * Size of the most recently created extent in bytes. + */ lastExtentSize: number; - // Padding can speed up updates if documents grow. + /** + * Padding can speed up updates if documents grow. + */ paddingFactor: number; - // A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine. + /** + * A number that indicates the user-set flags on the collection. userFlags only appears when using the mmapv1 storage engine. + */ userFlags?: number; - // Total index size in bytes. + /** + * Total index size in bytes. + */ totalIndexSize: number; - // Size of specific indexes in bytes. + /** + * Size of specific indexes in bytes. + */ indexSizes: { _id_: number; [index: string]: number; }; - // `true` if the collection is capped. + /** + * `true` if the collection is capped. + */ capped: boolean; - // The maximum number of documents that may be present in a capped collection. + /** + * The maximum number of documents that may be present in a capped collection. + */ max: number; - // The maximum size of a capped collection. + /** + * The maximum size of a capped collection. + */ maxSize: number; wiredTiger?: WiredTigerData; indexDetails?: any; @@ -1049,24 +1269,35 @@ export interface WiredTigerData { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#aggregate */ export interface CollectionAggregationOptions { readPreference?: ReadPreference | string; - // Return the query as cursor, on 2.6 > it returns as a real cursor - // on pre 2.6 it returns as an emulated cursor. + /** + * Return the query as cursor, on 2.6 > it returns as a real cursor + * on pre 2.6 it returns as an emulated cursor. + */ cursor?: { batchSize?: number }; - // Explain returns the aggregation execution plan (requires mongodb 2.6 >). + /** + * Explain returns the aggregation execution plan (requires mongodb 2.6 >). + */ explain?: boolean; - // lets the server know if it can use disk to store - // temporary results for the aggregation (requires mongodb 2.6 >). + /** + * Lets the server know if it can use disk to store + * temporary results for the aggregation (requires mongodb 2.6 >). + */ allowDiskUse?: boolean; - // specifies a cumulative time limit in milliseconds for processing operations - // on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + /** + * specifies a cumulative time limit in milliseconds for processing operations + * on the cursor. MongoDB interrupts the operation at the earliest following interrupt point. + */ maxTimeMS?: number; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * 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; @@ -1074,23 +1305,37 @@ export interface CollectionAggregationOptions { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertMany */ export interface CollectionInsertManyOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - //Force server to assign _id values instead of driver. + /** + * Force server to assign _id values instead of driver. + */ forceServerObjectId?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * Allow driver to bypass schema validation in MongoDB 3.2 or higher. + */ bypassDocumentValidation?: boolean; - // If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + /** + * If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails. + */ ordered?: boolean; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#bulkWrite */ export interface CollectionBulkWriteOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; - // Execute write operation in ordered or unordered fashion. + /** + * Execute write operation in ordered or unordered fashion. + */ ordered?: boolean; - // Allow driver to bypass schema validation in MongoDB 3.2 or higher. + /** + * Allow driver to bypass schema validation in MongoDB 3.2 or higher. + */ bypassDocumentValidation?: boolean; //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; @@ -1110,13 +1355,21 @@ export interface BulkWriteOpResultObject { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#count */ export interface MongoCountPreferences { - // The limit of documents to count. + /** + * The limit of documents to count. + */ limit?: number; - // The number of documents to skip for the count. + /** + * The number of documents to skip for the count. + */ skip?: boolean; - // An index name hint for the query. + /** + * An index name hint for the query. + */ hint?: string; - // The preferred read preference + /** + * The preferred read preference + */ readPreference?: ReadPreference | string; maxTimeMS?: number; session?: ClientSession; @@ -1148,13 +1401,17 @@ export interface FindAndModifyWriteOpResultObject { } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndReplace */ -export interface FindOneAndReplaceOption { +export interface FindOneAndReplaceOption extends CommonOptions { projection?: Object; sort?: Object; maxTimeMS?: number; upsert?: boolean; returnOriginal?: boolean; - session?: ClientSession; +} + +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#findOneAndUpdate */ +export interface FindOneAndUpdateOption extends FindOneAndReplaceOption { + arrayFilters?: Object[]; } /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#geoHaystackSearch */ @@ -1278,7 +1535,10 @@ export interface FindOneOptions { limit?: number; sort?: Array | Object; projection?: Object; - fields?: Object; // Deprecated Use options.projection instead + /** + * @deprecated Use options.projection instead + */ + fields?: Object; skip?: number; hint?: Object; explain?: boolean; @@ -1299,7 +1559,7 @@ export interface FindOneOptions { readPreference?: ReadPreference | string; partial?: boolean; maxTimeMs?: number; - collation?: Object; + collation?: CollationDocument; session?: ClientSession; } @@ -1314,7 +1574,9 @@ export interface InsertWriteOpResult { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne */ export interface CollectionInsertOneOptions extends CommonOptions { - // Serialize functions on any object. + /** + * Serialize functions on any object. + */ serializeFunctions?: boolean; //Force server to assign _id values instead of driver. forceServerObjectId?: boolean; @@ -1346,6 +1608,17 @@ export interface ReplaceOneOptions extends CommonOptions { bypassDocumentValidation?: boolean; } +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateOne */ +export interface UpdateOneOptions extends ReplaceOneOptions { + arrayFilters?: Object[]; +} + +/** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#updateMany */ +export interface UpdateManyOptions extends CommonOptions { + upsert?: boolean; + arrayFilters?: Object[]; +} + /** http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~updateWriteOpResult */ export interface UpdateWriteOpResult { result: { ok: number, n: number, nModified: number }; @@ -1407,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 */ @@ -1553,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 */ @@ -1658,17 +1937,29 @@ export class GridFSBucketWriteStream extends Writable { /** https://mongodb.github.io/node-mongodb-native/3.1/api/GridFSBucketWriteStream.html */ export interface GridFSBucketWriteStreamOptions { - /** Custom file id for the GridFS file. */ + /** + * Custom file id for the GridFS file. + **/ id?: GridFSBucketWriteStreamId, - /** The chunk size to use, in bytes */ + /** + * The chunk size to use, in bytes + */ chunkSizeBytes?: number, - /** The write concern */ + /** + * The write concern + */ w?: number, - /** The write concern timeout */ + /** + * The write concern timeout + */ wtimeout?: number, - /** The journal write concern */ + /** + * The journal write concern + */ j?: number - /** Default false; If true, disables adding an md5 field to file data */ + /** + * Default false; If true, disables adding an md5 field to file data + */ disableMD5?: boolean } @@ -1700,15 +1991,21 @@ export interface ChangeStreamOptions { maxAwaitTimeMS?: number; resumeAfter?: Object; batchSize?: number; - collation?: Object; + collation?: CollationDocument; readPreference?: ReadPreference; } type GridFSBucketWriteStreamId = string | number | Object | ObjectID; export interface LoggerOptions { - loggerLevel?: string // Custom logger function - logger?: log // Override default global log level. + /** + * Custom logger function + */ + loggerLevel?: string + /** + * Override default global log level. + */ + logger?: log } export type log = (message?: string, state?: LoggerState) => void @@ -1724,30 +2021,90 @@ export interface LoggerState { /** http://mongodb.github.io/node-mongodb-native/3.1/api/Logger.html */ export class Logger { constructor(className: string, options?: LoggerOptions) - // Log a message at the debug level + /** + * Log a message at the debug level + */ debug(message: string, state: LoggerState): void - // Log a message at the warn level + /** + * Log a message at the warn level + */ warn(message: string, state: LoggerState): void - // Log a message at the info level + /** + * Log a message at the info level + */ info(message: string, state: LoggerState): void - // Log a message at the error level + /** + * Log a message at the error level + */ error(message: string, state: LoggerState): void - // Is the logger set at info level + /** + * Is the logger set at info level + */ isInfo(): boolean - // Is the logger set at error level + /** + * Is the logger set at error level + */ isError(): boolean - // Is the logger set at error level + /** + * Is the logger set at error level + */ isWarn(): boolean - // Is the logger set at debug level + /** + * Is the logger set at debug level + */ isDebug(): boolean - // Resets the logger to default settings, error and no filtered classes + /** + * Resets the logger to default settings, error and no filtered classes + */ static reset(): void - // Get the current logger function + /** + * Get the current logger function + */ static currentLogger(): log //Set the current logger function static setCurrentLogger(log: log): void - // Set what classes to log. + /** + * Set what classes to log. + */ static filter(type: string, values: string[]): void - // Set the current log level + /** + * Set the current log level + */ 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/mongodb/mongodb-tests.ts b/types/mongodb/mongodb-tests.ts index b9b4a63c8d..ea755a8eb1 100644 --- a/types/mongodb/mongodb-tests.ts +++ b/types/mongodb/mongodb-tests.ts @@ -7,6 +7,7 @@ const connectionString = 'mongodb://127.0.0.1:27017/test'; var format = require('util').format; let options: mongodb.MongoClientOptions = { authSource: ' ', + loggerLevel: 'debug', w: 1, wtimeout: 300, j: true, @@ -21,7 +22,6 @@ let options: mongodb.MongoClientOptions = { reconnectTries: 123456, reconnectInterval: 123456, - ssl: true, sslValidate: false, checkServerIdentity: function () { }, @@ -31,12 +31,14 @@ let options: mongodb.MongoClientOptions = { sslKey: new Buffer(999), sslPass: new Buffer(999), promoteBuffers: false, - useNewUrlParser: false + useNewUrlParser: false, + authMechanism: 'SCRAM-SHA-1', + forceServerObjectId: false } MongoClient.connect(connectionString, options, function (err: mongodb.MongoError, client: mongodb.MongoClient) { if (err) throw err; const db = client.db('test'); - + var collection = db.collection('test_insert'); collection.insertOne({ a: 2 }, function (err: mongodb.MongoError, docs: any) { @@ -263,11 +265,11 @@ async function transfer(client: mongodb.MongoClient, from: any, to: any, amount: // `session.abortTransaction()` will undo the above `findOneAndUpdate()` throw new Error('Insufficient funds: ' + (A.balance + amount)); } - + const B = await db.collection('Account'). findOneAndUpdate({ name: to }, { $inc: { balance: amount } }, opts). then(res => res.value); - + await session.commitTransaction(); session.endSession(); return { from: A, to: B }; @@ -287,3 +289,4 @@ mongodb.connect(connectionString).then((client) => { ); }); + diff --git a/types/mongoose-paginate/mongoose-paginate-tests.ts b/types/mongoose-paginate/mongoose-paginate-tests.ts index 320077bc3a..d55f8a454e 100644 --- a/types/mongoose-paginate/mongoose-paginate-tests.ts +++ b/types/mongoose-paginate/mongoose-paginate-tests.ts @@ -40,7 +40,7 @@ let router: Router = Router(); router.get('/users.json', function(req: Request, res: Response) { let descending: boolean = true; - let options: PaginateOptions = {}; + let options: PaginateOptions = {} as PaginateOptions; options.select = 'email username'; options.sort = { 'username': (descending ? -1 : 1) }; options.populate = ''; diff --git a/types/mongoose/index.d.ts b/types/mongoose/index.d.ts index a296234559..83aaa33b2b 100644 --- a/types/mongoose/index.d.ts +++ b/types/mongoose/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mongoose 5.2.13 +// Type definitions for Mongoose 5.3.4 // Project: http://mongoosejs.com/ // Definitions by: horiuchi // sindrenm @@ -12,6 +12,10 @@ // alfirin // Idan Dardikman // Dominik Heigl +// Fazendaaa +// Norman Perrin +// Dan Manastireanu +// stablio // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -276,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[]; @@ -389,6 +403,8 @@ declare module "mongoose" { useNewUrlParser?: boolean; /** Set to false to make findOneAndUpdate() and findOneAndRemove() use native findOneAndUpdate() rather than findAndModify(). */ useFindAndModify?: boolean; + /** If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). */ + useCreateIndex?: boolean; // TODO safe?: any; @@ -407,11 +423,6 @@ declare module "mongoose" { * models associated with this connection. */ autoIndex?: boolean; - - /** - * If true, this connection will use createIndex() instead of ensureIndex() for automatic index builds via Model.init(). - */ - useCreateIndex?: boolean; }; } @@ -478,15 +489,6 @@ declare module "mongoose" { static STATES: any; } - /* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ - class ValidationError extends Error { - /** Console.log helper */ - toString(): string; - } - /* * section error.js * http://mongoosejs.com/docs/api.html#error-js @@ -511,6 +513,143 @@ declare module "mongoose" { /** For backwards compatibility. Same as mongoose.Error.messages */ static Messages: any; + + } + + module Error { + + /** + * 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 + * conditions that mongoose passed to `update()` when trying to update + * the document. + */ + export class DocumentNotFoundError extends Error { + } + + /** + * 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. + */ + export class CastError extends Error { + stringValue: string; + kind: string; + path: string; + value: any; + reason?: any; + model?: any; + + constructor(type: string, value: any, path: string, reason?: NativeError); + + setModel(model: any): void; + } + + /** + * 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 { + errors: any; + + constructor(instance: MongooseDocument); + + /** Console.log helper */ + toString(): string; + + inspect(): object; + + toJSON(): object; + + addError(path: string, error: any): void; + } + + /** + * 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 { + properties: any; + kind: string; + path: string; + value: any; + reason: any; + + constructor(properties: any); + + formatMessage(msg: string | Function, properties: any): string; + + toString(): string; + } + + /** + * 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. + */ + export class VersionError extends Error { + version: any; + modifiedPaths: Array; + + constructor(doc: MongooseDocument, currentVersion: any, modifiedPaths: any); + } + + /** + * 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. + */ + export class ParallelSaveError extends Error { + constructor(doc: MongooseDocument); + } + + /** + * 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). + */ + export class OverwriteModelError extends Error { + constructor(name: string); + } + + /** + * 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 { + constructor(name: string); + } + + /** + * 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. + */ + export class DivergentArrayError extends Error { + constructor(paths: Array); + } } interface EachAsyncOptions { @@ -682,11 +821,11 @@ declare module "mongoose" { * @param fn callback */ post(method: string, fn: ( - error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void + doc: T, next: (err?: NativeError) => void ) => void): this; post(method: string, fn: ( - doc: T, next: (err?: NativeError) => void + error: mongodb.MongoError, doc: T, next: (err?: NativeError) => void ) => void): this; /** @@ -868,6 +1007,7 @@ declare module "mongoose" { /** controls document#toObject behavior when called manually - defaults to true */ minimize?: boolean; read?: string; + writeConcern?: WriteConcern; /** defaults to true. */ safe?: boolean | { w?: number | string; wtimeout?: number; j?: boolean }; @@ -1118,7 +1258,7 @@ declare module "mongoose" { * Takes a populated field and returns it to its unpopulated state. * If the path was not populated, this is a no-op. */ - depopulate(path: string): this; + depopulate(path?: string): this; /** * Returns true if the Document stores the same data as doc. @@ -1165,7 +1305,7 @@ declare module "mongoose" { * @param kind optional kind property for the error * @returns the current ValidationError, with all currently invalidated paths */ - invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): ValidationError | boolean; + invalidate(path: string, errorMsg: string | NativeError, value: any, kind?: string): Error.ValidationError | boolean; /** Returns true if path was directly set and modified, else false. */ isDirectModified(path: string): boolean; @@ -1553,7 +1693,7 @@ declare module "mongoose" { * been using Query, we set it as an alias of DocumentQuery. */ class Query extends DocumentQuery { } - class DocumentQuery extends mquery { + class DocumentQuery extends mquery { /** * Specifies a javascript function or expression to pass to MongoDBs query system. * Only use $where when you have a condition that cannot be met using other MongoDB @@ -1633,8 +1773,8 @@ declare module "mongoose" { * Specifying this query as a count query. Passing a callback executes the query. * @param criteria mongodb selector */ - count(callback?: (err: any, count: number) => void): Query; - count(criteria: any, callback?: (err: any, count: number) => void): Query; + count(callback?: (err: any, count: number) => void): Query & QueryHelpers; + count(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Specifies this query as a `countDocuments()` query. Behaves like `count()`, @@ -1655,8 +1795,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -1668,8 +1808,8 @@ declare module "mongoose" { * @param {Function} [callback] optional params are (error, count) * @return {Query} this */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Returns a wrapper around a mongodb driver cursor. A QueryCursor exposes a @@ -1678,10 +1818,10 @@ declare module "mongoose" { cursor(options?: any): QueryCursor; /** Declares or executes a distict() operation. Passing a callback executes the query. */ - distinct(callback?: (err: any, res: any[]) => void): Query; - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(callback?: (err: any, res: any[]) => void): Query & QueryHelpers; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, criteria: any | Query, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** Specifies an $elemMatch condition */ elemMatch(criteria: (elem: Query) => void): this; @@ -1690,7 +1830,7 @@ declare module "mongoose" { elemMatch(path: string | any | Function, criteria: any): this; /** Specifies the complementary comparison value for paths specified with where() */ - equals(val: any): this; + equals(val: T): this; /** Executes the query */ exec(callback?: (err: any, res: T) => void): Promise; @@ -1705,9 +1845,9 @@ declare module "mongoose" { * query is executed, the result will be an array of documents. * @param criteria mongodb selector */ - find(callback?: (err: any, res: DocType[]) => void): DocumentQuery; + find(callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; find(criteria: any, - callback?: (err: any, res: DocType[]) => void): DocumentQuery; + callback?: (err: any, res: DocType[]) => void): DocumentQuery & QueryHelpers; /** * Declares the query a findOne operation. When executed, the first found document is @@ -1716,36 +1856,36 @@ declare module "mongoose" { * @param criteria mongodb selector * @param projection optional fields to return */ - findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery; + findOne(callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; findOne(criteria: any, - callback?: (err: any, res: DocType | null) => void): DocumentQuery; + callback?: (err: any, res: DocType | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + findOneAndRemove(callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: QueryFindOneAndRemoveOptions, - callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery; + callback?: (error: any, doc: DocType | null, result: any) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. * Finds a matching document, updates it according to the update arg, passing any options, and returns * the found document (if any) to the callback. The query executes immediately if callback is passed. */ - findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery; + findOneAndUpdate(callback?: (err: any, doc: DocType | null) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: { upsert: true, new: true } & QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(query: any, update: any, options: QueryFindOneAndUpdateOptions, - callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: DocType | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Specifies a $geometry condition. geometry() must come after either intersects() or within(). @@ -1770,15 +1910,15 @@ declare module "mongoose" { * Specifies a $gt query condition. * When called with one argument, the most recent path passed to where() is used. */ - gt(val: number): this; - gt(path: string, val: number): this; + gt(val: T): this; + gt(path: string, val: T): this; /** * Specifies a $gte query condition. * When called with one argument, the most recent path passed to where() is used. */ - gte(val: number): this; - gte(path: string, val: number): this; + gte(val: T): this; + gte(path: string, val: T): this; /** * Sets query hints. @@ -1803,7 +1943,7 @@ declare module "mongoose" { * getters/setters or other Mongoose magic applied. * @param bool defaults to true */ - lean(bool?: boolean): Query; + lean(bool?: boolean): Query & QueryHelpers; /** Specifies the maximum number of documents the query will return. Cannot be used with distinct() */ limit(val: number): this; @@ -1812,15 +1952,15 @@ declare module "mongoose" { * Specifies a $lt query condition. * When called with one argument, the most recent path passed to where() is used. */ - lt(val: number): this; - lt(path: string, val: number): this; + lt(val: T): this; + lt(path: string, val: T): this; /** * Specifies a $lte query condition. * When called with one argument, the most recent path passed to where() is used. */ - lte(val: number): this; - lte(path: string, val: number): this; + lte(val: T): this; + lte(path: string, val: T): this; /** * Specifies a $maxDistance query condition. @@ -1881,6 +2021,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; @@ -1927,8 +2091,8 @@ declare module "mongoose" { * you must first call remove() and then execute it by using the exec() method. * @param criteria mongodb selector */ - remove(callback?: (err: any) => void): Query; - remove(criteria: any | Query, callback?: (err: any) => void): Query; + remove(callback?: (err: any) => void): Query & QueryHelpers; + remove(criteria: any | Query, callback?: (err: any) => void): Query & QueryHelpers; /** Specifies which document fields to include or exclude (also known as the query "projection") */ select(arg: string | any): this; @@ -2006,20 +2170,20 @@ declare module "mongoose" { * Converts this query to a customized, reusable query * constructor with all arguments and options retained. */ - toConstructor(): new (...args: any[]) => Query; - toConstructor(): new (...args: any[]) => DocumentQuery; + toConstructor(): new (...args: any[]) => Query & QueryHelpers; + toConstructor(): new (...args: any[]) => DocumentQuery & QueryHelpers; /** * Declare and/or execute this query as an update() operation. * All paths passed that are not $atomic operations will become $set ops. * @param doc the update command */ - update(callback?: (err: any, affectedRows: number) => void): Query; - update(doc: any, callback?: (err: any, affectedRows: number) => void): Query; + update(callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; + update(doc: any, callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; update(criteria: any, doc: any, options: QueryUpdateOptions, - callback?: (err: any, affectedRows: number) => void): Query; + callback?: (err: any, affectedRows: number) => void): Query & QueryHelpers; /** Specifies a path for use with chaining. */ where(path?: string | any, val?: any): this; @@ -2605,7 +2769,7 @@ declare module "mongoose" { * http://mongoosejs.com/docs/api.html#model-js */ export var Model: Model; - interface Model extends NodeJS.EventEmitter, ModelProperties { + interface Model extends NodeJS.EventEmitter, ModelProperties { /** * Model constructor * Provides the interface to MongoDB collections as well as creates document instances. @@ -2655,11 +2819,11 @@ declare module "mongoose" { * @param projection optional fields to return */ findById(id: any | string | number, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findById(id: any | string | number, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; model(name: string): Model; @@ -2667,7 +2831,7 @@ declare module "mongoose" { * Creates a Query and specifies a $where condition. * @param argument is a javascript string or anonymous function */ - $where(argument: string | Function): DocumentQuery; + $where(argument: string | Function): DocumentQuery & QueryHelpers; /** * Performs aggregations on the models collection. @@ -2679,7 +2843,7 @@ declare module "mongoose" { aggregate(aggregations: any[], cb: Function): Promise; /** Counts number of matching documents in a database collection. */ - count(conditions: any, callback?: (err: any, count: number) => void): Query; + count(conditions: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Counts number of documents matching `criteria` in a database collection. @@ -2693,8 +2857,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - countDocuments(callback?: (err: any, count: number) => void): Query; - countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query; + countDocuments(callback?: (err: any, count: number) => void): Query & QueryHelpers; + countDocuments(criteria: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Estimates the number of documents in the MongoDB collection. Faster than @@ -2706,8 +2870,8 @@ declare module "mongoose" { * @param {Function} [callback] * @return {Query} */ - estimatedDocumentCount(callback?: (err: any, count: number) => void): Query; - estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query; + estimatedDocumentCount(callback?: (err: any, count: number) => void): Query & QueryHelpers; + estimatedDocumentCount(options: any, callback?: (err: any, count: number) => void): Query & QueryHelpers; /** * Shortcut for saving one or more documents to the database. MyModel.create(docs) @@ -2727,9 +2891,9 @@ declare module "mongoose" { discriminator(name: string, schema: Schema): Model; /** Creates a Query for a distinct operation. Passing a callback immediately executes the query. */ - distinct(field: string, callback?: (err: any, res: any[]) => void): Query; + distinct(field: string, callback?: (err: any, res: any[]) => void): Query & QueryHelpers; distinct(field: string, conditions: any, - callback?: (err: any, res: any[]) => void): Query; + callback?: (err: any, res: any[]) => void): Query & QueryHelpers; /** * Sends ensureIndex commands to mongo for each index declared in the schema. @@ -2749,12 +2913,12 @@ declare module "mongoose" { * Finds documents. * @param projection optional fields to return */ - find(callback?: (err: any, res: T[]) => void): DocumentQuery; - find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery; + find(callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; + find(conditions: any, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; find(conditions: any, projection?: any | null, options?: any | null, - callback?: (err: any, res: T[]) => void): DocumentQuery; + callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; @@ -2765,15 +2929,15 @@ declare module "mongoose" { * Executes immediately if callback is passed, else a Query object is returned. * @param id value of _id to query by */ - findByIdAndRemove(): DocumentQuery; + findByIdAndRemove(): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndRemove(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** @@ -2785,28 +2949,28 @@ declare module "mongoose" { */ findByIdAndDelete(): DocumentQuery; findByIdAndDelete(id: any | number | string, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndDelete(id: any | number | string, options: { /** if multiple docs are found by the conditions, sets the sort order to choose which doc to update */ sort?: any; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) * is equivalent to findOneAndUpdate({ _id: id }, ...). * @param id value of _id to query by */ - findByIdAndUpdate(): DocumentQuery; + findByIdAndUpdate(): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: { upsert: true, new: true } & ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T) => void): DocumentQuery; + callback?: (err: any, res: T) => void): DocumentQuery & QueryHelpers; findByIdAndUpdate(id: any | number | string, update: any, options: ModelFindByIdAndUpdateOptions, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Finds one document. @@ -2814,20 +2978,20 @@ declare module "mongoose" { * @param projection optional fields to return */ findOne(conditions?: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOne(conditions: any, projection: any, options: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issue a mongodb findAndModify remove command. * Finds a matching document, removes it, passing the found document (if any) to the callback. * Executes immediately if callback is passed else a Query object is returned. */ - findOneAndRemove(): DocumentQuery; + findOneAndRemove(): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndRemove(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2838,16 +3002,16 @@ declare module "mongoose" { maxTimeMS?: number; /** sets the document fields to return */ select?: any; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findOneAndDelete command. * Finds a matching document, removes it, passing the found document (if any) to the * callback. Executes immediately if callback is passed. */ - findOneAndDelete(): DocumentQuery; + findOneAndDelete(): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, - callback?: (err: any, res: T | null) => void): DocumentQuery; + callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; findOneAndDelete(conditions: any, options: { /** * if multiple docs are found by the conditions, sets the sort order to choose @@ -2864,7 +3028,7 @@ declare module "mongoose" { rawResult?: boolean; /** overwrites the schema's strict mode option for this update */ strict?: boolean|string; - }, callback?: (err: any, res: T | null) => void): DocumentQuery; + }, callback?: (err: any, res: T | null) => void): DocumentQuery & QueryHelpers; /** * Issues a mongodb findAndModify update command. @@ -2872,15 +3036,15 @@ declare module "mongoose" { * and returns the found document (if any) to the callback. The query executes immediately * if callback is passed else a Query object is returned. */ - findOneAndUpdate(): DocumentQuery; + findOneAndUpdate(): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: { upsert: true, new: true } & ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T, res: any) => void): DocumentQuery & QueryHelpers; findOneAndUpdate(conditions: any, update: any, options: ModelFindOneAndUpdateOptions, - callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery; + callback?: (err: any, doc: T | null, res: any) => void): DocumentQuery & QueryHelpers; /** * Implements $geoSearch functionality for Mongoose @@ -2897,7 +3061,7 @@ declare module "mongoose" { limit?: number; /** return the raw object instead of the Mongoose Model */ lean?: boolean; - }, callback?: (err: any, res: T[]) => void): DocumentQuery; + }, callback?: (err: any, res: T[]) => void): DocumentQuery & QueryHelpers; /** * Shortcut for creating a new Document from existing raw data, @@ -2957,35 +3121,35 @@ declare module "mongoose" { callback?: (err: any, res: T) => void): Promise; /** Removes documents from the collection. */ - remove(conditions: any, callback?: (err: any) => void): Query; - deleteOne(conditions: any, callback?: (err: any) => void): Query; - deleteMany(conditions: any, callback?: (err: any) => void): Query; + remove(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteOne(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; + deleteMany(conditions: any, callback?: (err: any) => void): Query & QueryHelpers; /** * Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set). * This function triggers the following middleware: replaceOne */ - replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query; + replaceOne(conditions: any, replacement: any, callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** * Updates documents in the database without returning them. * All update values are cast to their appropriate SchemaTypes before being sent. */ update(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; update(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateOne(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; updateMany(conditions: any, doc: any, options: ModelUpdateOptions, - callback?: (err: any, raw: any) => void): Query; + callback?: (err: any, raw: any) => void): Query & QueryHelpers; /** Creates a Query, applies the passed conditions, and returns the Query. */ - where(path: string, val?: any): Query; + where(path: string, val?: any): Query & QueryHelpers; } interface Document extends MongooseDocument, NodeJS.EventEmitter, ModelProperties { diff --git a/types/mongoose/mongoose-tests.ts b/types/mongoose/mongoose-tests.ts index 20b24ba887..f4fec31101 100644 --- a/types/mongoose/mongoose-tests.ts +++ b/types/mongoose/mongoose-tests.ts @@ -22,12 +22,12 @@ const connection2: Promise = mongoose.connect(connectUri, { pass: 'housan', config: { autoIndex: true, - useCreateIndex: true, }, mongos: true, bufferCommands: false, useNewUrlParser: true, useFindAndModify: true, + useCreateIndex: true }); const connection3: null = mongoose.connect(connectUri, function (error) { error.stack; @@ -145,6 +145,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; @@ -166,17 +167,6 @@ const getDB = async (tenant: string)=> { return conn1.useDb(tenant); }; - -/* - * section error/validation.js - * http://mongoosejs.com/docs/api.html#error-validation-js - */ -var validationError = {}; -validationError.toString().toLowerCase(); -/* inherited properties */ -validationError.stack; -validationError.message; - /* * section error.js * http://mongoosejs.com/docs/api.html#error-js @@ -190,6 +180,93 @@ mongooseError.stack; mongoose.Error.messages.hasOwnProperty(''); mongoose.Error.Messages.hasOwnProperty(''); +/* + * section error/cast.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.CastError + */ +var castError: mongoose.Error.CastError = new mongoose.Error.CastError('', '', ''); +castError.setModel('foo'); +castError.stringValue; +castError.kind; +castError.path; +castError.value; +/* inherited properties */ +castError.name; +castError.stack; +castError.message; + +/* + * section error/validator.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidatorError + */ +var validatorError: mongoose.Error.ValidatorError = new mongoose.Error.ValidatorError({ foo: 'bar' }) +validatorError.properties; +validatorError.kind; +validatorError.path; +validatorError.value; +validatorError.toString().toLowerCase(); +validatorError.formatMessage('foo', {}); +validatorError.formatMessage('foo', (bar: any)=>{ return bar; }); +/* inherited properties */ +validatorError.name; +validatorError.stack; +validatorError.message; + +/* + * section error/validation.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ValidationError + */ +var doc = {}; +var validationError: mongoose.Error.ValidationError = new mongoose.Error.ValidationError(doc); +validationError.toString().toLowerCase(); +validationError.inspect(); +validationError.toJSON().hasOwnProperty(''); +validationError.addError('foo', validatorError) +/* inherited properties */ +validationError.name; +validationError.stack; +validationError.message; + +/* + * section error/parallelSave.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.ParallelSaveError + */ +var parallelSaveError: mongoose.Error.ParallelSaveError = new mongoose.Error.ParallelSaveError(doc); +/* inherited properties */ +parallelSaveError.name; +parallelSaveError.stack; +parallelSaveError.message; + +/* + * section error/overwriteModel.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.OverwriteModelError + */ +var overwriteModelError: mongoose.Error.OverwriteModelError = new mongoose.Error.OverwriteModelError('foo'); +/* inherited properties */ +overwriteModelError.name; +overwriteModelError.stack; +overwriteModelError.message; + +/* + * section error/missingSchema.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError + */ +var missingSchemaError: mongoose.Error.MissingSchemaError = new mongoose.Error.MissingSchemaError('foo'); +/* inherited properties */ +missingSchemaError.name; +missingSchemaError.stack; +missingSchemaError.message; + +/* + * section error/divergentArray.js + * https://mongoosejs.com/docs/api.html#mongooseerror_MongooseError.MissingSchemaError + */ +var missingSchemaError: mongoose.Error.DivergentArrayError = new mongoose.Error.DivergentArrayError(['foo','bar']); +/* inherited properties */ +missingSchemaError.name; +missingSchemaError.stack; +missingSchemaError.message; + const pluralize = mongoose.pluralize(); const plural: string = pluralize('foo'); @@ -415,12 +492,12 @@ preHookTestSchemaArr.push( ); schema -.post('save', function (error, doc, next) { +.post('save', function (error: mongoose.Error, doc: mongoose.Document, next: (err?: mongoose.NativeError) => void) { error.stack; doc.model; next.apply; }) -.post('save', function (doc: mongoose.Document, next: Function) { +.post('save', function (doc: mongoose.Document, next: (err?: mongoose.NativeError) => void) { doc.model; next(new Error()); }) @@ -1003,6 +1080,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) { @@ -1989,3 +2067,40 @@ db.createCollection('customers'). // visible outside of the transaction. then(() => session.commitTransaction()). then(() => Customer.findOne({ name: 'Test' }).exec()) + +/** + * https://mongoosejs.com/docs/guide.html#writeConcern + */ +new mongoose.Schema({ name: String }, { + writeConcern: { + w: 'majority', + j: true, + wtimeout: 1000 + } +}); + +/* Query helpers: https://mongoosejs.com/docs/guide.html#query-helpers */ + +interface Animal2 extends mongoose.Document { + name: string; + type: string; + tags: string[]; +} +var animal2Schema = new mongoose.Schema({ + name: String, + type: String, + tags: { type: [String], index: true } // field level +}); +let animal2QueryHelpers = { + byName>(this: Q, name: string) { + return this.where({ name: new RegExp(name, 'i') }); + } +}; +animal2Schema.query = animal2QueryHelpers; +var Animal2 = mongoose.model>('Animal', animal2Schema); +Animal2.find().byName('fido').exec(function(err, animals) { + console.log(animals); +}); +Animal2.findOne().byName('fido').exec(function(err, animal) { + console.log(animal); +}); diff --git a/types/mongoose/tslint.json b/types/mongoose/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/mongoose/tslint.json +++ b/types/mongoose/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/mongoose/v3/tslint.json b/types/mongoose/v3/tslint.json index a41bf5d19a..7d5b2a06c0 100644 --- a/types/mongoose/v3/tslint.json +++ b/types/mongoose/v3/tslint.json @@ -18,6 +18,7 @@ "member-access": false, "new-parens": false, "no-any-union": false, + "no-angle-bracket-type-assertion": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, "no-consecutive-blank-lines": false, 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/mongoose/v4/tslint.json b/types/mongoose/v4/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/mongoose/v4/tslint.json +++ b/types/mongoose/v4/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/mongration/index.d.ts b/types/mongration/index.d.ts new file mode 100644 index 0000000000..7f46f3edc3 --- /dev/null +++ b/types/mongration/index.d.ts @@ -0,0 +1,35 @@ +// Type definitions for mongration 1.0 +// Project: https://github.com/awapps/mongration#readme +// Definitions by: Anton Lobashev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Db } from 'mongodb'; + +export interface DbConfig { + hosts?: string; + db?: string; + user?: string; + password?: string; + mongoUri?: string; + migrationCollection: string; + replicaSet?: string; +} + +export interface MigrationResponse { + id: string; + status: 'not-run' | 'skipped' | 'pending' | 'ok' | 'error' | 'rollback' | 'rollback-error'; +} + +export class Migration { + constructor(dbConfig: DbConfig); + add: (paths: string | string[]) => void; + addAllFromPath: (path: string) => void; + migrate: (doneCb?: (err: Error | null, response: MigrationResponse[]) => void) => void; +} + +export interface MigrationStep { + id: string; + up: (db: Db, cb: (err?: Error) => void) => void; + down?: (db: Db, cb: (err?: Error) => void) => void; +} diff --git a/types/mongration/mongration-tests.ts b/types/mongration/mongration-tests.ts new file mode 100644 index 0000000000..735aa6436a --- /dev/null +++ b/types/mongration/mongration-tests.ts @@ -0,0 +1,28 @@ +import { Migration, DbConfig, MigrationStep } from 'mongration'; + +const dbConfig: DbConfig = { + hosts: 'localhost:27017', + db: 'testdb', + migrationCollection: 'migrationversions' +}; + +const migration = new Migration(dbConfig); +migration.add('1-add-foo.js'); +migration.add(['2-add-bar.js', '3-add-foobar.js']); +migration.addAllFromPath('migrations'); +migration.migrate((err, response) => { + if (!err) { + return response; + } +}); + +// from https://github.com/awapps/mongration#creating-migration-steps +const step: MigrationStep = { + id: '1-step', + up: (db, cb) => { + db.collection('testcolleciton').insert({ name: 'initial-setup' }, cb); + }, + down: (db, cb) => { + db.collection('testcollection').remove({ name: 'initial-setup' }, cb); + } +}; diff --git a/types/mongration/tsconfig.json b/types/mongration/tsconfig.json new file mode 100644 index 0000000000..c47e0d78b6 --- /dev/null +++ b/types/mongration/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", + "mongration-tests.ts" + ] +} diff --git a/types/mongration/tslint.json b/types/mongration/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mongration/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/moo/index.d.ts b/types/moo/index.d.ts index fa3a59d2ab..fd53f98e0a 100644 --- a/types/moo/index.d.ts +++ b/types/moo/index.d.ts @@ -104,7 +104,7 @@ export interface Token { /** * The number of line breaks found in the match. (Always zero if this rule has lineBreaks: false.) */ - lineBreaks: boolean; + lineBreaks: number; /** * The line number of the beginning of the match, starting from 1. */ diff --git a/types/mozilla-readability/index.d.ts b/types/mozilla-readability/index.d.ts index a30925fb0b..7a7c26fdb8 100644 --- a/types/mozilla-readability/index.d.ts +++ b/types/mozilla-readability/index.d.ts @@ -7,21 +7,13 @@ export = Readability; declare class Readability { - constructor(uri: Readability.Uri, doc: Document, options?: Readability.Options); + constructor(doc: Document, options?: Readability.Options); parse(): Readability.ParseResult; isProbablyReaderable(helperIsVisible?: (node: any) => boolean): boolean; } declare namespace Readability { - interface Uri { - spec: string; - host: string; - prePath: string; - scheme: string; - pathBase: string; - } - interface Options { debug?: boolean; maxElemsToParse?: number; @@ -31,7 +23,6 @@ declare namespace Readability { } interface ParseResult { - uri: Uri; title: string; byline: string; dir: string; diff --git a/types/mozilla-readability/mozilla-readability-tests.ts b/types/mozilla-readability/mozilla-readability-tests.ts index e5431dd14e..0dec719559 100644 --- a/types/mozilla-readability/mozilla-readability-tests.ts +++ b/types/mozilla-readability/mozilla-readability-tests.ts @@ -5,42 +5,25 @@ import { JSDOM } from 'jsdom'; // because issue https://github.com/mozilla/readability/issues/346 // requires global variable `Node` when using nodejs. -const fakeUri: Readability.Uri = { - spec: "http://fakehost/test/page.html", - host: "fakehost", - prePath: "http://fakehost", - scheme: "http", - pathBase: "http://fakehost/test/" -}; - function test_basic_usage() { const dom = new JSDOM(`

          Hello

          Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; - const reader = new Readability(fakeUri, dom.window.document); + const reader = new Readability(dom.window.document); const article = reader.parse(); } function test_readability_with_options() { const dom = new JSDOM(`

          Hello

          Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; const options: Readability.Options = { debug: true, maxElemsToParse: 100, }; - const article = new Readability(fakeUri, dom.window.document, options).parse(); + const article = new Readability(dom.window.document, options).parse(); } function test_is_probably_readerable() { const dom = new JSDOM(`

          Hello

          Hi!`); - // Required until https://github.com/mozilla/readability/issues/346 - // is fixed. - Node = dom.window.Node; - const isReadable = new Readability(fakeUri, dom.window.document).isProbablyReaderable(); + const isReadable = new Readability(dom.window.document).isProbablyReaderable(); } diff --git a/types/mssql/index.d.ts b/types/mssql/index.d.ts index d4558737ba..891186f7ee 100644 --- a/types/mssql/index.d.ts +++ b/types/mssql/index.d.ts @@ -316,6 +316,7 @@ export declare class PreparedStatement extends events.EventEmitter { public parameters: IRequestParameters; public stream: any; public constructor(connection?: ConnectionPool); + public constructor(transaction: Transaction); public input(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; public output(name: string, type: (() => ISqlType) | ISqlType): PreparedStatement; public prepare(statement?: string): Promise; diff --git a/types/mssql/mssql-tests.ts b/types/mssql/mssql-tests.ts index 72bbc15126..18ad4b3ad9 100644 --- a/types/mssql/mssql-tests.ts +++ b/types/mssql/mssql-tests.ts @@ -189,6 +189,16 @@ function test_request_constructor() { var request4 = new sql.Request(); } +function test_prepared_statement_constructor() { + // Request can be constructed with a connection, preparedStatment, transaction or no arguments + var connection: sql.ConnectionPool = new sql.ConnectionPool(config); + var preparedStatment = new sql.PreparedStatement(connection); + var transaction = new sql.Transaction(connection); + + var preparedSatement1 = new sql.PreparedStatement(connection); + var preparedSatement2 = new sql.PreparedStatement(transaction); +} + function test_classes_extend_eventemitter() { var connection: sql.ConnectionPool = new sql.ConnectionPool(config); var transaction = new sql.Transaction(); diff --git a/types/multer-gridfs-storage/index.d.ts b/types/multer-gridfs-storage/index.d.ts index 0a827bedcb..9e6f5efcf3 100644 --- a/types/multer-gridfs-storage/index.d.ts +++ b/types/multer-gridfs-storage/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for multer-gridfs-storage 2.0 +// Type definitions for multer-gridfs-storage 3.1 // Project: https://github.com/devconcept/multer-gridfs-storage // Definitions by: devconcept // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -7,37 +7,69 @@ import { EventEmitter } from 'events'; import { Express } from 'express'; import * as Multer from 'multer'; -import { Db } from 'mongodb'; +import { Db, MongoClient } from 'mongodb'; +import { Connection, Mongoose } from 'mongoose'; + +declare class Cache { + initialize(opts: object): object; + findUri(cacheName: string, url: string): string; + has(cacheIndex: object): boolean; + get(cacheIndex: object): object; + set(cacheIndex: object, value: object): void; + isPending(cacheIndex: object): boolean; + isOpening(cacheIndex: object): boolean; + resolve(cacheIndex: object, db: Db, client: MongoClient): void; + reject(cacheIndex: object, err: Error): void; + waitFor(cacheIndex: object): Promise; + connections(): number; + remove(cacheIndex: object): void; + clear(): void; +} interface MulterGfsOptions { file?(req: Express.Request, file: Express.Multer.File): any; } declare class MulterGridfsStorage extends EventEmitter implements Multer.StorageEngine { - constructor(settings: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.DbStorageOptions); + db: Db; + client: MongoClient; + connected: boolean; + connecting: boolean; + configuration: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.DbStorageOptions; + error: Error; + caching: boolean; + cacheName: string; + cacheIndex: object; + + constructor(configuration: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.DbStorageOptions); _handleFile(req: Express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; _removeFile(req: Express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; + + static cache: Cache; } declare namespace MulterGridfsStorage { interface UrlStorageOptions extends MulterGfsOptions { url: string; - connectionOpts?: any; + options?: any; + cache?: boolean | string; } interface DbStorageOptions extends MulterGfsOptions { - db: Promise | Db; + db: Mongoose | Connection | Db | MongoClient | Promise; } interface FileConfig { filename?: string; id?: any; - metadata?: any; + metadata?: object; chunkSize?: number; bucketName?: string; contentType?: string; + aliases?: string[]; + disableMD5?: boolean; } } diff --git a/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts index d34eaeeae6..95c466ae36 100644 --- a/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts +++ b/types/multer-gridfs-storage/multer-gridfs-storage-tests.ts @@ -1,5 +1,6 @@ import MulterGridfsStorage = require('multer-gridfs-storage'); -import { Db, MongoClient, Server } from "mongodb"; +import { Db, MongoClient, Server } from 'mongodb'; +import * as mongoose from 'mongoose'; // Exported interfaces const conf: MulterGridfsStorage.FileConfig = { @@ -9,10 +10,16 @@ const conf: MulterGridfsStorage.FileConfig = { // Connection promise const dbPromise = MongoClient.connect('mongodb://yourhost:27017/database'); +// Mongoose promise +const mongoosePromise = mongoose.connect('mongodb://yourhost:27017/database'); +const mgConnectionPromise = mongoose + .connect('mongodb://yourhost:27017/database') + .then(instance => instance.connection); const server = new Server('localhost', 27017); const db = new Db('database', server); +// Database instance const opt1: MulterGridfsStorage.DbStorageOptions = { db, file: (req, file) => { @@ -24,9 +31,31 @@ const opt1: MulterGridfsStorage.DbStorageOptions = { } }; -const opt2: MulterGridfsStorage.UrlStorageOptions = { +const dbFileStorage = new MulterGridfsStorage(opt1); + +const opt2: MulterGridfsStorage.DbStorageOptions = { + db: mongoosePromise, + file: (req, file) => { + return { + disableMd5: true + }; + } +}; + +const opt3: MulterGridfsStorage.DbStorageOptions = { + db: mgConnectionPromise, + file: (req, file) => { + return 5; + } +}; + +const mongooseStorage = new MulterGridfsStorage(opt2); +const mgConnectionStorage = new MulterGridfsStorage(opt3); + +// Url based instance +const opt4: MulterGridfsStorage.UrlStorageOptions = { url: 'mongodb://yourhost:27017/database', - connectionOpts: {}, + options: {}, file: (req, file) => { return { metadata: file.mimetype @@ -34,25 +63,30 @@ const opt2: MulterGridfsStorage.UrlStorageOptions = { } }; -// All options -const dbFileStorage = new MulterGridfsStorage(opt1); +const urlFileStorage = new MulterGridfsStorage(opt4); -const urlFileStorage = new MulterGridfsStorage(opt2); +// Cache +const opt5: MulterGridfsStorage.UrlStorageOptions = { + url: 'mongodb://yourhost:27017/database', + cache: 'cache' +}; + +const cachedStorage = new MulterGridfsStorage(opt5); // Other properties are optional -const promiseStorage = new MulterGridfsStorage({ - db: dbPromise -}); +const promiseStorage = new MulterGridfsStorage({db: dbPromise}); -const dbStorage = new MulterGridfsStorage({ - db -}); +const dbStorage = new MulterGridfsStorage({db}); const urlStorage = new MulterGridfsStorage({ url: 'mongodb://yourhost:27017/database' }); // Extends event emitter -promiseStorage.on('connection', () => {}); -urlStorage.addListener('conection', () => {}); +promiseStorage.on('connection', () => { +}); +urlStorage.addListener('conection', () => { +}); dbStorage.removeAllListeners('conection'); + +MulterGridfsStorage.cache.connections(); diff --git a/types/multer-gridfs-storage/tsconfig.json b/types/multer-gridfs-storage/tsconfig.json index 1daa734d97..4729416ff1 100644 --- a/types/multer-gridfs-storage/tsconfig.json +++ b/types/multer-gridfs-storage/tsconfig.json @@ -4,11 +4,6 @@ "lib": [ "es6" ], - "paths": { - "mongodb": [ - "mongodb/v2" - ] - }, "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/types/multer-gridfs-storage/v2/index.d.ts b/types/multer-gridfs-storage/v2/index.d.ts new file mode 100644 index 0000000000..0a827bedcb --- /dev/null +++ b/types/multer-gridfs-storage/v2/index.d.ts @@ -0,0 +1,63 @@ +// Type definitions for multer-gridfs-storage 2.0 +// Project: https://github.com/devconcept/multer-gridfs-storage +// Definitions by: devconcept +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { EventEmitter } from 'events'; +import { Express } from 'express'; +import * as Multer from 'multer'; +import { Db } from 'mongodb'; + +interface MulterGfsOptions { + file?(req: Express.Request, file: Express.Multer.File): any; +} + +declare class MulterGridfsStorage extends EventEmitter implements Multer.StorageEngine { + constructor(settings: MulterGridfsStorage.UrlStorageOptions | MulterGridfsStorage.DbStorageOptions); + + _handleFile(req: Express.Request, file: Express.Multer.File, callback: (error?: any, info?: Express.Multer.File) => void): void; + + _removeFile(req: Express.Request, file: Express.Multer.File, callback: (error: Error) => void): void; +} + +declare namespace MulterGridfsStorage { + interface UrlStorageOptions extends MulterGfsOptions { + url: string; + connectionOpts?: any; + } + + interface DbStorageOptions extends MulterGfsOptions { + db: Promise | Db; + } + + interface FileConfig { + filename?: string; + id?: any; + metadata?: any; + chunkSize?: number; + bucketName?: string; + contentType?: string; + } +} + +// Merge multer's file declaration with ours +declare global { + namespace Express { + namespace Multer { + interface File { + id: any; + filename: string; + metadata: any; + contentType: string; + chunkSize: number; + bucketName: string; + uploadDate: Date; + md5: string; + size: number; + } + } + } +} + +export = MulterGridfsStorage; diff --git a/types/multer-gridfs-storage/v2/multer-gridfs-storage-tests.ts b/types/multer-gridfs-storage/v2/multer-gridfs-storage-tests.ts new file mode 100644 index 0000000000..f904ca053e --- /dev/null +++ b/types/multer-gridfs-storage/v2/multer-gridfs-storage-tests.ts @@ -0,0 +1,58 @@ +import MulterGridfsStorage = require('multer-gridfs-storage'); +import { Db, MongoClient, Server } from "mongodb"; + +// Exported interfaces +const conf: MulterGridfsStorage.FileConfig = { + filename: 'name', + bucketName: 'plants' +}; + +// Connection promise +const dbPromise = MongoClient.connect('mongodb://yourhost:27017').then((client) => client.db('database')); + +const server = new Server('localhost', 27017); +const db = new Db('database', server); + +const opt1: MulterGridfsStorage.DbStorageOptions = { + db, + file: (req, file) => { + return new Promise((resolve) => { + resolve({ + filename: file.originalname + }); + }); + } +}; + +const opt2: MulterGridfsStorage.UrlStorageOptions = { + url: 'mongodb://yourhost:27017/database', + connectionOpts: {}, + file: (req, file) => { + return { + metadata: file.mimetype + }; + } +}; + +// All options +const dbFileStorage = new MulterGridfsStorage(opt1); + +const urlFileStorage = new MulterGridfsStorage(opt2); + +// Other properties are optional +const promiseStorage = new MulterGridfsStorage({ + db: dbPromise +}); + +const dbStorage = new MulterGridfsStorage({ + db +}); + +const urlStorage = new MulterGridfsStorage({ + url: 'mongodb://yourhost:27017/database' +}); + +// Extends event emitter +promiseStorage.on('connection', () => {}); +urlStorage.addListener('conection', () => {}); +dbStorage.removeAllListeners('conection'); diff --git a/types/multer-gridfs-storage/v2/tsconfig.json b/types/multer-gridfs-storage/v2/tsconfig.json new file mode 100644 index 0000000000..81dfdd435a --- /dev/null +++ b/types/multer-gridfs-storage/v2/tsconfig.json @@ -0,0 +1,28 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "multer-gridfs-storage": [ + "multer-gridfs-storage/v2" + ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "multer-gridfs-storage-tests.ts" + ] +} diff --git a/types/multer-gridfs-storage/v2/tslint.json b/types/multer-gridfs-storage/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/multer-gridfs-storage/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/murmurhash/index.d.ts b/types/murmurhash/index.d.ts index 31c663fd33..eac6b500b7 100644 --- a/types/murmurhash/index.d.ts +++ b/types/murmurhash/index.d.ts @@ -9,21 +9,27 @@ export = murmurhash; * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) * * @param key - ASCII only - * @param seed - Positive integer only - * @return - 32-bit positive integer hash + * @param seed - (optional) positive integer + * @returns 32-bit positive integer hash */ -declare function murmurhash(key: string, seed: number): number; +declare function murmurhash(key: string, seed?: number): number; declare namespace murmurhash { - // Circular reference from murmurhash - function v3(key: string, seed: number): number; + /** + * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011) + * + * @param key - ASCII only + * @param seed - (optional) positive integer + * @returns 32-bit positive integer hash + */ + function v3(key: string, seed?: number): number; /** * JS Implementation of MurmurHash2 * * @param str - ASCII only - * @param seed - Positive integer only - * @return - 32-bit positive integer hash + * @param seed - (optional) positive integer + * @returns 32-bit positive integer hash */ - function v2(str: string, seed: number): number; + function v2(str: string, seed?: number): number; } diff --git a/types/murmurhash/murmurhash-tests.ts b/types/murmurhash/murmurhash-tests.ts index ebbbf09cab..fe7fc9c501 100644 --- a/types/murmurhash/murmurhash-tests.ts +++ b/types/murmurhash/murmurhash-tests.ts @@ -3,6 +3,11 @@ import murmurhash = require('murmurhash'); const stringValue = "test"; let numberValue = 123; +numberValue = murmurhash(stringValue); numberValue = murmurhash(stringValue, numberValue); + +numberValue = murmurhash.v2(stringValue); numberValue = murmurhash.v2(stringValue, numberValue); + +numberValue = murmurhash.v3(stringValue); numberValue = murmurhash.v3(stringValue, numberValue); diff --git a/types/mustache-express/index.d.ts b/types/mustache-express/index.d.ts new file mode 100644 index 0000000000..ff40de42d7 --- /dev/null +++ b/types/mustache-express/index.d.ts @@ -0,0 +1,23 @@ +// Type definitions for mustache-express 1.2 +// Project: https://github.com/bryanburgers/node-mustache-express#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Cache } from 'lru-cache'; + +export = mustacheExpress; + +declare function mustacheExpress( + partialsPath?: string, + partialsExt?: string +): mustacheExpress.ExpessEngine; + +declare namespace mustacheExpress { + interface ExpessEngine { + (path: string, options: any, cb: (...args: any[]) => any): any; + cache: TemplateCache; + } + + type TemplateCache = Cache; +} diff --git a/types/mustache-express/mustache-express-tests.ts b/types/mustache-express/mustache-express-tests.ts new file mode 100644 index 0000000000..9157798c7b --- /dev/null +++ b/types/mustache-express/mustache-express-tests.ts @@ -0,0 +1,10 @@ +import express = require('express'); +import mustacheExpress = require('mustache-express'); + +const app = express(); +app.engine('mustache', mustacheExpress()); +app.engine('mustache', mustacheExpress('/partials')); +app.engine('mustache', mustacheExpress('/partials', '.mst')); + +// $ExpectType Cache +mustacheExpress().cache; diff --git a/types/mustache-express/tsconfig.json b/types/mustache-express/tsconfig.json new file mode 100644 index 0000000000..9afb989b62 --- /dev/null +++ b/types/mustache-express/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", + "mustache-express-tests.ts" + ] +} diff --git a/types/mustache-express/tslint.json b/types/mustache-express/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mustache-express/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mustache/index.d.ts b/types/mustache/index.d.ts index 2b0ab91cd0..77b8880fdd 100644 --- a/types/mustache/index.d.ts +++ b/types/mustache/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Mustache 0.8.3 +// Type definitions for Mustache 0.8.4 // Project: https://github.com/janl/mustache.js // Definitions by: Mark Ashley Bell , Manuel Thalmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -20,7 +20,7 @@ interface MustacheStatic { /** * The opening and closing tags to parse. */ - tags: string; + tags: string[]; /** * A simple string scanner that is used by the template parser to find tokens in template strings. @@ -80,8 +80,11 @@ interface MustacheStatic { * -- or -- * * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + * + * @param tags + * The tags to use. */ - render(template: string, view: any | MustacheContext, partials?: any): string; + render(template: string, view: any | MustacheContext, partials?: any, tags?: string[]): string; /** * Renders the `template` with the given `view` and `partials` using the default writer. @@ -198,8 +201,11 @@ declare class MustacheWriter { * * @param template * The template to parse. + * + * @param tags + * The tags to use. */ - parse(template: string, tags?: any): any; + parse(template: string, tags?: string[]): any; /** * High-level method that is used to render the given `template` with the given `view`. @@ -216,8 +222,11 @@ declare class MustacheWriter { * -- or -- * * A function that is used to load partial template on the fly that takes a single argument: the name of the partial. + * + * @param tags + * The tags to use. */ - render(template: string, view: any | MustacheContext, partials: any): string; + render(template: string, view: any | MustacheContext, partials: any, tags?: string[]): string; /** * Low-level method that renders the given array of `tokens` using the given `context` and `partials`. diff --git a/types/mustache/mustache-tests.ts b/types/mustache/mustache-tests.ts index 30c920a30a..bca7d5a40e 100644 --- a/types/mustache/mustache-tests.ts +++ b/types/mustache/mustache-tests.ts @@ -26,4 +26,8 @@ var view4 = new class extends Mustache.Context } }; var template4 = "Hello, {{firstName}} {{lastName}}"; -var html4 = Mustache.render(template4, view4); \ No newline at end of file +var html4 = Mustache.render(template4, view4); + +var view5 = { title: "Joe", calc: function () { return 2 + 4; } }; +var template5 = "[[title]] spends [[calc]]"; +var output5 = Mustache.render(template5, view5, {}, ["[[", "]]"]); \ No newline at end of file diff --git a/types/mutexify/index.d.ts b/types/mutexify/index.d.ts new file mode 100644 index 0000000000..4fa1dffe2a --- /dev/null +++ b/types/mutexify/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for mutexify 1.2 +// Project: https://github.com/mafintosh/mutexify +// Definitions by: Gustav Bylund +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +interface Lock { + (fn: Release): number; + locked: boolean; +} + +type Release = ( + cb: (err?: any, value?: any) => any, + err: any, + value: any +) => void; + +declare function mutexify(): Lock; + +export = mutexify; +export as namespace mutexify; diff --git a/types/mutexify/mutexify-tests.ts b/types/mutexify/mutexify-tests.ts new file mode 100644 index 0000000000..dc921cb246 --- /dev/null +++ b/types/mutexify/mutexify-tests.ts @@ -0,0 +1,6 @@ +import mutexify = require("mutexify"); +const lock = mutexify(); + +lock(release => { + release(); +}); diff --git a/types/mutexify/tsconfig.json b/types/mutexify/tsconfig.json new file mode 100644 index 0000000000..4c1ee302d0 --- /dev/null +++ b/types/mutexify/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", "mutexify-tests.ts"] +} diff --git a/types/mutexify/tslint.json b/types/mutexify/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/mutexify/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/mz/mz-tests.ts b/types/mz/mz-tests.ts index b873c98bbe..a4ec4667a7 100644 --- a/types/mz/mz-tests.ts +++ b/types/mz/mz-tests.ts @@ -136,7 +136,7 @@ describe('readline', function () { var input = new stream.PassThrough() var output = new stream.PassThrough() var bufferedOutput = '' - var rl = readline.createInterface( input, output, completer, true ) + var rl = readline.createInterface( input, output, completer as readline.Completer, true ) rl.question('a').then(function (answer: string) { assert.equal(answer, 'bTESTSTRING') @@ -174,12 +174,12 @@ describe('readline', function () { it('completer support sync', function (done) { function completer (line: string) { assert.equal(line, 'b') - return <[string[], string]>[['bTESTSTRING'], line] + return [['bTESTSTRING'], line] as [string[], string] } var input = new stream.PassThrough() var output = new stream.PassThrough() - var rl = readline.createInterface(input, output, completer, true) + var rl = readline.createInterface(input, output, completer as readline.Completer, true) rl.question('a').then(function (answer) { assert.ok(output.read().toString().match(/TESTSTRING/)) @@ -197,7 +197,7 @@ describe('readline', function () { var input = new stream.PassThrough() var output = new stream.PassThrough() - var rl = readline.createInterface(input, output, completer, true ) + var rl = readline.createInterface(input, output, completer as readline.Completer, true ) rl.question('a').then(function (answer) { assert.ok(output.read().toString().match(/TESTSTRING/)) diff --git a/types/n3/index.d.ts b/types/n3/index.d.ts index a9438616c2..3d19f36d38 100644 --- a/types/n3/index.d.ts +++ b/types/n3/index.d.ts @@ -2,8 +2,9 @@ // Project: https://github.com/RubenVerborgh/N3.js // Definitions by: Fred Eisele // Ruben Taelman +// Laurens Rietveld // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 +// TypeScript Version: 2.3 /// @@ -12,93 +13,123 @@ import * as stream from "stream"; import * as RDF from "rdf-js"; import { EventEmitter } from "events"; -export interface Prefixes { - [key: string]: RDF.NamedNode; +export interface Prefixes { + [key: string]: I; } -export class Term implements RDF.Term { - termType: "NamedNode" | "BlankNode" | "Literal" | "Variable" | "DefaultGraph"; - id: string; - value: string; +export type Term = NamedNode | BlankNode | Literal | Variable | DefaultGraph; +export type PrefixedToIri = (suffix: string) => RDF.NamedNode; + +export class NamedNode implements RDF.NamedNode { + readonly termType: "NamedNode"; + readonly value: string; constructor(iri: string); - toJSON(): string; + readonly id: string; + toJSON(): {}; equals(other: RDF.Term): boolean; static subclass(type: any): void; } -export class NamedNode extends Term implements RDF.NamedNode { - termType: "NamedNode"; - value: string; - constructor(iri: string); -} - -export class BlankNode extends Term implements RDF.BlankNode { +export class BlankNode implements RDF.BlankNode { static nextId: number; - termType: "BlankNode"; - value: string; + readonly termType: "BlankNode"; + readonly value: string; constructor(name: string); + readonly id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Variable extends Term implements RDF.Variable { - termType: "Variable"; - value: string; +export class Variable implements RDF.Variable { + readonly termType: "Variable"; + readonly value: string; constructor(name: string); + readonly id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Literal extends Term implements RDF.Literal { +export class Literal implements RDF.Literal { static readonly langStringDatatype: NamedNode; - termType: "Literal"; - value: string; - language: string; - datatype: RDF.NamedNode; - datatypeString: string; + readonly termType: "Literal"; + readonly value: string; + readonly id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; + readonly language: string; + readonly datatype: NamedNode; + readonly datatypeString: string; constructor(id: string); } -export class DefaultGraph extends Term implements RDF.DefaultGraph { - termType: "DefaultGraph"; - value: ""; +export class DefaultGraph implements RDF.DefaultGraph { + readonly termType: "DefaultGraph"; + readonly value: ""; constructor(); + readonly id: string; + toJSON(): {}; + equals(other: RDF.Term): boolean; + static subclass(type: any): void; } -export class Quad implements RDF.Quad { - constructor(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term); - subject: RDF.Term; - predicate: RDF.Term; - object: RDF.Term; - graph: RDF.Term; - equals(other: RDF.Quad): boolean; +export type Quad_Subject = NamedNode | BlankNode | Variable; +export type Quad_Predicate = NamedNode | Variable; +export type Quad_Object = NamedNode | Literal | BlankNode | Variable; +export type Quad_Graph = DefaultGraph | NamedNode | BlankNode | Variable; + +export class BaseQuad implements RDF.BaseQuad { + constructor(subject: Term, predicate: Term, object: Term, graph?: Term); + subject: Term; + predicate: Term; + object: Term; + graph: Term; + equals(other: RDF.BaseQuad): boolean; + toJSON(): string; +} + +export class Quad extends BaseQuad implements RDF.Quad { + constructor(subject: Term, predicate: Term, object: Term, graph?: Term); + subject: Quad_Subject; + predicate: Quad_Predicate; + object: Quad_Object; + graph: Quad_Graph; + equals(other: RDF.BaseQuad): boolean; toJSON(): string; } export class Triple extends Quad implements RDF.Triple {} export namespace DataFactory { - function namedNode(value: string): RDF.NamedNode; - function blankNode(value?: string): RDF.BlankNode; - function literal(value: string | number, languageOrDatatype?: string | RDF.NamedNode): RDF.Literal; - function variable(value: string): RDF.Variable; - function defaultGraph(): RDF.DefaultGraph; - function triple(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term): RDF.Quad; - function quad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): RDF.Quad; + function namedNode(value: string): NamedNode; + function blankNode(value?: string): BlankNode; + function literal(value: string | number, languageOrDatatype?: string | RDF.NamedNode): Literal; + function variable(value: string): Variable; + function defaultGraph(): DefaultGraph; + function quad(subject: RDF.Quad_Subject, predicate: RDF.Quad_Predicate, object: RDF.Quad_Object, graph?: RDF.Quad_Graph): Quad; + function quad(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object'], graph?: Q_In['graph']): Q_Out; + function triple(subject: RDF.Quad_Subject, predicate: RDF.Quad_Predicate, object: RDF.Quad_Object): Quad; + function triple(subject: Q_In['subject'], predicate: Q_In['predicate'], object: Q_In['object']): Q_Out; } export type ErrorCallback = (err: Error, result: any) => void; -export type QuadCallback = (result: Quad) => void; -export type QuadPredicate = (result: Quad) => boolean; +export type QuadCallback = (result: Q) => void; +export type QuadPredicate = (result: Q) => boolean; export type OTerm = RDF.Term | string | null; export type Logger = (message?: any, ...optionalParams: any[]) => void; -export interface BlankTriple { - predicate: RDF.Term; - object: RDF.Term; +export interface BlankTriple { + predicate: Q['predicate']; + object: Q['object']; } export interface ParserConstructor { - new (options?: ParserOptions): N3Parser; - (options?: ParserOptions): N3Parser; + new (options?: ParserOptions): N3Parser; + (options?: ParserOptions): N3Parser; } export const Parser: ParserConstructor; @@ -109,19 +140,19 @@ export interface ParserOptions { baseIRI?: string; } -export type ParseCallback = (error: Error, quad: Quad, prefixes: Prefixes) => void; +export type ParseCallback = (error: Error, quad: Q, prefixes: Prefixes) => void; -export interface N3Parser { - parse(input: string, callback: ParseCallback): void; +export interface N3Parser { + parse(input: string, callback: ParseCallback): void; } export interface StreamParserConstructor { - new (options?: ParserOptions): N3StreamParser; - (options?: ParserOptions): N3StreamParser; + new (options?: ParserOptions): N3StreamParser; + (options?: ParserOptions): N3StreamParser; } export const StreamParser: StreamParserConstructor; -export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.Sink { +export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.Sink { // Below are the NodeJS.ReadableStream methods, // we can not extend the interface directly, // as `read` clashes with RDF.Sink. @@ -131,78 +162,79 @@ export interface N3StreamParser extends RDF.Stream, NodeJS.WritableStream, RDF.S pause(): this; resume(): this; isPaused(): boolean; - pipe(destination: T, options?: { end?: boolean; }): T; - unpipe(destination?: NodeJS.WritableStream | RDF.Stream): void; + pipe>(destination: T, options?: { end?: boolean; }): T; + unpipe(destination?: NodeJS.WritableStream | RDF.Stream): void; unshift(chunk: string | Buffer): void; - wrap(oldStream: NodeJS.ReadableStream | RDF.Stream): NodeJS.ReadableStream; + wrap(oldStream: NodeJS.ReadableStream | RDF.Stream): NodeJS.ReadableStream; } export interface WriterOptions { format?: string; - prefixes?: Prefixes; + prefixes?: Prefixes; + end?: boolean; } export interface WriterConstructor { - new (options?: WriterOptions): N3Writer; - new (fd: any, options?: WriterOptions): N3Writer; - (options?: WriterOptions): N3Writer; - (fd: any, options?: WriterOptions): N3Writer; + new (options?: WriterOptions): N3Writer; + new (fd: any, options?: WriterOptions): N3Writer; + (options?: WriterOptions): N3Writer; + (fd: any, options?: WriterOptions): N3Writer; } export const Writer: WriterConstructor; -export interface N3Writer { - quadToString(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term, graph?: RDF.Term): string; +export interface N3Writer { + quadToString(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'], graph?: Q['graph']): string; quadsToString(quads: RDF.Quad[]): string; - addQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; + addQuad(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'] | Array, graph?: Q['graph'], done?: () => void): void; addQuad(quad: RDF.Quad): void; addQuads(quads: RDF.Quad[]): void; - addPrefix(prefix: string, iri: string, done?: () => void): void; - addPrefixes(prefixes: Prefixes, done?: () => void): void; + addPrefix(prefix: string, iri: RDF.NamedNode | string , done?: () => void): void; + addPrefixes(prefixes: Prefixes, done?: () => void): void; end(err?: ErrorCallback, result?: string): void; - blank(predicate: RDF.Term, object: RDF.Term): RDF.Term; - blank(triple: BlankTriple | RDF.Quad | BlankTriple[] | RDF.Quad[]): RDF.Term; - list(triple: RDF.Term[]): RDF.Term[]; + blank(predicate: Q['predicate'], object: Q['object']): BlankNode; + blank(triple: BlankTriple | RDF.Quad | BlankTriple[] | RDF.Quad[]): BlankNode; + list(triple: Array): Quad_Object[]; } export interface StreamWriterConstructor { - new (options?: WriterOptions): N3StreamWriter; - new (fd: any, options?: WriterOptions): N3StreamWriter; - (options?: WriterOptions): N3StreamWriter; - (fd: any, options?: WriterOptions): N3StreamWriter; + new (options?: WriterOptions): N3StreamWriter; + new (fd: any, options?: WriterOptions): N3StreamWriter; + (options?: WriterOptions): N3StreamWriter; + (fd: any, options?: WriterOptions): N3StreamWriter; } export const StreamWriter: StreamWriterConstructor; -export interface N3StreamWriter extends NodeJS.ReadWriteStream, RDF.Source {} +export interface N3StreamWriter extends NodeJS.ReadWriteStream, RDF.Source {} -export interface N3Store extends RDF.Sink { +export interface N3Store extends RDF.Sink { readonly size: number; - addQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; - addQuad(quad: RDF.Quad): void; - addQuads(quads: RDF.Quad[]): void; - removeQuad(subject: RDF.Term, predicate: RDF.Term, object: RDF.Term | RDF.Term[], graph?: RDF.Term, done?: () => void): void; - removeQuad(quad: RDF.Quad): void; - removeQuads(quads: RDF.Quad[]): void; + addQuad(subject: Q_RDF['subject'], predicate: Q_RDF['predicate'], object: Q_RDF['object'] | Array, graph?: Q_RDF['graph'], done?: () => void): void; + addQuad(quad: Q_RDF): void; + addQuads(quads: Q_RDF[]): void; + removeQuad(subject: Q_RDF['subject'], predicate: Q_RDF['predicate'], object: Q_RDF['object'] | Array, graph?: Q_RDF['graph'], done?: () => void): void; + removeQuad(quad: Q_RDF): void; + removeQuads(quads: Q_RDF[]): void; getQuads(subject: OTerm, predicate: OTerm, object: OTerm | OTerm[], graph: OTerm): Quad[]; countQuads(subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): number; - forEach(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): void; - every(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; - some(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; - getSubjects(predicate: OTerm, object: OTerm, graph: OTerm): RDF.Term[]; - forSubjects(callback: QuadCallback, predicate: OTerm, object: OTerm, graph: OTerm): void; - getPredicates(subject: OTerm, object: OTerm, graph: OTerm): RDF.Term[]; - forPredicates(callback: QuadCallback, subject: OTerm, object: OTerm, graph: OTerm): void; - getObjects(subject: OTerm, predicate: OTerm, graph: OTerm): RDF.Term[]; - forObjects(callback: QuadCallback, subject: OTerm, predicate: OTerm, graph: OTerm): void; - getGraphs(subject: OTerm, predicate: OTerm, object: OTerm): RDF.Term[]; - forGraphs(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm): void; + forEach(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): void; + every(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; + some(callback: QuadPredicate, subject: OTerm, predicate: OTerm, object: OTerm, graph: OTerm): boolean; + getSubjects(predicate: OTerm, object: OTerm, graph: OTerm): Array; + forSubjects(callback: QuadCallback, predicate: OTerm, object: OTerm, graph: OTerm): void; + getPredicates(subject: OTerm, object: OTerm, graph: OTerm): Array; + forPredicates(callback: QuadCallback, subject: OTerm, object: OTerm, graph: OTerm): void; + getObjects(subject: OTerm, predicate: OTerm, graph: OTerm): Array; + forObjects(callback: QuadCallback, subject: OTerm, predicate: OTerm, graph: OTerm): void; + getGraphs(subject: OTerm, predicate: OTerm, object: OTerm): Array; + forGraphs(callback: QuadCallback, subject: OTerm, predicate: OTerm, object: OTerm): void; createBlankNode(suggestedName?: string): BlankNode; // match, removeMatches and deleteGraph are missing for full RDF.Store adherence remove(stream: stream.Stream): EventEmitter; } export interface StoreConstructor { - new (triples?: RDF.Quad[], options?: StoreOptions): N3Store; - (triples?: RDF.Quad[], options?: StoreOptions): N3Store; + new (triples?: Q_RDF[], options?: StoreOptions): N3Store; + (triples?: Q_RDF[], options?: StoreOptions): N3Store; } export const Store: StoreConstructor; @@ -217,6 +249,9 @@ export namespace Util { function isVariable(value: RDF.Term | null): boolean; function isDefaultGraph(value: RDF.Term | null): boolean; function inDefaultGraph(value: RDF.Quad): boolean; - function prefix(iri: string, factory?: RDF.DataFactory): (suffix: string) => RDF.NamedNode; - function prefixes(defaultPrefixes: Prefixes, factory?: RDF.DataFactory): (iri: string) => (suffix: string) => RDF.NamedNode; + function prefix(iri: RDF.NamedNode|string, factory?: RDF.DataFactory): PrefixedToIri; + function prefixes( + defaultPrefixes: Prefixes, + factory?: RDF.DataFactory + ): (prefix: string) => PrefixedToIri; } diff --git a/types/n3/n3-tests.ts b/types/n3/n3-tests.ts index d24960a112..58d10892da 100644 --- a/types/n3/n3-tests.ts +++ b/types/n3/n3-tests.ts @@ -17,7 +17,8 @@ function test_add_prefixes() { writer.addPrefixes({ freebase: N3.DataFactory.namedNode("http://rdf.freebase.com/ns/"), - xsd: N3.DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#") + xsd: N3.DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#"), + rdf: 'http://test' }); writer.end((error, result) => { @@ -31,7 +32,7 @@ function test_serialize() { format: "ttl", prefixes: { foaf: "http://xmlns.com/foaf/0.1", - freebase: "http://rdf.freebase.com/ns/", + freebase: N3.DataFactory.namedNode("http://rdf.freebase.com/ns/"), g: "http://base.google.com/ns/1.0" } }); @@ -76,7 +77,13 @@ function test_doc_rdf_to_triples_2() { } function test_doc_rdf_stream_to_triples_1() { - const parser: N3.N3Parser = new N3.Parser(); + interface QuadBnode extends N3.BaseQuad { + subject: N3.BlankNode; + predicate: N3.BlankNode; + object: N3.BlankNode; + graph: N3.BlankNode; + } + const parser: N3.N3Parser = new N3.Parser({factory: N3.DataFactory}); parser.parse('abc', console.log); const streamParser: N3.N3StreamParser = N3.StreamParser(); @@ -113,7 +120,7 @@ function test_doc_from_triples_to_string() { } function test_doc_from_triples_to_rdf_stream() { - const writer: N3.N3Writer = new N3.Writer(process.stdout, { prefixes: { c: N3.DataFactory.namedNode('http://example.org/cartoons#') } }); + const writer: N3.N3Writer = new N3.Writer(process.stdout, { end: false, prefixes: { c: N3.DataFactory.namedNode('http://example.org/cartoons#') } }); writer.addQuad(N3.DataFactory.quad( N3.DataFactory.namedNode('http://example.org/cartoons#Tom'), N3.DataFactory.namedNode('http://www.w3.org/1999/02/22-rdf-syntax-ns#type'), @@ -177,7 +184,26 @@ function test_doc_storing() { const bnode2: RDF.BlankNode = store.createBlankNode('abc'); const mickey: RDF.Quad = store.getQuads(N3.DataFactory.namedNode('http://ex.org/Mickey'), null, null, null)[0]; + if (mickey.object.termType === "Literal") { + console.log(mickey.object.datatype); + } console.log(mickey.subject, mickey.predicate, mickey.object, '.'); + + interface N3QuadGeneralized extends N3.BaseQuad { + subject: N3.Quad_Subject | N3.BlankNode | N3.Literal; + predicate: N3.Quad_Predicate | N3.BlankNode | N3.Literal; + object: N3.Quad_Object | N3.BlankNode | N3.Literal; + graph: N3.Quad_Graph | N3.BlankNode | N3.Literal; + } + interface RDFQuadGeneralized extends RDF.BaseQuad { + subject: RDF.Quad_Subject | RDF.BlankNode | RDF.Literal; + predicate: RDF.Quad_Predicate | RDF.BlankNode | RDF.Literal; + object: RDF.Quad_Object | RDF.BlankNode | RDF.Literal; + graph: RDF.Quad_Graph | RDF.BlankNode | RDF.Literal; + } + const storeGeneralized = new N3.Store(); + // storeGeneralized. + storeGeneralized.addQuad(N3.DataFactory.namedNode('http://ex.org/Pluto'), N3.DataFactory.blankNode(), N3.DataFactory.namedNode('http://ex.org/Dog')); } function test_doc_utility() { diff --git a/types/n3/tslint.json b/types/n3/tslint.json index d88586e5bd..e27ad90359 100644 --- a/types/n3/tslint.json +++ b/types/n3/tslint.json @@ -1,3 +1,6 @@ { - "extends": "dtslint/dt.json" + "extends": "dtslint/dt.json", + "rules": { + "no-unnecessary-generics": false + } } diff --git a/types/nes/index.d.ts b/types/nes/index.d.ts index 7c48cb84b0..78ff90e046 100644 --- a/types/nes/index.d.ts +++ b/types/nes/index.d.ts @@ -3,7 +3,7 @@ // Definitions by: Ivo Stratev // Rodrigo Saboya // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 /* + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/types/net-keepalive/tsconfig.json b/types/net-keepalive/tsconfig.json index 7a0277396e..e3f703b220 100644 --- a/types/net-keepalive/tsconfig.json +++ b/types/net-keepalive/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "baseUrl": "../", "typeRoots": [ 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/netlify-identity-widget/index.d.ts b/types/netlify-identity-widget/index.d.ts new file mode 100644 index 0000000000..a231be53d2 --- /dev/null +++ b/types/netlify-identity-widget/index.d.ts @@ -0,0 +1,86 @@ +// Type definitions for netlify-identity-widget 1.4 +// Project: https://github.com/netlify/netlify-identity-widget +// Definitions by: Naveen Kumar Sangi +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export interface InitOptions { + // The container to attach to. e.g.: '#some-query-selector' + container?: string; + + // Absolute url to endpoint. ONLY USE IN SPECIAL CASES! + // e.g. https://www.example.com/.netlify/functions/identity + // Generally avoid setting the APIUrl. You should only set this when + // your app is served from a domain that differs from where the + // identity endpoint is served.This is common for Cordova or Electron + // apps where you host from localhost or a file. + APIUrl?: string; +} + +export interface Token { + access_token: string; + expires_at: string | number; + expires_in: string | number; + refresh_token: string; + token_type: string; +} + +export interface User { + api: { + _sameOrigin?: boolean; + apiURL: string; + defaultHeaders: { + [header: string]: string | string[] | undefined; + }; + }; + app_metadata: { + provider: string; + }; + aud: string; + audience?: any; + confirmed_at: string; + created_at: string; + updated_at: string; + email: string; + id: string; + role: string; + token?: Token; + url: string; + user_metadata: { + avatar_url: string; + full_name: string; + }; +} + +/** + * Initialises the netlify identity widget. + */ +export function init(opts?: InitOptions): void; + +/** + * Opens the netlify login modal to the corresponding tab. + */ +export function open(tabName?: "signup" | "login"): void; + +/** + * Closes the netlify login modal. + */ +export function close(): void; + +/** + * Retrieves the current logged in user information. + */ +export function currentUser(): User | null; + +/** + * Registers callbacks to corresponding events on the widget. + */ +export function on(event: 'init', cb: (user: User | null) => void): void; +export function on(event: 'login', cb: (user: User) => void): void; +export function on(event: 'logout' | 'open' | 'close', cb: () => void): void; +export function on(event: 'error', cb: (err: Error) => void): void; + +/** + * Logs out the current user. Returns a Promise when a user is + * logged in, else returns undefined. + */ +export function logout(): Promise | undefined; diff --git a/types/netlify-identity-widget/netlify-identity-widget-tests.ts b/types/netlify-identity-widget/netlify-identity-widget-tests.ts new file mode 100644 index 0000000000..f44daaec37 --- /dev/null +++ b/types/netlify-identity-widget/netlify-identity-widget-tests.ts @@ -0,0 +1,69 @@ +import es6styleimport from 'netlify-identity-widget'; + +import NetlifyIdentityWidget = require('netlify-identity-widget'); + +// Type 0: es6styleimport test +es6styleimport.init(); + +// Type 1: Initialize without options +NetlifyIdentityWidget.init(); +NetlifyIdentityWidget.init({}); + +// Type 2: Initialize with container option +NetlifyIdentityWidget.init({ container: 'body' }); + +// Type 3: Initialize with a specific APIUrl +NetlifyIdentityWidget.init({ APIUrl: 'https://www.example.com/.netlify/functions/identity' }); + +// Type 4: Initialize with both the options specified +NetlifyIdentityWidget.init({ + APIUrl: 'https://www.example.com/.netlify/functions/identity', + container: 'body', +}); + +// Open widget modal to let users login +NetlifyIdentityWidget.open(); +NetlifyIdentityWidget.on('open', () => { + // Widget is open and ready to login +}); + +// Open wigdet modal with signup tab selected +NetlifyIdentityWidget.open('signup'); + +// Close the widget programmatically +NetlifyIdentityWidget.close(); +NetlifyIdentityWidget.on('close', () => { + // Widget is closed +}); + +// Event handling after login +NetlifyIdentityWidget.on('login', (user) => { + // You can now use User info after a successful login +}); + +// Event handling after logout +NetlifyIdentityWidget.on('logout', () => { + // You can now notify that the logout was successful +}); + +// Event handling after login on page refresh +NetlifyIdentityWidget.on('init', (user) => { + // Now the widget is ready to use + // If a user was already logged in, the value is returned else null is passed via callback +}); + +// Event handling on errors +NetlifyIdentityWidget.on('error', (err) => { + // The error occured during operation is passed in via callback +}); + +// Use the current logged in user +const user = NetlifyIdentityWidget.currentUser(); + +// If a user is logged in, logout returns a Promise +const logoutPromise = NetlifyIdentityWidget.logout(); +if (logoutPromise) { + logoutPromise.then(() => { + // You can now do clean up after successful logout + }); +} diff --git a/types/netlify-identity-widget/tsconfig.json b/types/netlify-identity-widget/tsconfig.json new file mode 100644 index 0000000000..8ded135467 --- /dev/null +++ b/types/netlify-identity-widget/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "netlify-identity-widget-tests.ts" + ] +} diff --git a/types/netlify-identity-widget/tslint.json b/types/netlify-identity-widget/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/netlify-identity-widget/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/newman/index.d.ts b/types/newman/index.d.ts index cd2801c375..7bd7aef744 100644 --- a/types/newman/index.d.ts +++ b/types/newman/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for newman 3.10 +// Type definitions for newman 3.11 // Project: https://github.com/postmanlabs/newman // Definitions by: Leonid Logvinov // Graham McGregor @@ -168,9 +168,12 @@ export interface NewmanRunExecutionAssertion { error: NewmanRunExecutionAssertionError; } export interface NewmanRunExecutionAssertionError { + name: string; + index: number; + test: string; message: string; -} -export interface NewmanRunFailure { + stack: string; +}export interface NewmanRunFailure { error: NewmanRunExecutionAssertionError; /** The event where the failure occurred */ at: string; diff --git a/types/newrelic/index.d.ts b/types/newrelic/index.d.ts index f6c54f5a4b..a5fd434d99 100644 --- a/types/newrelic/index.d.ts +++ b/types/newrelic/index.d.ts @@ -1,351 +1,347 @@ -// Type definitions for newrelic 3.3 +// Type definitions for newrelic 3.4 // Project: http://github.com/newrelic/node-newrelic // Definitions by: Matt R. Wilson +// Brooks Patton // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // https://docs.newrelic.com/docs/agents/nodejs-agent/api-guides/nodejs-agent-api -declare namespace newrelic { - interface NewRelicAPI { - /** - * Give the current transaction a custom name. - * - * Overrides any New Relic naming rules set in configuration or from New Relic's servers. - * - * IMPORTANT: this function must be called when a transaction is active. New - * Relic transactions are tied to web requests, so this method may be called - * from within HTTP or HTTPS listener functions, Express routes, or other - * contexts where a web request or response object are in scope. - * - * The `name` will be prefixed with 'Custom/' when sent. - */ - setTransactionName(name: string): void; - /** - * Returns a handle on the currently executing transaction. - * - * This handle can then be used to end or ignore a given transaction safely from any context. - * It is best used with newrelic.startWebTransaction() and newrelic.startBackgroundTransaction(). - */ - getTransaction(): TransactionHandle; +/** + * Give the current transaction a custom name. + * + * Overrides any New Relic naming rules set in configuration or from New Relic's servers. + * + * IMPORTANT: this function must be called when a transaction is active. New + * Relic transactions are tied to web requests, so this method may be called + * from within HTTP or HTTPS listener functions, Express routes, or other + * contexts where a web request or response object are in scope. + * + * The `name` will be prefixed with 'Custom/' when sent. + */ +export function setTransactionName(name: string): void; - /** - * Specify the `Dispatcher` and `Dispatcher Version` environment values. - * - * A dispatcher is typically the service responsible for brokering - * the request with the process responsible for responding to the - * request. For example Node's `http` module would be the dispatcher - * for incoming HTTP requests. - */ - setDispatcher(name: string, version?: string): void; +/** + * Returns a handle on the currently executing transaction. + * + * This handle can then be used to end or ignore a given transaction safely from any context. + * It is best used with newrelic.startWebTransaction() and newrelic.startBackgroundTransaction(). + */ +export function getTransaction(): TransactionHandle; - /** - * Give the current transaction a name based on your own idea of what - * constitutes a controller in your Node application. Also allows you to - * optionally specify the action being invoked on the controller. If the action - * is omitted, then the API will default to using the HTTP method used in the - * request (e.g. GET, POST, DELETE). Overrides any New Relic naming rules set - * in configuration or from New Relic's servers. - * - * IMPORTANT: this function must be called when a transaction is active. New - * Relic transactions are tied to web requests, so this method may be called - * from within HTTP or HTTPS listener functions, Express routes, or other - * contexts where a web request or response object are in scope. - * - * The `name` will be prefixed with 'Controller/' when sent. - * The `action` defaults to the HTTP method used for the request. - */ - setControllerName(name: string, action: string): void; +/** + * Specify the `Dispatcher` and `Dispatcher Version` environment values. + * + * A dispatcher is typically the service responsible for brokering + * the request with the process responsible for responding to the + * request. For example Node's `http` module would be the dispatcher + * for incoming HTTP requests. + */ +export function setDispatcher(name: string, version?: string): void; - /** - * Add a custom attribute to the current transaction. - * - * Some attributes are reserved (see CUSTOM_BLACKLIST in the docs for the current, very short list), and - * as with most API methods, this must be called in the context of an - * active transaction. - * - * Most recently set value wins. - */ - addCustomAttribute(key: string, value: string): void; +/** + * Give the current transaction a name based on your own idea of what + * constitutes a controller in your Node application. Also allows you to + * optionally specify the action being invoked on the controller. If the action + * is omitted, then the API will default to using the HTTP method used in the + * request (e.g. GET, POST, DELETE). Overrides any New Relic naming rules set + * in configuration or from New Relic's servers. + * + * IMPORTANT: this function must be called when a transaction is active. New + * Relic transactions are tied to web requests, so this method may be called + * from within HTTP or HTTPS listener functions, Express routes, or other + * contexts where a web request or response object are in scope. + * + * The `name` will be prefixed with 'Controller/' when sent. + * The `action` defaults to the HTTP method used for the request. + */ +export function setControllerName(name: string, action: string): void; - /** - * Adds all custom attributes in an object to the current transaction. - * - * See documentation for `addCustomAttribute` for more information on setting custom attributes. - */ - addCustomAttributes(atts: { [key: string]: string }): void; +/** + * Add a custom attribute to the current transaction. + * + * Some attributes are reserved (see CUSTOM_BLACKLIST in the docs for the current, very short list), and + * as with most API methods, this must be called in the context of an + * active transaction. + * + * Most recently set value wins. + */ +export function addCustomAttribute(key: string, value: string|number): void; - /** - * Tell the tracer whether to ignore the current transaction. - * - * The most common use for this will be to mark a transaction as ignored (maybe it's handling - * a websocket polling channel, or maybe it's an external call you don't care - * is slow), but it's also useful when you want a transaction that would - * otherwise be ignored due to URL or transaction name normalization rules - * to *not* be ignored. - */ - setIgnoreTransaction(ignored: boolean): void; +/** + * Adds all custom attributes in an object to the current transaction. + * + * See documentation for `addCustomAttribute` for more information on setting custom attributes. + */ +export function addCustomAttributes(atts: { [key: string]: string|number }): void; - /** - * Send errors to New Relic that you've already handled yourself. - * - * NOTE: Errors that are recorded using this method do _not_ obey the `ignore_status_codes` configuration. - * - * Optional. Any custom attributes to be displayed in the New Relic UI. - */ - noticeError(error: Error, customAttributes?: { [key: string]: string }): void; +/** + * Tell the tracer whether to ignore the current transaction. + * + * The most common use for this will be to mark a transaction as ignored (maybe it's handling + * a websocket polling channel, or maybe it's an external call you don't care + * is slow), but it's also useful when you want a transaction that would + * otherwise be ignored due to URL or transaction name normalization rules + * to *not* be ignored. + */ +export function setIgnoreTransaction(ignored: boolean): void; - /** - * If the URL for a transaction matches the provided pattern, name the - * transaction with the provided name. - * - * If there are capture groups in the pattern (which is a standard JavaScript regular expression, - * and can be passed as either a RegExp or a string), then the substring matches ($1, $2, - * etc.) are replaced in the name string. BE CAREFUL WHEN USING SUBSTITUTION. - * If the replacement substrings are highly variable (i.e. are identifiers, - * GUIDs, or timestamps), the rule will generate too many metrics and - * potentially get your application blacklisted by New Relic. - * - * An example of a good rule with replacements: - * - * newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)', 'CommerceAPI/$1/$2') - * - * An example of a bad rule with replacements: - * - * newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1') - * - * Keep in mind that the original URL and any query parameters will be sent - * along with the request, so slow transactions will still be identifiable. - * - * Naming rules can not be removed once added. They can also be added via the - * agent's configuration. See configuration documentation for details. - */ - addNamingRule(pattern: RegExp | string, name: string): void; +/** + * Send errors to New Relic that you've already handled yourself. + * + * NOTE: Errors that are recorded using this method do _not_ obey the `ignore_status_codes` configuration. + * + * Optional. Any custom attributes to be displayed in the New Relic UI. + */ +export function noticeError(error: Error, customAttributes?: { [key: string]: string }): void; - /** - * If the URL for a transaction matches the provided pattern, ignore the transaction attached to that URL. - * - * Useful for filtering socket.io connections and other long-polling requests out of your agents to keep - * them from distorting an app's apdex or mean response time. - * - * Example: - * - * newrelic.addIgnoringRule('^/socket\\.io/') - */ - addIgnoringRule(pattern: RegExp | string): void; +/** + * If the URL for a transaction matches the provided pattern, name the + * transaction with the provided name. + * + * If there are capture groups in the pattern (which is a standard JavaScript regular expression, + * and can be passed as either a RegExp or a string), then the substring matches ($1, $2, + * etc.) are replaced in the name string. BE CAREFUL WHEN USING SUBSTITUTION. + * If the replacement substrings are highly variable (i.e. are identifiers, + * GUIDs, or timestamps), the rule will generate too many metrics and + * potentially get your application blacklisted by New Relic. + * + * An example of a good rule with replacements: + * + * newrelic.addNamingRule('^/storefront/(v[1-5])/(item|category|tag)', 'CommerceAPI/$1/$2') + * + * An example of a bad rule with replacements: + * + * newrelic.addNamingRule('^/item/([0-9a-f]+)', 'Item/$1') + * + * Keep in mind that the original URL and any query parameters will be sent + * along with the request, so slow transactions will still be identifiable. + * + * Naming rules can not be removed once added. They can also be added via the + * agent's configuration. See configuration documentation for details. + */ +export function addNamingRule(pattern: RegExp | string, name: string): void; - /** - * Get the header necessary for Browser Monitoring. - * - * This script must be manually injected into your templates, as high as possible - * in the header, but _after_ any X-UA-COMPATIBLE HTTP-EQUIV meta tags. - * Otherwise you may hurt IE! - * - * This method must be called _during_ a transaction, and must be called every - * time you want to generate the headers. - * - * Do *not* reuse the headers between users, or even between requests. - */ - getBrowserTimingHeader(): string; +/** + * If the URL for a transaction matches the provided pattern, ignore the transaction attached to that URL. + * + * Useful for filtering socket.io connections and other long-polling requests out of your agents to keep + * them from distorting an app's apdex or mean response time. + * + * Example: + * + * newrelic.addIgnoringRule('^/socket\\.io/') + */ +export function addIgnoringRule(pattern: RegExp | string): void; - /** - * Instrument a particular method to improve visibility into a transaction, - * or optionally turn it into a metric. - * - * The name defines a name for the segment. This name will be visible in transaction traces and - * as a new metric in the New Relic UI. - * The record flag defines whether the segment should be recorded as a metric. - * The handler is the function you want to track as a segment. - * The optional callback is a function passed to the handler to fire after its work is done. - * - * The agent begins timing the segment when startSegment is called. - * The segment is ended when either the handler finishes executing, or callback is fired, if it is provided. - * If a promise is returned from the handler, the segment's ending will be tied to that promise resolving or rejecting. - */ - startSegment>(name: string, record: boolean, handler: T): T; - startSegment any>(name: string, record: boolean, handler: (cb?: C) => T, callback?: C): T; +/** + * Get the header necessary for Browser Monitoring. + * + * This script must be manually injected into your templates, as high as possible + * in the header, but _after_ any X-UA-COMPATIBLE HTTP-EQUIV meta tags. + * Otherwise you may hurt IE! + * + * This method must be called _during_ a transaction, and must be called every + * time you want to generate the headers. + * + * Do *not* reuse the headers between users, or even between requests. + */ +export function getBrowserTimingHeader(): string; - /** - * Instrument a particular callback to improve visibility into a transaction. - * - * Use this API call to improve instrumentation of a particular method, or to track work across asynchronous - * boundaries by calling createTracer() in both the target function and its parent asynchronous function. - * - * The name will be visible in transaction traces and as a new metric in the New Relic UI. - * - * The agent begins timing the segment when createTracer is called, and ends the segment when the callback - * defined by the callback argument finishes executing. - * - * @deprecated - * This method has been deprecated in favor of newrelic.startSegment() - */ - createTracer any>(name: string, handle: T): T; +/** + * Instrument a particular method to improve visibility into a transaction, + * or optionally turn it into a metric. + * + * The name defines a name for the segment. This name will be visible in transaction traces and + * as a new metric in the New Relic UI. + * The record flag defines whether the segment should be recorded as a metric. + * The handler is the function you want to track as a segment. + * The optional callback is a function passed to the handler to fire after its work is done. + * + * The agent begins timing the segment when startSegment is called. + * The segment is ended when either the handler finishes executing, or callback is fired, if it is provided. + * If a promise is returned from the handler, the segment's ending will be tied to that promise resolving or rejecting. + */ +export function startSegment>(name: string, record: boolean, handler: T): T; +export function startSegment any>(name: string, record: boolean, handler: (cb?: C) => T, callback?: C): T; - /** - * Creates and starts a web transaction to record work done in the handle supplied. - * - * This transaction will run until the handle - * synchronously returns UNLESS: - * 1. The handle function returns a promise, where the end of the - * transaction will be tied to the end of the promise returned. - * 2. `getTransaction` is called in the handle, flagging the - * transaction as externally handled. In this case the transaction - * will be ended when `TransactionHandle#end` is called in the user's code. - * - * @example - * var newrelic = require('newrelic') - * newrelic.startWebTransaction('/some/url/path', function() { - * var transaction = newrelic.getTransaction() - * setTimeout(function() { - * // do some work - * transaction.end() - * }, 100) - * }) - * - * The `url` is used to name and group related transactions in APM, - * so it should be a generic name and not include any variable parameters. - */ - startWebTransaction(url: string, handle: (...args: any[]) => any): any; +/** + * Instrument a particular callback to improve visibility into a transaction. + * + * Use this API call to improve instrumentation of a particular method, or to track work across asynchronous + * boundaries by calling createTracer() in both the target function and its parent asynchronous function. + * + * The name will be visible in transaction traces and as a new metric in the New Relic UI. + * + * The agent begins timing the segment when createTracer is called, and ends the segment when the callback + * defined by the callback argument finishes executing. + * + * @deprecated + * This method has been deprecated in favor of newrelic.startSegment() + */ +export function createTracer any>(name: string, handle: T): T; - /** - * Creates and starts a background transaction to record work done in the handle supplied. - * - * This transaction will run until the handle - * synchronously returns UNLESS: - * 1. The handle function returns a promise, where the end of the - * transaction will be tied to the end of the promise returned. - * 2. `API#getTransaction` is called in the handle, flagging the - * transaction as externally handled. In this case the transaction - * will be ended when `TransactionHandle#end` is called in the user's code. - * - * @example - * var newrelic = require('newrelic') - * newrelic.startBackgroundTransaction('Red October', 'Subs', function() { - * var transaction = newrelic.getTransaction() - * setTimeout(function() { - * // do some work - * transaction.end() - * }, 100) - * }) - * - * The `url` is used to name and group related transactions in APM, - * so it should be a generic name and not include any variable parameters. - * - * The optional `group can be used for grouping background transactions in APM. - * For more information see: - * https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown - */ - startBackgroundTransaction(name: string, handle: (...args: any[]) => any): any; - startBackgroundTransaction(name: string, group: string, handle: (...args: any[]) => any): any; +/** + * Creates and starts a web transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startWebTransaction('/some/url/path', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + */ +export function startWebTransaction(url: string, handle: (...args: any[]) => any): any; - /** - * End the current web or background custom transaction. - * - * This method requires being in the correct transaction context when called. - */ - endTransaction(): void; +/** + * Creates and starts a background transaction to record work done in the handle supplied. + * + * This transaction will run until the handle + * synchronously returns UNLESS: + * 1. The handle function returns a promise, where the end of the + * transaction will be tied to the end of the promise returned. + * 2. `API#getTransaction` is called in the handle, flagging the + * transaction as externally handled. In this case the transaction + * will be ended when `TransactionHandle#end` is called in the user's code. + * + * @example + * var newrelic = require('newrelic') + * newrelic.startBackgroundTransaction('Red October', 'Subs', function() { + * var transaction = newrelic.getTransaction() + * setTimeout(function() { + * // do some work + * transaction.end() + * }, 100) + * }) + * + * The `url` is used to name and group related transactions in APM, + * so it should be a generic name and not include any variable parameters. + * + * The optional `group can be used for grouping background transactions in APM. + * For more information see: + * https://docs.newrelic.com/docs/apm/applications-menu/monitoring/transactions-page#txn-type-dropdown + */ +export function startBackgroundTransaction(name: string, handle: (...args: any[]) => any): any; +export function startBackgroundTransaction(name: string, group: string, handle: (...args: any[]) => any): any; - /** - * Record an event-based metric, usually associated with a particular duration. - * - * The `name` must be a string following standard metric naming rules. The `value` will - * usually be a number, but it can also be an object. - * * When `value` is a numeric value, it should represent the magnitude of a measurement - * associated with an event; for example, the duration for a particular method call. - * * When `value` is an object, it must contain count, total, min, max, and sumOfSquares - * keys, all with number values. This form is useful to aggregate metrics on your own - * and report them periodically; for example, from a setInterval. These values will - * be aggregated with any previously collected values for the same metric. The names - * of these keys match the names of the keys used by the platform API. - */ - recordMetric(name: string, value: number | Metric): void; +/** + * End the current web or background custom transaction. + * + * This method requires being in the correct transaction context when called. + */ +export function endTransaction(): void; - /** - * Update a metric that acts as a simple counter. - * - * The count of the selected metric will be incremented by the specified amount, defaulting to 1. - */ - incrementMetric(name: string, value?: number): void; +/** + * Record an event-based metric, usually associated with a particular duration. + * + * The `name` must be a string following standard metric naming rules. The `value` will + * usually be a number, but it can also be an object. + * * When `value` is a numeric value, it should represent the magnitude of a measurement + * associated with an event; for example, the duration for a particular method call. + * * When `value` is an object, it must contain count, total, min, max, and sumOfSquares + * keys, all with number values. This form is useful to aggregate metrics on your own + * and report them periodically; for example, from a setInterval. These values will + * be aggregated with any previously collected values for the same metric. The names + * of these keys match the names of the keys used by the platform API. + */ +export function recordMetric(name: string, value: number | Metric): void; - /** - * Record an event-based metric, usually associated with a particular duration. - * - * `eventType` must be an alphanumeric string less than 255 characters. - * The keys of `attributes` must be shorter than 255 characters. - */ - recordCustomEvent(eventType: string, attributes: { [keys: string]: boolean | number | string }): void; +/** + * Update a metric that acts as a simple counter. + * + * The count of the selected metric will be incremented by the specified amount, defaulting to 1. + */ +export function incrementMetric(name: string, value?: number): void; - /** - * Registers an instrumentation function. - * - * The provided onRequire callback will be fired when the given module is loaded with require. - * The moduleName parameter should be the string that will be passed to require; - * for example, 'express' or 'amqplib/callback_api'. - * - * The optional onError callback is called if the onRequire parameters throws an error. - * This is useful for debugging your instrumentation. - * - * Use this method to: - * - Add instrumentation for modules not currently instrumented by New Relic. - * - Instrument your own code. - * - Replace the Node.js agent's built-in instrumentation with your own. - */ - instrument: Instrument; +/** + * Record an event-based metric, usually associated with a particular duration. + * + * `eventType` must be an alphanumeric string less than 255 characters. + * The keys of `attributes` must be shorter than 255 characters. + */ +export function recordCustomEvent(eventType: string, attributes: { [keys: string]: boolean | number | string }): void; - /** - * Sets an instrumentation callback for a datastore module. - * - * This method is just like `instrument`, except it provides a datastore-service-specialized shim. - */ - instrumentDatastore: Instrument; +/** + * Registers an instrumentation function. + * + * The provided onRequire callback will be fired when the given module is loaded with require. + * The moduleName parameter should be the string that will be passed to require; + * for example, 'express' or 'amqplib/callback_api'. + * + * The optional onError callback is called if the onRequire parameters throws an error. + * This is useful for debugging your instrumentation. + * + * Use this method to: + * - Add instrumentation for modules not currently instrumented by New Relic. + * - Instrument your own code. + * - Replace the Node.js agent's built-in instrumentation with your own. + */ +export const instrument: Instrument; - /** - * Sets an instrumentation callback for a web framework module. - * - * This method is just like `instrument`, except it provides a web-framework-specialized shim. - */ - instrumentWebframework: Instrument; +/** + * Sets an instrumentation callback for a datastore module. + * + * This method is just like `instrument`, except it provides a datastore-service-specialized shim. + */ +export const instrumentDatastore: Instrument; - /** - * Sets an instrumentation callback for a message service client module. - * - * This method is just like `instrument`, except it provides a message-service-specialized shim. - */ - instrumentMessages: Instrument; +/** + * Sets an instrumentation callback for a web framework module. + * + * This method is just like `instrument`, except it provides a web-framework-specialized shim. + */ +export const instrumentWebframework: Instrument; - /** - * Gracefully shuts down the agent. - * - * If `collectPendingData` is true, the agent will send any pending data to the collector - * before shutting down. Defaults to `false`. - */ - shutdown(cb?: (error?: Error) => void): void; - shutdown(options?: { collectPendingData?: boolean, timeout?: number }, cb?: (error?: Error) => void): void; - } +/** + * Sets an instrumentation callback for a message service client module. + * + * This method is just like `instrument`, except it provides a message-service-specialized shim. + */ +export const instrumentMessages: Instrument; - interface Instrument { - (opts: { moduleName: string, onRequire: () => void, onError?: (err: Error) => void }): void; - (moduleName: string, onRequire: () => void, onError?: (err: Error) => void): void; - } +/** + * Gracefully shuts down the agent. + * + * If `collectPendingData` is true, the agent will send any pending data to the collector + * before shutting down. Defaults to `false`. + */ +export function shutdown(cb?: (error?: Error) => void): void; +export function shutdown(options?: { collectPendingData?: boolean, timeout?: number }, cb?: (error?: Error) => void): void; - interface Metric { - count: number; - total: number; - min: number; - max: number; - sumOfSquares: number; - } +export interface Instrument { + (opts: { moduleName: string, onRequire: () => void, onError?: (err: Error) => void }): void; + (moduleName: string, onRequire: () => void, onError?: (err: Error) => void): void; +} - interface TransactionHandle { - /** - * End the transaction. - */ - end(callback?: () => any): void; +export interface Metric { + count: number; + total: number; + min: number; + max: number; + sumOfSquares: number; +} - /** - * Mark the transaction to be ignored. - */ - ignore(): void; - } +export interface TransactionHandle { + /** + * End the transaction. + */ + end(callback?: () => any): void; + + /** + * Mark the transaction to be ignored. + */ + ignore(): void; } -declare const api: newrelic.NewRelicAPI; -export = api; diff --git a/types/newrelic/newrelic-tests.ts b/types/newrelic/newrelic-tests.ts index 3f99152c66..29eabfeb21 100644 --- a/types/newrelic/newrelic-tests.ts +++ b/types/newrelic/newrelic-tests.ts @@ -14,7 +14,9 @@ newrelic.setDispatcher("foo", "42"); // $ExpectType void newrelic.setControllerName("foo", "GET"); // $ExpectType void newrelic.addCustomAttribute("foo", "bar"); // $ExpectType void +newrelic.addCustomAttribute("foo", 42); // $ExpectType void newrelic.addCustomAttributes({ foo: "bar", baz: "bang" }); // $ExpectType void +newrelic.addCustomAttributes({ foo: "bar", baz: 42 }); // $ExpectType void newrelic.setIgnoreTransaction(true); // $ExpectType void diff --git a/types/next-redux-saga/index.d.ts b/types/next-redux-saga/index.d.ts new file mode 100644 index 0000000000..0366868d97 --- /dev/null +++ b/types/next-redux-saga/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for next-redux-saga 3.0 +// Project: https://github.com/bmealhouse/next-redux-saga +// Definitions by: Leo Cavalcante +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.0 + +import { ComponentType } from "react"; + +declare function nextReduxSaga

          (arg: { async: boolean }): ((BaseComponent: ComponentType

          ) => ComponentType

          ); +declare function nextReduxSaga

          (arg: ComponentType

          ): ComponentType

          ; + +export = nextReduxSaga; diff --git a/types/next-redux-saga/next-redux-saga-tests.tsx b/types/next-redux-saga/next-redux-saga-tests.tsx new file mode 100644 index 0000000000..c905971457 --- /dev/null +++ b/types/next-redux-saga/next-redux-saga-tests.tsx @@ -0,0 +1,65 @@ +import * as React from 'react'; +import withRedux from 'next-redux-wrapper'; +import withReduxSaga from 'next-redux-saga'; +import { createStore, Reducer, Store, AnyAction } from 'redux'; + +interface InitialState { + foo: string; +} + +const reducer: Reducer = (state: InitialState = { foo: '' }, action: AnyAction): InitialState => { + switch (action.type) { + case 'FOO': + return { ...state, foo: action.payload }; + default: + return state; + } +}; + +const makeStore = (initialState: InitialState): Store => { + return createStore(reducer, initialState); +}; + +interface OwnProps { + bar: string; +} + +interface Props { + foo: string; + custom: string; +} + +class Page extends React.Component { + static getInitialProps({ store, isServer, pathname, query }: any) { + store.dispatch({ type: 'FOO', payload: 'foo' }); + return { custom: 'custom' }; + } + render() { + return ( +

          +
          Prop from Redux {this.props.foo}
          +
          Prop from getInitialProps {this.props.custom}
          +
          + ); + } +} + +type ConnectStateProps = Props; +type DispatchProps = Props; +type MergedProps = Props; + +// Test various typings + +const Com1 = withRedux( + (initialState: InitialState, options) => { + if (options.isServer || options.req || options.query || options.res) { + const a = 1; + } + return createStore(reducer, initialState); + }, +)(withReduxSaga({ async: true })(Page)); + +const Com2 = withRedux(makeStore)(withReduxSaga(Page)); + +const com1Instance = (); +const com2Instance = (); diff --git a/types/next-redux-saga/package.json b/types/next-redux-saga/package.json new file mode 100644 index 0000000000..6d68bf2f9b --- /dev/null +++ b/types/next-redux-saga/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "redux": "^3.6.0" + } +} diff --git a/types/next-redux-saga/tsconfig.json b/types/next-redux-saga/tsconfig.json new file mode 100644 index 0000000000..2f57e82a4e --- /dev/null +++ b/types/next-redux-saga/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "next-redux-saga-tests.tsx" + ] +} diff --git a/types/next-redux-saga/tslint.json b/types/next-redux-saga/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/next-redux-saga/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} 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/next-server/asset.d.ts b/types/next-server/asset.d.ts new file mode 100644 index 0000000000..d021de3929 --- /dev/null +++ b/types/next-server/asset.d.ts @@ -0,0 +1,2 @@ +export function setAssetPrefix(url: string): void; +export default function(path: string): string; diff --git a/types/next-server/config.d.ts b/types/next-server/config.d.ts new file mode 100644 index 0000000000..d2cc3cf6e2 --- /dev/null +++ b/types/next-server/config.d.ts @@ -0,0 +1,6 @@ +export interface RuntimeConfig { + serverRuntimeConfig: any; + publicRuntimeConfig?: any; +} +export function setConfig(configValue: any): void; +export default function(): RuntimeConfig; diff --git a/types/next-server/constants.d.ts b/types/next-server/constants.d.ts new file mode 100644 index 0000000000..d2dc74dad0 --- /dev/null +++ b/types/next-server/constants.d.ts @@ -0,0 +1,23 @@ +export const PHASE_EXPORT: string; +export const PHASE_PRODUCTION_BUILD: string; +export const PHASE_PRODUCTION_SERVER: string; +export const PHASE_DEVELOPMENT_SERVER: string; +export const PAGES_MANIFEST: string; +export const BUILD_MANIFEST: string; +export const REACT_LOADABLE_MANIFEST: string; +export const SERVER_DIRECTORY: string; +export const CONFIG_FILE: string; +export const BUILD_ID_FILE: string; +export const BLOCKED_PAGES: string[]; + +export const CLIENT_STATIC_FILES_PATH: string; +export const CLIENT_STATIC_FILES_RUNTIME: string; +export const CLIENT_STATIC_FILES_RUNTIME_PATH: string; +/** static/runtime/main.js */ +export const CLIENT_STATIC_FILES_RUNTIME_MAIN: string; +/** static/runtime/webpack.js */ +export const CLIENT_STATIC_FILES_RUNTIME_WEBPACK: string; +/** matches static//pages/.js */ +export const IS_BUNDLED_PAGE_REGEX: RegExp; +/** matches static//pages/:page*.js */ +export const ROUTE_NAME_REGEX: RegExp; diff --git a/types/next-server/dynamic.d.ts b/types/next-server/dynamic.d.ts new file mode 100644 index 0000000000..38a85bf77e --- /dev/null +++ b/types/next-server/dynamic.d.ts @@ -0,0 +1,42 @@ +import * as React from "react"; +import { + LoadableComponent, + CommonOptions as LoadableOptions, + LoadingComponentProps as LoadableLoadingComponentProps +} from "react-loadable"; + +type Omit = Pick>; + +type AsyncComponent

          = Promise>; +type AsyncComponentLoader

          = () => AsyncComponent

          ; +type ModuleMapping = Record; +type LoadedModuleMapping = Record; + +interface NextDynamicOptions

          extends Omit { + modules?: () => ModuleMapping; // overridden + loading?: LoadableOptions["loading"]; // optional + loader?: AsyncComponentLoader

          ; // optional, overriden + render?: (props: P, loaded: LoadedModuleMapping) => React.ReactNode; // optional, overriden + ssr?: boolean; + loadableGenerated?: { + webpack?: any; + modules?: any; + }; +} + +type DynamicComponent

          = React.ComponentType

          & LoadableComponent; + +/** + * Overloaded dynamic function. + * https://github.com/zeit/next.js/blob/7.0.0/lib/dynamic.js#L55 + */ +declare function dynamic

          ( + options: AsyncComponent

          | NextDynamicOptions

          +): DynamicComponent

          ; +declare function dynamic

          ( + asyncModule: AsyncComponent

          , + options: NextDynamicOptions

          +): DynamicComponent

          ; + +export type LoadingComponentProps = LoadableLoadingComponentProps; +export default dynamic; diff --git a/types/next-server/head.d.ts b/types/next-server/head.d.ts new file mode 100644 index 0000000000..8a8be730f8 --- /dev/null +++ b/types/next-server/head.d.ts @@ -0,0 +1,8 @@ +import * as React from "react"; + +export function defaultHead(className?: string): JSX.Element[]; +export default class Head extends React.Component { + static canUseDOM: boolean; + static peek(): Array>; + static rewind(): Array>; +} diff --git a/types/next-server/index.d.ts b/types/next-server/index.d.ts new file mode 100644 index 0000000000..6e8fcd3ed6 --- /dev/null +++ b/types/next-server/index.d.ts @@ -0,0 +1,125 @@ +// Type definitions for next-server 7.0 +// Project: https://github.com/zeit/next.js/packages/next-server +// Definitions by: Drew Hays +// Brice BERNARD +// James Hegedus +// Resi Respati +// Scott Jones +// Joao Vieira +// AJ Livingston +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import * as http from "http"; +import { NextConfig } from "./next-config"; +import { UrlLike, DefaultQuery } from "./router"; + +declare namespace next { + interface RenderOptions { + staticMarkup: boolean; + distDir: string; + buildId: string; + generateETags: boolean; + runtimeConfig?: Record; + } + + /** + * Options passed to the Server constructor in Node.js. + */ + interface ServerOptions { + dev?: boolean; + dir?: string; + staticMarkup?: boolean; + quiet?: boolean; + conf?: NextConfig; + } + + interface ServerRoute

          { + match(pathname: string, params?: Partial

          ): P | false; + fn(req: http.IncomingMessage, res: http.ServerResponse, params: P, parsedUrl: UrlLike): Promise; + } + + interface ServerRouter { + routes: ServerRoute[]; + add(route: ServerRoute): void; + match(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): (() => Promise) | undefined; + } + + /** + * Next.js server instance API. + */ + interface Server { + dir: string; + quiet: boolean; + router: ServerRouter; + nextConfig: NextConfig; + distDir: string; + buildId: string; + renderOpts: RenderOptions; + + currentPhase(): string; + handleRequest( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl?: UrlLike + ): Promise; + getRequestHandler(): ( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl?: UrlLike + ) => Promise; + + setAssetPrefix(prefix: string): void; + prepare(): Promise; + close(): Promise; + setImmutableAssetCacheControl(res: http.ServerResponse): void; + generateRoutes(): ServerRoute[]; + run(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; + + render( + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: DefaultQuery, + parsedUrl?: UrlLike + ): Promise; + renderToHTML( + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: DefaultQuery + ): Promise; + renderError( + err: any, + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: DefaultQuery + ): Promise; + renderErrorToHTML( + err: any, + req: http.IncomingMessage, + res: http.ServerResponse, + pathname: string, + query?: DefaultQuery + ): Promise; + render404( + req: http.IncomingMessage, + res: http.ServerResponse, + parsedUrl?: UrlLike + ): Promise; + + serveStatic( + req: http.IncomingMessage, + res: http.ServerResponse, + path: string + ): Promise; + isServeableUrl(path: string): boolean; + readBuildId(): string; + } +} + +declare function next(options?: next.ServerOptions): next.Server; +export = next; diff --git a/types/next-server/link.d.ts b/types/next-server/link.d.ts new file mode 100644 index 0000000000..520868f05f --- /dev/null +++ b/types/next-server/link.d.ts @@ -0,0 +1,17 @@ +import * as url from "url"; +import * as React from "react"; +import { UrlLike } from "./router"; + +export interface LinkProps { + prefetch?: boolean; + shallow?: boolean; + scroll?: boolean; + replace?: boolean; + onError?(error: any): void; + href?: string | UrlLike; + as?: string | UrlLike; + passHref?: boolean; + children: React.ReactElement; +} + +export default class Link extends React.Component {} diff --git a/types/next-server/next-config.d.ts b/types/next-server/next-config.d.ts new file mode 100644 index 0000000000..5a542abf29 --- /dev/null +++ b/types/next-server/next-config.d.ts @@ -0,0 +1,23 @@ +/** + * Next.js config schema. + * https://github.com/zeit/next.js/blob/7.0.0/server/config.js#L9 + */ +export interface NextConfig { + webpack?: any; + webpackDevMiddleware?: any; + poweredByHeader?: boolean; + distDir?: string; + assetPrefix?: string; + configOrigin?: string; + useFileSystemPublicRoutes?: boolean; + generateBuildId?: () => string; + generateEtags?: boolean; + pageExtensions?: string[]; + publicRuntimeConfig?: object; + serverRuntimeConfig?: object; + + // Plugin can define their own keys. + [key: string]: any; +} + +export default function(phase: string, dir: string, customConfig?: NextConfig): NextConfig; diff --git a/types/next-server/router.d.ts b/types/next-server/router.d.ts new file mode 100644 index 0000000000..af946608df --- /dev/null +++ b/types/next-server/router.d.ts @@ -0,0 +1,100 @@ +import * as React from "react"; +import * as url from "url"; + +type EventName = + | "routeChangeStart" + | "routeChangeComplete" + | "routeChangeError" + | "beforeHistoryChange" + | "hashChangeStart" + | "hashChangeComplete"; + +interface RouteChangeError { + cancelled: boolean; +} + +type EventHandler = (url: string) => any; +type ErrorEventHandler = (err: RouteChangeError, url: string) => any; + +export type UrlLike = url.UrlObject | url.Url; + +export interface EventChangeOptions { + shallow?: boolean; + [key: string]: any; +} + +export type PopStateCallback = (state: any) => boolean | undefined; + +export type RouterCallback = () => void; + +export type DefaultQuery = Record; + +export interface RouterProps { + // url property fields + readonly pathname: string; + readonly route: string; + readonly asPath?: string; + readonly query?: Q; + + // property fields + readonly components: { + [key: string]: { Component: React.ComponentType; err: any }; + }; + + // core method fields + back(): void; + beforePopState(cb: PopStateCallback): boolean; + prefetch(url: string): Promise>; + push( + url: string | UrlLike, + as?: string | UrlLike, + options?: EventChangeOptions + ): Promise; + reload(route: string): Promise; + replace( + url: string | UrlLike, + as?: string | UrlLike, + options?: EventChangeOptions + ): Promise; + + // events (deprecated soonish) + onBeforeHistoryChange?(as: string): void; + onHashChangeStart?(url: string): void; + onHashChangeComplete?(url: string): void; + onRouteChangeComplete?(url: string): void; + onRouteChangeError?(error: RouteChangeError, url: string): void; + onRouteChangeStart?(url: string): void; + + // events API (6.1.1+) + readonly events: { + on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; + off: (eventName: EventName, handler: (url: string) => any) => void; + }; +} + +export interface SingletonRouter extends RouterProps { + router: RouterProps | null; + readyCallbacks: RouterCallback[]; + ready(cb: RouterCallback): void; +} + +export interface WithRouterProps { + router?: SingletonRouter; +} + +/** + * Remove properties `K` from `T`. + * + * @internal + */ +export type Omit = T extends any ? Pick> : never; + +// Manually disabling the no-unnecessary-generics rule so users can +// retain type inference if they wrap their component in withRouter +// without defining props explicitly +export function withRouter( + Component: React.ComponentType> +): React.ComponentType>>; + +declare const Router: SingletonRouter; +export default Router; diff --git a/types/next-server/test/next-server-constants-tests.ts b/types/next-server/test/next-server-constants-tests.ts new file mode 100644 index 0000000000..6ebade7c9f --- /dev/null +++ b/types/next-server/test/next-server-constants-tests.ts @@ -0,0 +1,30 @@ +import { + PHASE_DEVELOPMENT_SERVER, + IS_BUNDLED_PAGE_REGEX +} from "next-server/constants"; + +const isIndexPage = IS_BUNDLED_PAGE_REGEX.test( + "static/CjW0mFnyG80HdP4eSUiy7/pages/index.js" +); + +// Example taken from: https://github.com/cyrilwanner/next-compose-plugins/blob/a25b313899638912cc9defc0be072f4fe4a1e855/README.md +const config = (nextConfig: any = {}) => { + return { + ...nextConfig, + + // define in which phases this plugin should get applied. + // you can also use multiple phases or negate them. + // however, users can still overwrite them in their configuration if they really want to. + phases: [PHASE_DEVELOPMENT_SERVER], + + webpack(config: any, options: any) { + // do something here which only gets applied during development server phase + + if (typeof nextConfig.webpack === "function") { + return nextConfig.webpack(config, options); + } + + return config; + } + }; +}; diff --git a/types/next-server/test/next-server-dynamic-tests.tsx b/types/next-server/test/next-server-dynamic-tests.tsx new file mode 100644 index 0000000000..b6e0b86fe6 --- /dev/null +++ b/types/next-server/test/next-server-dynamic-tests.tsx @@ -0,0 +1,65 @@ +import * as React from "react"; +import dynamic, { LoadingComponentProps } from "next-server/dynamic"; + +// You'd typically do this via import('./MyComponent') +interface MyComponentProps { + foo: string; +} +const MyComponent: React.StatelessComponent = () =>

          I'm async!
          ; +const asyncComponent = Promise.resolve(MyComponent); + +// Examples from +// https://github.com/zeit/next.js/#dynamic-import + +const LoadingComponent: React.StatelessComponent = ({ + isLoading, + error +}) =>

          loading...

          ; + +// 1. Basic Usage (Also does SSR) +const DynamicComponent = dynamic(asyncComponent); +const dynamicComponentJSX = ; + +// 2. With Custom Loading Component +const DynamicComponentWithCustomLoading = dynamic(asyncComponent, { + loading: LoadingComponent +}); +const dynamicComponentWithCustomLoadingJSX = ; + +// 3. With No SSR +const DynamicComponentWithNoSSR = dynamic(asyncComponent, { + ssr: false +}); + +// 4. With Multiple Modules At Once +const HelloBundle = dynamic({ + modules: () => { + const components = { + Hello1: asyncComponent, + Hello2: asyncComponent + }; + + return components; + }, + render: (props, { Hello1, Hello2 }) => ( +
          +

          {props.foo}

          + + +
          + ) +}); +const helloBundleJSX = ; + +// 5. With plain Loadable options +const LoadableComponent = dynamic({ + loader: () => asyncComponent, + loading: LoadingComponent, + delay: 200, + timeout: 10000 +}); + +// 6. No loading +const DynamicComponentWithNoLoading = dynamic(asyncComponent, { + loading: () => null +}); diff --git a/types/next-server/test/next-server-head-tests.tsx b/types/next-server/test/next-server-head-tests.tsx new file mode 100644 index 0000000000..bea5643cad --- /dev/null +++ b/types/next-server/test/next-server-head-tests.tsx @@ -0,0 +1,11 @@ +import Head, * as head from "next-server/head"; +import * as React from "react"; + +const elements: JSX.Element[] = head.defaultHead(); +const jsx = {elements}; + +if (!Head.canUseDOM) { + Head.rewind().map(x => [x.key, x.props, x.type]); +} + +Head.peek().map(x => [x.key, x.props, x.type]); diff --git a/types/next-server/test/next-server-link-tests.tsx b/types/next-server/test/next-server-link-tests.tsx new file mode 100644 index 0000000000..3d34ac54b4 --- /dev/null +++ b/types/next-server/test/next-server-link-tests.tsx @@ -0,0 +1,23 @@ +import Link from "next-server/link"; +import * as React from "react"; + +const links = ( +
          + { + console.log("Handled error!", e); + }} + prefetch + replace + scroll + shallow + > + Gotta link to somewhere! + + + All props are optional! + +
          +); diff --git a/types/next-server/test/next-server-router-tests.tsx b/types/next-server/test/next-server-router-tests.tsx new file mode 100644 index 0000000000..356a3be559 --- /dev/null +++ b/types/next-server/test/next-server-router-tests.tsx @@ -0,0 +1,157 @@ +import Router, { withRouter, WithRouterProps } from "next-server/router"; +import * as React from "react"; +import * as qs from "querystring"; + +Router.readyCallbacks.push(() => { + console.log("I'll get called when the router initializes."); +}); +Router.ready(() => { + console.log( + "I'll get called immediately if the router initializes, or when it eventually does.", + ); +}); + +// Access readonly properties of the router. + +Object.keys(Router.components).forEach(key => { + const c = Router.components[key]; + c.err.isAnAny; + + return ; +}); + +function split(routeLike: string) { + routeLike.split("/").forEach(part => { + console.log("path part: ", part); + }); +} + +if (Router.asPath) { + split(Router.asPath); + split(Router.asPath); +} + +split(Router.pathname); + +const query = `?${qs.stringify(Router.query)}`; + +// Assign some callback methods. +Router.events.on('routeChangeStart', (url: string) => console.log("Route is starting to change.", url)); +Router.events.on('beforeHistoryChange', (as: string) => console.log("History hasn't changed yet.", as)); +Router.events.on('routeChangeComplete', (url: string) => console.log("Route change is complete.", url)); +Router.events.on('routeChangeError', (err: any, url: string) => console.log("Route change errored.", err, url)); + +// Call methods on the router itself. +Router.reload("/route").then(() => console.log("route was reloaded")); +Router.back(); +Router.beforePopState(({ url }) => !!url); + +Router.push("/route").then((success: boolean) => + console.log("route push success: ", success), +); +Router.push("/route", "/asRoute").then((success: boolean) => + console.log("route push success: ", success), +); +Router.push("/route", "/asRoute", { shallow: false }).then((success: boolean) => + console.log("route push success: ", success), +); + +Router.replace("/route").then((success: boolean) => + console.log("route replace success: ", success), +); +Router.replace("/route", "/asRoute").then((success: boolean) => + console.log("route replace success: ", success), +); +Router.replace("/route", "/asRoute", { + shallow: false, +}).then((success: boolean) => console.log("route replace success: ", success)); + +Router.prefetch("/route").then(Component => { + const element = ; +}); + +interface TestComponentProps extends WithRouterProps { + testValue: string; +} + +class TestComponent extends React.Component { + state = { ready: false }; + + constructor(props: TestComponentProps) { + super(props); + if (props.router) { + props.router.ready(() => { + this.setState({ ready: true }); + }); + } + } + + render() { + return ( +
          +

          {this.state.ready ? 'Ready' : 'Not Ready'}

          +

          Route: {this.props.router ? this.props.router.route : ""}

          +

          Another prop: {this.props.testValue}

          +
          + ); + } +} + +withRouter(TestComponent); + +interface TestComponent2Props extends WithRouterProps { + testValue: string; +} + +class TestComponent2 extends React.Component { + state = { ready: false }; + + constructor(props: TestComponent2Props) { + super(props); + if (props.router) { + props.router.ready(() => { + this.setState({ ready: true }); + }); + } + } + + render() { + return ( +
          +

          {this.state.ready ? 'Ready' : 'Not Ready'}

          +

          Route: {this.props.router ? this.props.router.route : ""}

          +

          Another prop: {this.props.testValue}

          +
          + ); + } +} + +const TestComponent2WithRouter = withRouter(TestComponent2); +const res = ; + +interface TestSFCQuery { + test?: string; +} + +interface TestSFCProps extends WithRouterProps { + testProp: string; +} + +const TestSFC: React.SFC = ({ router }) => { + return
          {router && router.query && router.query.test}
          ; +}; +const TestSFCComponent = withRouter(TestSFC); + +const res2 = ; + +const TestSFC2 = withRouter(({ router }) => { + return
          {router && router.query && router.query.test}
          ; +}); + +const res3 = ; + +const TestSFC3 = withRouter(({ router }) => { + return
          {router && router.query && router.query.test}
          ; +}); + +const res4 = ; diff --git a/types/next-server/test/next-server-tests.ts b/types/next-server/test/next-server-tests.ts new file mode 100644 index 0000000000..7b4bfcca74 --- /dev/null +++ b/types/next-server/test/next-server-tests.ts @@ -0,0 +1,92 @@ +import createServer = require("next-server"); +import * as http from "http"; +import * as url from "url"; + +const defaultServer: createServer.Server = createServer(); +const server = createServer({ + dir: "..", + quiet: true, + conf: { + distDir: "./dist", + useFileSystemPublicRoutes: false, + anotherProperty: { + key: true + } + } +}); + +const devServer = createServer({ + dev: true, + dir: "..", + quiet: true, + conf: { + distDir: "./dist", + useFileSystemPublicRoutes: false, + anotherProperty: { + key: true + } + } +}); + +const { + dir, + quiet, + router, + nextConfig, + distDir, + buildId + } = server; + const { assetPrefix } = nextConfig; + const voidFunc = () => {}; + +server.prepare().then(voidFunc); +server.close().then(voidFunc); + +const parsedUrl = url.parse("https://www.example.com"); +const handler = server.getRequestHandler(); + +function handle(req: http.IncomingMessage, res: http.ServerResponse) { + handler(req, res); + handler(req, res, parsedUrl).then(voidFunc); + server.run(req, res, parsedUrl).then(voidFunc); + + server.render(req, res, "/path/to/resource").then(voidFunc); + server.render(req, res, "/path/to/resource", {}, parsedUrl).then(voidFunc); + server + .render(req, res, "/path/to/resource", { key: "value" }, parsedUrl) + .then(voidFunc); + server + .renderError(new Error(), req, res, "/path/to/resource") + .then(voidFunc); + server + .renderError(new Error(), req, res, "/path/to/resource", { + key: "value", + }) + .then(voidFunc); + server + .renderError( + "this can be an error, too!", + req, + res, + "/path/to/resource", + { key: "value" }, + ) + .then(voidFunc); + server.render404(req, res, parsedUrl).then(voidFunc); + + server + .renderToHTML(req, res, "/path/to/resource", { foo: "bar" }) + .then(x => x.split("\n")); + server + .renderErrorToHTML(new Error(), req, res, "/path/to/resource", { + foo: "bar", + }) + .then(x => x.split("\n")); + + server.serveStatic(req, res, "/path/to/thing").then(voidFunc); + + let b: boolean; + b = server.isServeableUrl("/path/to/thing"); + + const s: string = server.readBuildId(); +} diff --git a/types/next-server/tsconfig.json b/types/next-server/tsconfig.json new file mode 100644 index 0000000000..4d72dadef2 --- /dev/null +++ b/types/next-server/tsconfig.json @@ -0,0 +1,38 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "asset.d.ts", + "config.d.ts", + "constants.d.ts", + "dynamic.d.ts", + "head.d.ts", + "link.d.ts", + "next-config.d.ts", + "router.d.ts", + "test/next-server-tests.ts", + "test/next-server-constants-tests.ts", + "test/next-server-head-tests.tsx", + "test/next-server-link-tests.tsx", + "test/next-server-dynamic-tests.tsx", + "test/next-server-router-tests.tsx" + ] +} diff --git a/types/next-server/tslint.json b/types/next-server/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/next-server/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/next/config.d.ts b/types/next/config.d.ts index 8466b60a4f..f9fea12cbd 100644 --- a/types/next/config.d.ts +++ b/types/next/config.d.ts @@ -1 +1,2 @@ -export default function(): { serverRuntimeConfig: any; publicRuntimeConfig: any }; +export * from 'next-server/config'; +export { default } from 'next-server/config'; diff --git a/types/next/constants.d.ts b/types/next/constants.d.ts new file mode 100644 index 0000000000..d0d2e2361e --- /dev/null +++ b/types/next/constants.d.ts @@ -0,0 +1 @@ +export * from 'next-server/constants'; diff --git a/types/next/document.d.ts b/types/next/document.d.ts index b76ed7b2b0..9ac8985cdf 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -37,7 +37,7 @@ export interface NextDocumentContext exte * https://github.com/zeit/next.js/blob/7.0.0/server/document.js#L16 */ export interface DefaultDocumentIProps extends RenderPageResponse { - styles?: Array>; + styles?: React.ReactNode; } /** @@ -55,6 +55,7 @@ export interface DocumentProps { runtimeConfig?: any; nextExport?: boolean; err?: any; + [key: string]: any; }; dev: boolean; dir?: string; @@ -104,5 +105,7 @@ export class NextScript extends React.Component {} export default class Document

          extends React.Component< P & DefaultDocumentIProps & DocumentProps > { - static getInitialProps(context: NextDocumentContext): DefaultDocumentIProps; + static getInitialProps( + context: NextDocumentContext + ): DefaultDocumentIProps | Promise; } diff --git a/types/next/dynamic.d.ts b/types/next/dynamic.d.ts index 38a85bf77e..0b10e6238e 100644 --- a/types/next/dynamic.d.ts +++ b/types/next/dynamic.d.ts @@ -1,42 +1,2 @@ -import * as React from "react"; -import { - LoadableComponent, - CommonOptions as LoadableOptions, - LoadingComponentProps as LoadableLoadingComponentProps -} from "react-loadable"; - -type Omit = Pick>; - -type AsyncComponent

          = Promise>; -type AsyncComponentLoader

          = () => AsyncComponent

          ; -type ModuleMapping = Record; -type LoadedModuleMapping = Record; - -interface NextDynamicOptions

          extends Omit { - modules?: () => ModuleMapping; // overridden - loading?: LoadableOptions["loading"]; // optional - loader?: AsyncComponentLoader

          ; // optional, overriden - render?: (props: P, loaded: LoadedModuleMapping) => React.ReactNode; // optional, overriden - ssr?: boolean; - loadableGenerated?: { - webpack?: any; - modules?: any; - }; -} - -type DynamicComponent

          = React.ComponentType

          & LoadableComponent; - -/** - * Overloaded dynamic function. - * https://github.com/zeit/next.js/blob/7.0.0/lib/dynamic.js#L55 - */ -declare function dynamic

          ( - options: AsyncComponent

          | NextDynamicOptions

          -): DynamicComponent

          ; -declare function dynamic

          ( - asyncModule: AsyncComponent

          , - options: NextDynamicOptions

          -): DynamicComponent

          ; - -export type LoadingComponentProps = LoadableLoadingComponentProps; -export default dynamic; +export * from 'next-server/dynamic'; +export { default } from 'next-server/dynamic'; diff --git a/types/next/error.d.ts b/types/next/error.d.ts index 09d7e31860..8ad2226f07 100644 --- a/types/next/error.d.ts +++ b/types/next/error.d.ts @@ -10,5 +10,5 @@ export interface DefaultErrorIProps { } export default class Error

          extends React.Component

          { - static getInitialProps(context: NextContext): DefaultErrorIProps; + static getInitialProps(context: NextContext): Promise | DefaultErrorIProps; } diff --git a/types/next/head.d.ts b/types/next/head.d.ts index d46b371d11..616f88775c 100644 --- a/types/next/head.d.ts +++ b/types/next/head.d.ts @@ -1,8 +1,2 @@ -import * as React from "react"; - -export function defaultHead(): JSX.Element[]; -export default class Head extends React.Component { - static canUseDOM: boolean; - static peek(): Array>; - static rewind(): Array>; -} +export * from 'next-server/head'; +export { default } from 'next-server/head'; diff --git a/types/next/index.d.ts b/types/next/index.d.ts index d788ddd941..4dc0b49d07 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -1,11 +1,12 @@ // Type definitions for next 7.0 -// Project: https://github.com/zeit/next.js +// Project: https://github.com/zeit/next.js/packages/next // Definitions by: Drew Hays // Brice BERNARD // James Hegedus // Resi Respati // Scott Jones // Joao Vieira +// AJ Livingston // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -13,10 +14,18 @@ import * as http from "http"; import * as url from "url"; +import { Server as NextServer, ServerOptions as NextServerOptions, RenderOptions } from 'next-server'; +import { NextConfig as NextServerConfig } from 'next-server/next-config'; import { Response as NodeResponse } from "node-fetch"; import { SingletonRouter, DefaultQuery, UrlLike } from "./router"; declare namespace next { + // Moved to next-server + type NextConfig = NextServerConfig; + type Server = NextServer; + type ServerOptions = NextServerOptions; + // End Moved to next-server + // Deprecated type QueryStringMapObject = DefaultQuery; type ServerConfig = NextConfig; @@ -47,126 +56,21 @@ declare namespace next { } /** - * Next.js config schema. - * https://github.com/zeit/next.js/blob/7.0.0/server/config.js#L9 + * Next.js dev server instance API. */ - interface NextConfig { - webpack?: any; - webpackDevMiddleware?: any; - poweredByHeader?: boolean; - distDir?: string; - assetPrefix?: string; - configOrigin?: string; - useFileSystemPublicRoutes?: boolean; - generateBuildId?: () => string; - generateEtags?: boolean; - pageExtensions?: string[]; - publicRuntimeConfig?: object; - serverRuntimeConfig?: object; - - // Plugin can define their own keys. - [key: string]: any; - } - - /** - * Options passed to the Server constructor in Node.js. - * https://github.com/zeit/next.js/blob/7.0.0/server/index.js#L25 - */ - interface ServerOptions { - dir?: string; - dev?: boolean; - staticMarkup?: boolean; - quiet?: boolean; - conf?: NextConfig; - } - - /** - * Next.js server instance API. - */ - interface Server { - // From constructor - // https://github.com/zeit/next.js/blob/7.0.0/server/index.js#L25 - dir: string; - dev: boolean; - quiet: boolean; - router: SingletonRouter; - http: null | http.Server; - nextConfig: NextConfig; - distDir: string; - buildId: string; + interface DevServer extends Server { hotReloader: any; - renderOpts: { - dev: string; - staticMarkup: boolean; - distDir: string; + renderOpts: RenderOptions & { + dev: true; hotReloader: any; - buildId: string; - generateETags: boolean; - runtimeConfig?: object; }; getHotReloader( dir: string, options: { quiet: boolean; config: NextConfig; buildId: string } ): any; - handleRequest( - req: http.IncomingMessage, - res: http.ServerResponse, - parsedUrl?: UrlLike - ): Promise; - getRequestHandler(): ( - req: http.IncomingMessage, - res: http.ServerResponse, - parsedUrl?: UrlLike - ) => Promise; - setAssetPrefix(prefix: string): void; - prepare(): Promise; - close(): Promise; - defineRoutes(): Promise; - start(): Promise; - run(req: http.IncomingMessage, res: http.ServerResponse, parsedUrl: UrlLike): Promise; - - render( - req: http.IncomingMessage, - res: http.ServerResponse, - pathname: string, - query?: DefaultQuery, - parsedUrl?: UrlLike - ): Promise; - renderToHTML( - req: http.IncomingMessage, - res: http.ServerResponse, - pathname: string, - query?: DefaultQuery - ): Promise; - renderError( - err: any, - req: http.IncomingMessage, - res: http.ServerResponse, - pathname: string, - query?: DefaultQuery - ): Promise; - renderErrorToHTML( - err: any, - req: http.IncomingMessage, - res: http.ServerResponse, - pathname: string, - query?: DefaultQuery - ): Promise; - render404( - req: http.IncomingMessage, - res: http.ServerResponse, - parsedUrl?: UrlLike - ): Promise; - - serveStatic( - req: http.IncomingMessage, - res: http.ServerResponse, - path: string - ): Promise; - isServeableUrl(path: string): boolean; - readBuildId(): string; + addExportPathMapRoutes(): Promise; getCompilationError(): Promise; } @@ -214,5 +118,6 @@ declare namespace next { } } +declare function next(options?: next.ServerOptions & { dev: true }): next.DevServer; declare function next(options?: next.ServerOptions): next.Server; export = next; diff --git a/types/next/link.d.ts b/types/next/link.d.ts index 12e3ee5419..04c383e914 100644 --- a/types/next/link.d.ts +++ b/types/next/link.d.ts @@ -1,21 +1,8 @@ -import * as url from "url"; -import * as React from "react"; -import { UrlLike } from "./router"; +import { LinkProps } from 'next-server/link'; // Deprecated export type LinkState = LinkProps; // End Deprecated -export interface LinkProps { - prefetch?: boolean; - shallow?: boolean; - scroll?: boolean; - replace?: boolean; - onError?(error: any): void; - href?: string | UrlLike; - as?: string | UrlLike; - passHref?: boolean; - children: React.ReactElement; -} - -export default class Link extends React.Component {} +export * from 'next-server/link'; +export { default } from 'next-server/link'; diff --git a/types/next/router.d.ts b/types/next/router.d.ts index 4232f356c9..8fd3df698b 100644 --- a/types/next/router.d.ts +++ b/types/next/router.d.ts @@ -1,95 +1,2 @@ -import * as React from "react"; -import * as url from "url"; - -type EventName = - | "routeChangeStart" - | "routeChangeComplete" - | "routeChangeError" - | "beforeHistoryChange" - | "hashChangeStart" - | "hashChangeComplete"; - -interface RouteChangeError { - cancelled: boolean; -} - -type EventHandler = (url: string) => any; -type ErrorEventHandler = (err: RouteChangeError, url: string) => any; - -export type UrlLike = url.UrlObject | url.Url; - -export interface EventChangeOptions { - shallow?: boolean; - [key: string]: any; -} - -export type PopStateCallback = (state: any) => boolean | undefined; - -export type RouterCallback = () => void; - -export type DefaultQuery = Record; - -export interface RouterProps { - // url property fields - readonly pathname: string; - readonly route: string; - readonly asPath?: string; - readonly query?: Q; - - // property fields - readonly components: { - [key: string]: { Component: React.ComponentType; err: any }; - }; - - // core method fields - back(): void; - beforePopState(cb: PopStateCallback): boolean; - prefetch(url: string): Promise>; - push( - url: string | UrlLike, - as?: string | UrlLike, - options?: EventChangeOptions - ): Promise; - reload(route: string): Promise; - replace( - url: string | UrlLike, - as?: string | UrlLike, - options?: EventChangeOptions - ): Promise; - - // events (deprecated soonish) - onAppUpdated?(nextRoute: string): void; - onBeforeHistoryChange?(as: string): void; - onHashChangeStart?(url: string): void; - onHashChangeComplete?(url: string): void; - onRouteChangeComplete?(url: string): void; - onRouteChangeError?(error: RouteChangeError, url: string): void; - onRouteChangeStart?(url: string): void; - - // events API (6.1.1+) - readonly events: { - on: (eventName: EventName, handler: EventHandler | ErrorEventHandler) => void; - off: (eventName: EventName, handler: (url: string) => any) => void; - }; -} - -export interface SingletonRouter extends RouterProps { - router: RouterProps | null; - readyCallbacks: RouterCallback[]; - ready(cb: RouterCallback): void; -} - -export interface WithRouterProps { - router: SingletonRouter; -} - -// Manually disabling the no-unnecessary-generics rule so users can -// retain type inference if they warp their component in withRouter -// without defining props explicitly -export function withRouter( - // tslint:disable-next-line:no-unnecessary-generics - Component: React.ComponentType> -): React.ComponentType; - -declare const Router: SingletonRouter; -export default Router; +export * from 'next-server/router'; +export { default } from 'next-server/router'; diff --git a/types/next/test/next-constants-tests.ts b/types/next/test/next-constants-tests.ts new file mode 100644 index 0000000000..64413ea97c --- /dev/null +++ b/types/next/test/next-constants-tests.ts @@ -0,0 +1,30 @@ +import { + PHASE_DEVELOPMENT_SERVER, + IS_BUNDLED_PAGE_REGEX +} from "next/constants"; + +const isIndexPage = IS_BUNDLED_PAGE_REGEX.test( + "static/CjW0mFnyG80HdP4eSUiy7/pages/index.js" +); + +// Example taken from: https://github.com/cyrilwanner/next-compose-plugins/blob/a25b313899638912cc9defc0be072f4fe4a1e855/README.md +const config = (nextConfig: any = {}) => { + return { + ...nextConfig, + + // define in which phases this plugin should get applied. + // you can also use multiple phases or negate them. + // however, users can still overwrite them in their configuration if they really want to. + phases: [PHASE_DEVELOPMENT_SERVER], + + webpack(config: any, options: any) { + // do something here which only gets applied during development server phase + + if (typeof nextConfig.webpack === "function") { + return nextConfig.webpack(config, options); + } + + return config; + } + }; +}; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index d25b340e64..bf7ccf036d 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,4 +1,5 @@ import Document, { + DocumentProps, Enhancer, Head, Main, @@ -12,6 +13,27 @@ interface WithUrlProps { url: string; } +class MyDocumentDefault extends Document { + static async getInitialProps(ctx: NextDocumentContext) { + const initialProps = await Document.getInitialProps(ctx); + return { ...initialProps }; + } + + render() { + return ( + + + + + +

          + + + + ); + } +} + class MyDoc extends Document { static getInitialProps({ req, renderPage }: NextDocumentContext) { // without callback @@ -29,6 +51,14 @@ class MyDoc extends Document { return { html, head, buildManifest, styles, url }; } + constructor(props: WithUrlProps & DocumentProps) { + super(props); + const { __NEXT_DATA__, url } = props; + + // Custom __NEXT_DATA__ attribute + __NEXT_DATA__.url = url; + } + render() { const { pathname, query } = this.props.__NEXT_DATA__; diff --git a/types/next/test/next-router-tests.tsx b/types/next/test/next-router-tests.tsx index 04fa50b912..28602ef097 100644 --- a/types/next/test/next-router-tests.tsx +++ b/types/next/test/next-router-tests.tsx @@ -79,16 +79,18 @@ class TestComponent extends React.Component { - this.setState({ ready: true }); - }); + if (props.router) { + props.router.ready(() => { + this.setState({ ready: true }); + }); + } } render() { return (

          {this.state.ready ? 'Ready' : 'Not Ready'}

          -

          Route: {this.props.router.route}

          +

          Route: {this.props.router ? this.props.router.route : ""}

          Another prop: {this.props.testValue}

          ); @@ -104,5 +106,5 @@ interface TestSFCQuery { interface TestSFCProps extends WithRouterProps { } const TestSFC: React.SFC = ({ router }) => { - return
          {router.query && router.query.test}
          ; + return
          {router && router.query && router.query.test}
          ; }; diff --git a/types/next/test/next-tests.ts b/types/next/test/next-tests.ts index 646b110c0d..3c8a403e46 100644 --- a/types/next/test/next-tests.ts +++ b/types/next/test/next-tests.ts @@ -15,9 +15,21 @@ const server = createServer({ } }); +const devServer = createServer({ + dev: true, + dir: "..", + quiet: true, + conf: { + distDir: "./dist", + useFileSystemPublicRoutes: false, + anotherProperty: { + key: true + } + } +}); + const { dir, - dev, quiet, router, nextConfig, @@ -29,8 +41,6 @@ const { server.prepare().then(voidFunc); server.close().then(voidFunc); -server.defineRoutes().then(voidFunc); -server.start().then(voidFunc); const parsedUrl = url.parse("https://www.example.com"); const handler = server.getRequestHandler(); @@ -79,5 +89,5 @@ function handle(req: http.IncomingMessage, res: http.ServerResponse) { b = server.isServeableUrl("/path/to/thing"); const s: string = server.readBuildId(); - server.getCompilationError().then(err => err.thisIsAnAny); + devServer.getCompilationError().then(err => err.thisIsAnAny); } diff --git a/types/next/tsconfig.json b/types/next/tsconfig.json index 125953fcd6..9981affbd3 100644 --- a/types/next/tsconfig.json +++ b/types/next/tsconfig.json @@ -20,6 +20,7 @@ }, "files": [ "index.d.ts", + "constants.d.ts", "app.d.ts", "document.d.ts", "dynamic.d.ts", @@ -29,6 +30,7 @@ "router.d.ts", "config.d.ts", "test/next-tests.ts", + "test/next-constants-tests.ts", "test/next-app-tests.tsx", "test/next-error-tests.tsx", "test/next-head-tests.tsx", diff --git a/types/ng-cordova/file.d.ts b/types/ng-cordova/file.d.ts index 8ebe777c14..c6c71972b4 100644 --- a/types/ng-cordova/file.d.ts +++ b/types/ng-cordova/file.d.ts @@ -36,7 +36,10 @@ declare namespace ngCordova { } export interface IFilePromise extends ng.IPromise { - then(successCallback: (promiseValue: T) => ng.IPromise | TResult, errorCallback?: (error: IFileError) => ng.IPromise | TResult): ng.IPromise; + then( + successCallback: (promiseValue: T) => ng.IPromise | TResult, + errorCallback?: (error: IFileError) => ng.IPromise | TResult2 + ): ng.IPromise; catch(onRejected: (error: IFileError) => ng.IPromise | TResult): ng.IPromise; } diff --git a/types/ng-cordova/fileTransfer.d.ts b/types/ng-cordova/fileTransfer.d.ts index e4ef359c14..9c1d8bf3c2 100644 --- a/types/ng-cordova/fileTransfer.d.ts +++ b/types/ng-cordova/fileTransfer.d.ts @@ -14,7 +14,11 @@ declare namespace ngCordova { } export interface IFileTransferPromise extends ng.IPromise { - then(successCallback: (promiseValue: T) => ng.IPromise | TResult, errorCallback?: (error: FileTransferError) => ng.IPromise | TResult, notifyCallback?: (state: any) => any): ng.IPromise; + then( + successCallback: (promiseValue: T) => ng.IPromise | TResult, + errorCallback?: (error: FileTransferError) => ng.IPromise | TResult2, + notifyCallback?: (state: any) => any + ): ng.IPromise; catch(onRejected: (error: FileTransferError) => ng.IPromise | TResult): ng.IPromise; } 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/ng-tags-input/tsconfig.json b/types/ng-tags-input/tsconfig.json index 42a59350cb..09cfc54e25 100644 --- a/types/ng-tags-input/tsconfig.json +++ b/types/ng-tags-input/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/ngeohash/index.d.ts b/types/ngeohash/index.d.ts index 25c8f29e5b..7fa05a0f4e 100644 --- a/types/ngeohash/index.d.ts +++ b/types/ngeohash/index.d.ts @@ -12,7 +12,7 @@ declare namespace ngeohash { type GeographicBoundingBox = [number, number, number, number]; type NSEW = [number, number]; - function encode(latitude: number, longitude: number, precision?: number): string; + function encode(latitude: number | string, longitude: number | string, precision?: number): string; function decode(hashstring: string): GeographicPoint; function decode_bbox(hashstring: string): GeographicBoundingBox; function bboxes(minlat: number, minlon: number, maxlat: number, maxlon: number, precision?: number): Array; diff --git a/types/ngeohash/ngeohash-tests.ts b/types/ngeohash/ngeohash-tests.ts index 34ad34d7cf..5c77ae94df 100644 --- a/types/ngeohash/ngeohash-tests.ts +++ b/types/ngeohash/ngeohash-tests.ts @@ -1,6 +1,7 @@ import geohash = require('ngeohash'); console.log(geohash.encode(37.8324, 112.5584)); +console.log(geohash.encode('37.8324', '112.5584')); // prints ww8p1r4t8 var latlon = geohash.decode('ww8p1r4t8'); diff --git a/types/ngprogress/ngprogress-tests.ts b/types/ngprogress/ngprogress-tests.ts index e250e9cb0e..f27bf8bf17 100644 --- a/types/ngprogress/ngprogress-tests.ts +++ b/types/ngprogress/ngprogress-tests.ts @@ -1,7 +1,7 @@ -var ngProgress: NgProgress.INgProgress = {}; +declare const ngProgress: NgProgress.INgProgress; ngProgress.start(); ngProgress.height('10px'); diff --git a/types/nightmare/nightmare-tests.ts b/types/nightmare/nightmare-tests.ts index d49d8b5932..5d6da26d2a 100644 --- a/types/nightmare/nightmare-tests.ts +++ b/types/nightmare/nightmare-tests.ts @@ -17,7 +17,7 @@ new Nightmare() .click('.searchsubmit') .wait('.url.breadcrumb') .evaluate(() => { - return (document.querySelector('.url.breadcrumb')).innerText; + return (document.querySelector('.url.breadcrumb') as HTMLElement).innerText; }, (breadcrumb: string) => { // expect(breadcrumb).to.equal('github.com'); }) @@ -165,7 +165,7 @@ new Nightmare() .goto('http://validator.w3.org/#validate_by_upload') .upload('#uploaded_file', 'test/files/jquery-2.1.1.min.js') .evaluate(function () { - return (document.getElementById('uploaded_file')).value; + return (document.getElementById('uploaded_file') as HTMLInputElement).value; }, function (value) { }) .run(done); @@ -214,7 +214,7 @@ new Nightmare() var seconds = function () { var gifs = document.querySelectorAll('img'); - var split = (gifs[gifs.length - 2]).src.split('.gif')[0]; + var split = (gifs[gifs.length - 2] as HTMLImageElement).src.split('.gif')[0]; var seconds = split.split('.com/c')[1]; return parseInt(seconds, 10); }; @@ -319,7 +319,7 @@ new Nightmare() .headers(headers) .goto('http://httpbin.org/headers') .evaluate(function () { - return (document.body.children[0]).innerHTML; + return (document.body.children[0] as HTMLElement).innerHTML; }, function (data: string) { }) .run(done); diff --git a/types/nightwatch/index.d.ts b/types/nightwatch/index.d.ts index b6930fe90a..01e1d99aa6 100644 --- a/types/nightwatch/index.d.ts +++ b/types/nightwatch/index.d.ts @@ -2,10 +2,11 @@ // Project: http://nightwatchjs.org/api // Definitions by: Rahul Kavalapara // Connor Schlesiger +// Clayton Astrom // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export interface NightwatchCustomPageObjects { - page: {[name: string]: () => NightwatchBrowser}; + page: {[name: string]: () => EnhancedPageObject}; } export interface NightwatchDesiredCapabilities { @@ -775,41 +776,13 @@ export interface NightwatchKeys { "COMMAND": string; } -export interface NightwatchAPI { +export interface NightwatchAPI extends SharedFunctions { assert: NightwatchAssertions; expect: Expect; verify: NightwatchAssertions; - /** - * Clear a textarea or a text input element's value. Uses elementIdValue protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.clearValue('input[type=text]'); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - */ - clearValue(selector: string, callback?: () => void): this; - - /** - * Simulates a click event on the given DOM element. Uses elementIdClick protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.click("#main ul li a.first"); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - */ - click(selector: string, callback?: () => void): this; - /** * Close the current window. This can be useful when you're working with multiple windows open (e.g. an OAuth login). Uses window protocol command. * @@ -867,26 +840,6 @@ export interface NightwatchAPI { */ end(callback?: () => void): this; - /** - * Retrieve the value of an attribute for a given DOM element. Uses elementIdAttribute protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.getAttribute("#main ul li a.first", "href", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, "#home"); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param attribute: The attribute name to inspect. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The value of the attribute - */ - getAttribute(selector: string, attribute: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** * Retrieve a single cookie visible to the current page. The cookie is returned as a cookie JSON object, as defined here. * Uses cookie protocol command. @@ -924,87 +877,6 @@ export interface NightwatchAPI { */ getCookies(callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** - * Retrieve the value of a css property for a given DOM element. Uses elementIdCssProperty protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.getCssProperty("#main ul li a.first", "display", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, 'inline'); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param cssProperty: The CSS property to inspect. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The value of the css property - */ - getCssProperty(selector: string, cssProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - - /** - * Determine an element's size in pixels. Uses elementIdSize protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.getElementSize("#main ul li a.first", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value.width, 500); - * this.assert.equal(result.value.height, 20); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The width and height of the element in pixels - */ - getElementSize(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - - /** - * Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. - * The element's coordinates are returned as a JSON object with x and y properties. Uses elementIdLocation protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.getLocation("#main ul li a.first", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value.x, 200); - * this.assert.equal(result.value.y, 200); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The X and Y coordinates for the element on the page - */ - getLocation(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - - /** - * Determine an element's location on the screen once it has been scrolled into view. Uses elementIdLocationInView protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.getLocationInView("#main ul li a.first", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value.x, 200); - * this.assert.equal(result.value.y, 200); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The X and Y coordinates for the element on the page. - */ - getLocationInView(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** * Gets a log from selenium * @@ -1040,44 +912,6 @@ export interface NightwatchAPI { */ getLogTypes(callback?: (result: NightwatchCallbackResult) => void): this; - /** - * Query for an element's tag name. Uses elementIdName protocol command. - * - * Usage: - * ``` - * this.demoTest = function (client) { - * client.getTagName("#main ul li .first", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, "a"); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The element's tag name, as a lowercase string. - */ - getTagName(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - - /** - * Returns the visible text for the element. Uses elementIdText protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.getText("#main ul li a.first", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, "nightwatchjs.org"); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The element's visible text. - */ - getText(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** * Returns the title of the current page. Uses title protocol command. * @@ -1095,25 +929,6 @@ export interface NightwatchAPI { */ getTitle(callback?: (this: NightwatchAPI, result?: string) => void): this; - /** - * Returns a form element current value. Uses elementIdValue protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.getValue("form.login input[type=text]", function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, "enter username"); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - * @returns The element's value. - */ - getValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** * This command is an alias to url and also a convenience method when called without any arguments in the sense that it performs a call to .url() with passing the value of launch_url * field from the settings file. Uses url protocol command. @@ -1162,24 +977,6 @@ export interface NightwatchAPI { */ isLogAvailable(typeString: string, callback?: (result: NightwatchCallbackResult) => void): this; - /** - * Determine if an element is currently displayed. Uses elementIdDisplayed protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.isVisible('#main', function(result) { - * this.assert.equal(typeof result, "object"); - * this.assert.equal(result.status, 0); - * this.assert.equal(result.value, true); - * }); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - */ - isVisible(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; - /** * Maximizes the current window. * @@ -1193,22 +990,6 @@ export interface NightwatchAPI { */ maximizeWindow(callback?: (result: NightwatchCallbackResult) => void): this; - /** - * Move the mouse by an offset of the specified element. Uses moveTo protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.moveToElement('#main', 10, 10); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param xoffset: X offset to move to, relative to the top-left corner of the element. - * @param yoffset: Y offset to move to, relative to the top-left corner of the element. - * @param callback: Optional callback function to be called when the command finishes. - */ - moveToElement(selector: string, xoffset: number, yoffset: number, callback?: (result: NightwatchCallbackResult) => void): this; - /** * Suspends the test for the given time in milliseconds. If the milliseconds argument is missing it will suspend the test indefinitely * @@ -1368,30 +1149,6 @@ export interface NightwatchAPI { */ setCookie(cookie: any, callback?: () => void): this; - /** - * Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified. - * An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec (http://www.w3.org/TR/webdriver/#character-types), - * is loaded onto the main Nightwatch instance as client.Keys. - * - * Usage: - * ``` - * // send some simple text to an input - * this.demoTest = function (browser) { - * browser.setValue('input[type=text]', 'nightwatch'); - * }; - * - * // - * // send some text to an input and hit enter. - * this.demoTest = function (browser) { - * browser.setValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param inputValue: The text to send to the element or key strokes. - * @param callback: Optional callback function to be called when the command finishes. - */ - setValue(selector: string, inputValue: string, callback?: () => void): this; - /** * Sets the current window position. * @@ -1407,20 +1164,6 @@ export interface NightwatchAPI { */ setWindowPosition(OffsetX: number, OffsetY: number, callback?: () => void): this; - /** - * Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element. Uses submit protocol command. - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.submitForm('form.login'); - * }; - * ``` - * @param selector: The CSS/Xpath selector used to locate the element. - * @param callback: Optional callback function to be called when the command finishes. - */ - submitForm(selector: string, callback?: () => void): this; - /** * Change focus to another window. The window to change focus to may be specified by its server assigned window handle, or by the value of its name attribute. * To find out the window handle use window_handles protocol action @@ -1455,116 +1198,6 @@ export interface NightwatchAPI { */ urlHash(hash: string): this; - /** - * Opposite of waitForElementPresent. Waits a given time in milliseconds for an element to be not present (i.e. removed) in the page before performing any other commands - * or assertions. If the element is still present after the specified amount of time, the test fails. You can change the polling interval by defining - * a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file. - * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.waitForElementNotPresent('#dialog', 1000); - * }; - * ``` - * @param selector: The selector (CSS / Xpath) used to locate the element. - * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. - * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. - * @param callback: Optional callback function to be called when the command finishes. - * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time - * (e.g. Element %s was not in the page for %d ms). - */ - waitForElementNotPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; - - /** - * Opposite of waitForElementVisible. Waits a given time in milliseconds for an element to be not visible (i.e. hidden but existing) in the page before performing - * any other commands or assertions. If the element fails to be hidden in the specified amount of time, the test fails. You can change the polling interval by - * defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file. - * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.waitForElementNotVisible('#dialog', 1000); - * }; - * ``` - * @param selector: The selector (CSS / Xpath) used to locate the element. - * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. - * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. - * @param callback: Optional callback function to be called when the command finishes. - * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time - * (e.g. Element %s was not in the page for %d ms). - */ - waitForElementNotVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; - - /** - * Waits a given time in milliseconds for an element to be present in the page before performing any other commands or assertions. - * If the element fails to be present in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false. - * You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in - * your external globals file. - * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.waitForElementPresent('body', 1000); - * // continue if failed - * browser.waitForElementPresent('body', 1000, false); - * // with callback - * browser.waitForElementPresent('body', 1000, function() { - * // do something while we're here - * }); - * // custom Spanish message - * browser.waitForElementPresent('body', 1000, 'elemento %s no era presente en %d ms'); - * // many combinations possible - the message is always the last argument - * browser.waitForElementPresent('body', 1000, false, function() {}, 'elemento %s no era presente en %d ms'); - * }; - * ``` - * @param selector: The selector (CSS / Xpath) used to locate the element. - * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. - * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. - * @param callback: Optional callback function to be called when the command finishes. - * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time - * (e.g. Element %s was not in the page for %d ms). - */ - waitForElementPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; - - /** - * Waits a given time in milliseconds for an element to be visible in the page before performing any other commands or assertions. - * If the element fails to be present and visible in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false. - * You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json - * or in your external globals file. - * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). - * - * Usage: - * ``` - * this.demoTest = function (browser) { - * browser.waitForElementVisible('body', 1000); - * // continue if failed - * browser.waitForElementVisible('body', 1000, false); - * // with callback - * browser.waitForElementVisible('body', 1000, function() { - * // do something while we're here - * }); - * // custom Spanish message - * browser.waitForElementVisible('body', 1000, 'elemento %s no era visible en %d ms'); - * // many combinations possible - the message is always the last argument - * browser.waitForElementVisible('body', 1000, false, function() {}, 'elemento %s no era visible en %d ms'); - * }; - * ``` - * @param selector: The selector (CSS / Xpath) used to locate the element. - * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. - * @param abortOnFailure: By the default if the element is not found the test will fail. - * Set this to false if you wish for the test to continue even if the assertion fails. - * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. - * @param callback: Optional callback function to be called when the command finishes. - * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms). - */ - waitForElementVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; - /** * Accepts the currently displayed alert dialog. Usually, this is equivalent to clicking on the 'OK' button in the dialog. * @param callback: Optional callback function to be called when the command finishes. @@ -2173,6 +1806,7 @@ export interface NightwatchTestHooks { after?: NightwatchTestHook; beforeEach?: NightwatchTestHook; afterEach?: NightwatchTestHook; + '@disabled'?: boolean; } export type NightwatchTests = NightwatchTestFunctions | NightwatchTestHooks; @@ -2214,3 +1848,432 @@ export interface Nightwatch { api: NightwatchAPI; client: NightwatchClient; } + +/** + * #### [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances) + * Element instances encapsulate the definition used to handle element selectors. + * Generally you won't need to access them directly, + * instead referring to them using their `@`-prefixed names for selector arguments, + * but they are available through a page object or section's elements property. + */ +export interface EnhancedElementInstance { + /** + * The name of the element as defined by its key in the parent section or the page object's `elements` definition. + * This is the same name used with the `@` prefix in selector arguments for page object commands that refer to the element. + */ + name: string; + + /** + * The locate strategy to be used with `selector` when finding the element within the DOM. + */ + locateStrategy: string; + + /** + * A reference to the parent object instance. + * This is the parent section or the page object that contained the definition for this object. + */ + parent: EnhancedPageObject; + + /** + * The selector string used to find the element in the DOM. + */ + selector: string; +} + +/** + * #### [Enhanced Page Object Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-page-object-instances) + * Page object module definitions are used to define page object instances when their respective factory functions within the page reference of the standard command API is called. + * ``` + * var myPageObject = browser.page.MyPage(); // defined in MyPage.js module + * ``` + * Every time a factory function like MyPage above is called, a new instance of the page object is instantiated. + */ +export interface EnhancedPageObject extends SharedFunctions { + /** + * A reference providing access to the full Nightwatch command API, + * usually known as "client" or "browser" in test cases. + * This is used to access those commands that are not part of the subset of commands within the page object API. + */ + api: NightwatchAPI; + + /** + * A map of Element objects (see [Enhanced Element Instances](https://github.com/nightwatchjs/nightwatch/wiki/Page-Object-API#enhanced-element-instances)) used by element selectors. + */ + elements: {[name: string]: EnhancedElementInstance}; + + /** + * The name of the page object as defined by its module name (not including the extension). + * This is the same name used to access the `page` object factory from the page reference in the command API. + */ + name: string; +} + +export interface SharedFunctions { + /** + * Clear a textarea or a text input element's value. Uses elementIdValue protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.clearValue('input[type=text]'); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + */ + clearValue(selector: string, callback?: () => void): this; + + /** + * Simulates a click event on the given DOM element. Uses elementIdClick protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.click("#main ul li a.first"); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + */ + click(selector: string, callback?: () => void): this; + + /** + * Retrieve the value of an attribute for a given DOM element. Uses elementIdAttribute protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.getAttribute("#main ul li a.first", "href", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, "#home"); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param attribute: The attribute name to inspect. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The value of the attribute + */ + getAttribute(selector: string, attribute: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Retrieve the value of a css property for a given DOM element. Uses elementIdCssProperty protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.getCssProperty("#main ul li a.first", "display", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, 'inline'); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param cssProperty: The CSS property to inspect. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The value of the css property + */ + getCssProperty(selector: string, cssProperty: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Determine an element's size in pixels. Uses elementIdSize protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.getElementSize("#main ul li a.first", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value.width, 500); + * this.assert.equal(result.value.height, 20); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The width and height of the element in pixels + */ + getElementSize(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Determine an element's location on the page. The point (0, 0) refers to the upper-left corner of the page. + * The element's coordinates are returned as a JSON object with x and y properties. Uses elementIdLocation protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.getLocation("#main ul li a.first", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value.x, 200); + * this.assert.equal(result.value.y, 200); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The X and Y coordinates for the element on the page + */ + getLocation(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Determine an element's location on the screen once it has been scrolled into view. Uses elementIdLocationInView protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.getLocationInView("#main ul li a.first", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value.x, 200); + * this.assert.equal(result.value.y, 200); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The X and Y coordinates for the element on the page. + */ + getLocationInView(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Query for an element's tag name. Uses elementIdName protocol command. + * + * Usage: + * ``` + * this.demoTest = function (client) { + * client.getTagName("#main ul li .first", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, "a"); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The element's tag name, as a lowercase string. + */ + getTagName(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Returns the visible text for the element. Uses elementIdText protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.getText("#main ul li a.first", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, "nightwatchjs.org"); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The element's visible text. + */ + getText(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Returns a form element current value. Uses elementIdValue protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.getValue("form.login input[type=text]", function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, "enter username"); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + * @returns The element's value. + */ + getValue(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Determine if an element is currently displayed. Uses elementIdDisplayed protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.isVisible('#main', function(result) { + * this.assert.equal(typeof result, "object"); + * this.assert.equal(result.status, 0); + * this.assert.equal(result.value, true); + * }); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + */ + isVisible(selector: string, callback?: (this: NightwatchAPI, result: NightwatchCallbackResult) => void): this; + + /** + * Move the mouse by an offset of the specified element. Uses moveTo protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.moveToElement('#main', 10, 10); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param xoffset: X offset to move to, relative to the top-left corner of the element. + * @param yoffset: Y offset to move to, relative to the top-left corner of the element. + * @param callback: Optional callback function to be called when the command finishes. + */ + moveToElement(selector: string, xoffset: number, yoffset: number, callback?: (result: NightwatchCallbackResult) => void): this; + + /** + * Sends some text to an element. Can be used to set the value of a form element or to send a sequence of key strokes to an element. Any UTF-8 character may be specified. + * An object map with available keys and their respective UTF-8 characters, as defined on W3C WebDriver draft spec (http://www.w3.org/TR/webdriver/#character-types), + * is loaded onto the main Nightwatch instance as client.Keys. + * + * Usage: + * ``` + * // send some simple text to an input + * this.demoTest = function (browser) { + * browser.setValue('input[type=text]', 'nightwatch'); + * }; + * + * // + * // send some text to an input and hit enter. + * this.demoTest = function (browser) { + * browser.setValue('input[type=text]', ['nightwatch', browser.Keys.ENTER]); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param inputValue: The text to send to the element or key strokes. + * @param callback: Optional callback function to be called when the command finishes. + */ + setValue(selector: string, inputValue: string, callback?: () => void): this; + + /** + * Submit a FORM element. The submit command may also be applied to any element that is a descendant of a FORM element. Uses submit protocol command. + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.submitForm('form.login'); + * }; + * ``` + * @param selector: The CSS/Xpath selector used to locate the element. + * @param callback: Optional callback function to be called when the command finishes. + */ + submitForm(selector: string, callback?: () => void): this; + + /** + * Opposite of waitForElementPresent. Waits a given time in milliseconds for an element to be not present (i.e. removed) in the page before performing any other commands + * or assertions. If the element is still present after the specified amount of time, the test fails. You can change the polling interval by defining + * a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file. + * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.waitForElementNotPresent('#dialog', 1000); + * }; + * ``` + * @param selector: The selector (CSS / Xpath) used to locate the element. + * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. + * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param callback: Optional callback function to be called when the command finishes. + * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time + * (e.g. Element %s was not in the page for %d ms). + */ + waitForElementNotPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; + + /** + * Opposite of waitForElementVisible. Waits a given time in milliseconds for an element to be not visible (i.e. hidden but existing) in the page before performing + * any other commands or assertions. If the element fails to be hidden in the specified amount of time, the test fails. You can change the polling interval by + * defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in your external globals file. + * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.waitForElementNotVisible('#dialog', 1000); + * }; + * ``` + * @param selector: The selector (CSS / Xpath) used to locate the element. + * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. + * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param callback: Optional callback function to be called when the command finishes. + * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time + * (e.g. Element %s was not in the page for %d ms). + */ + waitForElementNotVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; + + /** + * Waits a given time in milliseconds for an element to be present in the page before performing any other commands or assertions. + * If the element fails to be present in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false. + * You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json or in + * your external globals file. + * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.waitForElementPresent('body', 1000); + * // continue if failed + * browser.waitForElementPresent('body', 1000, false); + * // with callback + * browser.waitForElementPresent('body', 1000, function() { + * // do something while we're here + * }); + * // custom Spanish message + * browser.waitForElementPresent('body', 1000, 'elemento %s no era presente en %d ms'); + * // many combinations possible - the message is always the last argument + * browser.waitForElementPresent('body', 1000, false, function() {}, 'elemento %s no era presente en %d ms'); + * }; + * ``` + * @param selector: The selector (CSS / Xpath) used to locate the element. + * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. + * @param abortOnFailure: By the default if the element is not found the test will fail. Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param callback: Optional callback function to be called when the command finishes. + * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time + * (e.g. Element %s was not in the page for %d ms). + */ + waitForElementPresent(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; + + /** + * Waits a given time in milliseconds for an element to be visible in the page before performing any other commands or assertions. + * If the element fails to be present and visible in the specified amount of time, the test fails. You can change this by setting abortOnFailure to false. + * You can change the polling interval by defining a waitForConditionPollInterval property (in milliseconds) in as a global property in your nightwatch.json + * or in your external globals file. + * Similarly, a default timeout can be specified as a global waitForConditionTimeout property (in milliseconds). + * + * Usage: + * ``` + * this.demoTest = function (browser) { + * browser.waitForElementVisible('body', 1000); + * // continue if failed + * browser.waitForElementVisible('body', 1000, false); + * // with callback + * browser.waitForElementVisible('body', 1000, function() { + * // do something while we're here + * }); + * // custom Spanish message + * browser.waitForElementVisible('body', 1000, 'elemento %s no era visible en %d ms'); + * // many combinations possible - the message is always the last argument + * browser.waitForElementVisible('body', 1000, false, function() {}, 'elemento %s no era visible en %d ms'); + * }; + * ``` + * @param selector: The selector (CSS / Xpath) used to locate the element. + * @param time: The number of milliseconds to wait. The runner performs repeated checks every 500 ms. + * @param abortOnFailure: By the default if the element is not found the test will fail. + * Set this to false if you wish for the test to continue even if the assertion fails. + * To set this globally you can define a property `abortOnNightwatchAssertionsFailure` in your globals. + * @param callback: Optional callback function to be called when the command finishes. + * @param message: Optional message to be shown in the output; the message supports two placeholders: %s for current selector and %d for the time (e.g. Element %s was not in the page for %d ms). + */ + waitForElementVisible(selector: string, time?: number, abortOnFailure?: boolean, callback?: () => void, message?: string): this; +} diff --git a/types/nise/index.d.ts b/types/nise/index.d.ts new file mode 100644 index 0000000000..f054bad373 --- /dev/null +++ b/types/nise/index.d.ts @@ -0,0 +1,282 @@ +// Type definitions for nise 1.4 +// Project: https://github.com/sinonjs/nise#readme +// Definitions by: Alexander T. +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export interface FakeUploadProgress { + 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; +} + +export interface FakeXMLHttpRequest { + /** + * 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: FakeUploadProgress; + /** + * 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; + + /** + * 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; + + onloadstart(e: Event): void; + onprogress(e: Event): void; + ontimeout(e: Event): void; + onloadend(e: Event): void; + onerror(e: Event): void; + onabort(e: Event): void; + onload(e: Event): void; +} + +export interface FakeServerOptions { + /** + * 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; +} + +export interface FakeServer extends FakeServerOptions { + lastRequest: FakeXMLHttpRequest | undefined; + firstRequest: FakeXMLHttpRequest | undefined; + secondRequest: FakeXMLHttpRequest | undefined; + thirdRequest: FakeXMLHttpRequest | undefined; + + /** + * 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: FakeXMLHttpRequest): 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: FakeXMLHttpRequest[]; + + /** + * 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: FakeXMLHttpRequest) => 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: FakeXMLHttpRequest) => 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: FakeXMLHttpRequest) => 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: FakeXMLHttpRequest) => 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: FakeXMLHttpRequest) => void): void; + respondWith(...args: any[]): 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; + + getRequest(): FakeXMLHttpRequest | undefined; + reset(): void; + resetBehavior(): void; + resetHistory(): void; +} + +export interface FakeXMLHttpRequestStatic { + new(): FakeXMLHttpRequest; + /** + * 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: FakeXMLHttpRequest): void; + /** + * Restore original function(s). + */ + restore(): void; +} + +export interface FakeServerStatic { + create(options?: Partial): FakeServer; +} + +export interface FakeXHR { + useFakeXMLHttpRequest(): FakeXMLHttpRequestStatic; + FakeXMLHttpRequest: FakeXMLHttpRequestStatic; +} + +export const fakeServerWithClock: FakeServerStatic; +export const fakeServer: FakeServerStatic; +export const fakeXhr: FakeXHR; diff --git a/types/nise/nise-tests.ts b/types/nise/nise-tests.ts new file mode 100644 index 0000000000..827275fc55 --- /dev/null +++ b/types/nise/nise-tests.ts @@ -0,0 +1,56 @@ +import { fakeXhr, fakeServer, FakeServer, FakeXMLHttpRequest } from 'nise'; + +function testCreateFakeServer() { + fakeServer.create(); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3, fakeHTTPMethods: true, respondImmediately: false }); + fakeServer.create({ autoRespond: true, autoRespondAfter: 3 }); +} + +function testFakeServer() { + const server: FakeServer = fakeServer.create(); + const respondWith = ['GET', 'http://test.com', [200, {}, '']]; + + server.requests; + server.autoRespond = true; + + server.respondWith((xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith('body'); + server.respondWith([]); + + server.respondWith('http://test.com', 'body'); + server.respondWith('http://test.com', []); + server.respondWith('http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', 'http://test.com', 'body'); + server.respondWith('GET', 'http://test.com', []); + server.respondWith('GET', 'http://test.com', (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith(/url/, ''); + server.respondWith(/url/, []); + server.respondWith(/url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + + server.respondWith('GET', /url/, ''); + server.respondWith('GET', /url/, []); + server.respondWith('GET', /url/, (xhr: FakeXMLHttpRequest) => xhr.respond(200)); + server.respondWith(...respondWith); + server.respond(); + server.restore(); +} + +function testFakeXMLHttpRequest() { + const xhr = new fakeXhr.FakeXMLHttpRequest(); + const headers = xhr.getAllResponseHeaders(); + const header = xhr.getResponseHeader('test'); + + xhr.setResponseHeaders({ Accept: 'application/json' }); + xhr.setResponseBody('body'); + xhr.respond(200, { Accept: 'application/json' }, 'body'); + xhr.error(); +} + +function testFakeXMLHttpRequestStatic() { + fakeXhr.FakeXMLHttpRequest.useFilters = true; + fakeXhr.FakeXMLHttpRequest.addFilter((method, url, async, user, pass) => true); + fakeXhr.FakeXMLHttpRequest.onCreate = (xhr: FakeXMLHttpRequest) => { }; + fakeXhr.FakeXMLHttpRequest.restore(); +} diff --git a/types/nise/tsconfig.json b/types/nise/tsconfig.json new file mode 100644 index 0000000000..1e535819c3 --- /dev/null +++ b/types/nise/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true, + "strictNullChecks": true, + "noImplicitThis": true, + "noImplicitAny": true, + "module": "commonjs", + "noEmit": true, + "types": [], + "lib": ["es6", "dom"], + "baseUrl": "../", + "typeRoots": ["../"] + }, + + "files": [ + "nise-tests.ts", + "index.d.ts" + ] +} diff --git a/types/nise/tslint.json b/types/nise/tslint.json new file mode 100644 index 0000000000..08b1465cd6 --- /dev/null +++ b/types/nise/tslint.json @@ -0,0 +1,6 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "unified-signatures": false + } +} diff --git a/types/noble/index.d.ts b/types/noble/index.d.ts index 61ca1f2113..5b4af235e7 100644 --- a/types/noble/index.d.ts +++ b/types/noble/index.d.ts @@ -30,6 +30,8 @@ export declare function removeListener(event: "scanStop", listener: () => void): export declare function removeListener(event: "discover", listener: (peripheral: Peripheral) => void): events.EventEmitter; export declare function removeListener(event: string, listener: Function): events.EventEmitter; +export declare function removeAllListeners(event?: string): events.EventEmitter; + export declare var state:string; export declare class Peripheral extends events.EventEmitter { diff --git a/types/noble/noble-tests.ts b/types/noble/noble-tests.ts index 0c8dcf6c20..a4441eba6e 100644 --- a/types/noble/noble-tests.ts +++ b/types/noble/noble-tests.ts @@ -35,6 +35,12 @@ noble.removeListener("discover", (peripheral: noble.Peripheral): void => { peripheral.disconnect((): void => {}); }); +noble.removeAllListeners("stateChange"); +noble.removeAllListeners("scanStart"); +noble.removeAllListeners("scanStop"); +noble.removeAllListeners("discover"); +noble.removeAllListeners(); + var peripheral: noble.Peripheral = new noble.Peripheral(); peripheral.uuid = "12ad4e81"; peripheral.advertisement = { diff --git a/types/node-crate/index.d.ts b/types/node-crate/index.d.ts index 8fa75581e0..971c71db24 100644 --- a/types/node-crate/index.d.ts +++ b/types/node-crate/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for node-crate 2.0 -// Project: https://github.com/arobson/rabbot +// Project: https://github.com/megastef/node-crate // Definitions by: Greg Jednaszewski // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -30,6 +30,10 @@ declare namespace crate { * Creates a table with the given schema. */ create: (schema: object) => Promise; + /** + * Creates a table if it doesn't already exist. + */ + createIfNotExists: (schema: object) => Promise; /** * Drops a table. */ diff --git a/types/node-crate/node-crate-tests.ts b/types/node-crate/node-crate-tests.ts index d98f8c2694..117fdcbcdf 100644 --- a/types/node-crate/node-crate-tests.ts +++ b/types/node-crate/node-crate-tests.ts @@ -10,6 +10,8 @@ crate.insert('users', {id: 'test', password: 'password'}); crate.create({users: {id: 'string primary key', password: 'string'}}); +crate.createIfNotExists({users: {id: 'string primary key', password: 'string'}}); + crate.drop('users'); crate.update('users', {password: 'newPassword'}, "id = 'test'"); diff --git a/types/node-cron/index.d.ts b/types/node-cron/index.d.ts index 75ddaefdde..8c6b70ec1c 100644 --- a/types/node-cron/index.d.ts +++ b/types/node-cron/index.d.ts @@ -1,15 +1,28 @@ -// Type definitions for node-cron 1.2 -// Project: http://merencia.com/node-cron/ -// Definitions by: morsic +// Type definitions for node-cron 2.0 +// Project: https://github.com/node-cron/node-cron +// Definitions by: morsic , +// burtek // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// immediateStart - default true -export function schedule(a: string, func: () => void, immediateStart?: boolean): ScheduledTask; +export function schedule(cronExpression: string, func: () => void, options?: ScheduleOptions): ScheduledTask; -export function validate(a: string): boolean; +export function validate(cronExpression: string): boolean; export interface ScheduledTask { start: () => this; stop: () => this; destroy: () => void; } + +export interface ScheduleOptions { + /** + * A boolean to set if the created task is scheduled. + * + * Defaults to `true` + */ + scheduled?: boolean; + /** + * The timezone that is used for job scheduling + */ + timezone?: string; +} diff --git a/types/node-cron/node-cron-tests.ts b/types/node-cron/node-cron-tests.ts index c670924d27..17350b6427 100644 --- a/types/node-cron/node-cron-tests.ts +++ b/types/node-cron/node-cron-tests.ts @@ -17,7 +17,7 @@ cron.schedule('1-5 * * * *', () => { const task = cron.schedule('* * * * *', () => { log('immediately started'); // because of manual call start method -}, false); +}, { scheduled: false }); task.start(); diff --git a/types/node-forge/README.md b/types/node-forge/README.md index fcac651de8..c70966e474 100644 --- a/types/node-forge/README.md +++ b/types/node-forge/README.md @@ -27,3 +27,4 @@ BSD-2-Clause [Aakash Goenka](https://github.com/a-k-g) [Rafal2228](https://github.com/rafal2228) [Beeno Tung](https://github.com/beenotung) +[Nikita Koryabkin](https://github.com/Apologiz) diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index e30a217ddc..d2fcddc2d9 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -1,10 +1,13 @@ // Type definitions for node-forge 0.7.6 // Project: https://github.com/digitalbazaar/forge -// Definitions by: Seth Westphal -// Kay Schecker -// Aakash Goenka -// Rafal2228 -// Beeno Tung +// Definitions by: Seth Westphal +// Kay Schecker +// Aakash Goenka +// Rafal2228 +// Beeno Tung +// Joe Flateau +// Nikita Koryabkin +// timhwang21 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -18,6 +21,15 @@ declare module "node-forge" { type Utf8 = string; type OID = string; + namespace jsbn { + class BigInteger { + data: number[]; + t: number; + s: number; + toString(): string; + } + } + namespace pem { interface EncodeOptions { @@ -38,30 +50,63 @@ declare module "node-forge" { } namespace pki { - type PEM = string; - type Key = any; + type PublicKey = rsa.PublicKey | ed25519.Key; + type PrivateKey = rsa.PrivateKey | ed25519.Key; interface KeyPair { - publicKey: Key; - privateKey: Key; + publicKey: PublicKey; + privateKey: PrivateKey; } function pemToDer(pem: PEM): util.ByteStringBuffer; - function privateKeyToPem(key: Key, maxline?: number): PEM; - function privateKeyInfoToPem(key: Key, maxline?: number): PEM; - function publicKeyToPem(key: Key, maxline?: number): PEM; - function publicKeyFromPem(pem: PEM): Key; - function privateKeyFromPem(pem: PEM): Key; + function privateKeyToPem(key: PrivateKey, maxline?: number): PEM; + function privateKeyInfoToPem(key: Bytes, maxline?: number): PEM; + function publicKeyToPem(key: PublicKey, maxline?: number): PEM; + function publicKeyFromPem(pem: PEM): PublicKey; + 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; } var oids: oids; + namespace ed25519 { + type Key = ArrayBuffer; + } + namespace rsa { + type EncryptionScheme = 'RSAES-PKCS1-V1_5' | 'RSA-OAEP' | 'RAW' | 'NONE' | null; + type SignatureScheme = 'RSASSA-PKCS1-V1_5' | pss.PSS | 'NONE' | null; + + interface PublicKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + encrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + verify(digest: Bytes, signature: Bytes, scheme?: SignatureScheme): boolean; + } + + interface PrivateKey { + n: jsbn.BigInteger; + e: jsbn.BigInteger; + d: jsbn.BigInteger; + p: jsbn.BigInteger; + q: jsbn.BigInteger; + dP: jsbn.BigInteger; + dQ: jsbn.BigInteger; + qInv: jsbn.BigInteger; + decrypt(data: Bytes, scheme?: EncryptionScheme, schemeOptions?: any): Bytes; + sign(md: md.MessageDigest, scheme?: SignatureScheme): Bytes; + } + + interface KeyPair { + publicKey: PublicKey; + privateKey: PrivateKey; + } interface GenerateKeyPairOptions { bits?: number; @@ -73,6 +118,8 @@ declare module "node-forge" { algorithm?: string; } + function setPublicKey(n: any, e: any): any; + function generateKeyPair(bits?: number, e?: number, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; function generateKeyPair(options?: GenerateKeyPairOptions, callback?: (err: Error, keypair: KeyPair) => void): KeyPair; } @@ -96,9 +143,15 @@ declare module "node-forge" { function publicKeyFromPrivateKey(options: { privateKey: NativeBuffer }): NativeBuffer; - function sign(options: { privateKey: NativeBuffer }): NativeBuffer; + function sign(options: { + message: string, + encoding: string, + privateKey: NativeBuffer + }): NativeBuffer; function verify(options: { + message: string, + encoding: string, signature: Buffer | Uint8Array | util.ByteBuffer | string, publicKey: NativeBuffer }): boolean; @@ -140,7 +193,8 @@ declare module "node-forge" { hash: any; }; extensions: any[]; - publicKey: any; + privateKey: PrivateKey; + publicKey: PublicKey; md: any; /** * Sets the subject of this certificate. @@ -150,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. @@ -179,7 +233,7 @@ declare module "node-forge" { * @param key the private key to sign with. * @param md the message digest object to use (defaults to forge.md.sha1). */ - sign(key: pki.Key, md: md.MessageDigest): void; + sign(key: pki.PrivateKey, md?: md.MessageDigest): void; /** * Attempts verify the signature on the passed certificate using this * certificate's public key. @@ -192,11 +246,41 @@ 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): Key; + function decryptRsaPrivateKey(pem: PEM, passphrase?: string): PrivateKey; function createCertificate(): Certificate; + + function certificationRequestToPem(cert: Certificate, maxline?: number): PEM; + + function certificationRequestFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + + function createCertificationRequest(): Certificate; + + function publicKeyToAsn1(publicKey: PublicKey): any; + + function publicKeyToRSAPublicKey(publicKey: PublicKey): any; + } + + namespace random { + function getBytes(count: number, callback?: (bytes: Bytes) => any): Bytes; + function getBytesSync(count: number): Bytes; + type CB = (_: any, seed: string) => void; + interface Random { + seedFileSync: (needed: number) => string; + seedFile: (needed: number, cb: CB) => void; + } + function createInstance(): Random; } namespace ssh { @@ -218,22 +302,22 @@ declare module "node-forge" { /** * @description Encodes a private RSA key as an OpenSSH file */ - function privateKeyToOpenSSH(privateKey: pki.Key, passphrase?: string): string; + function privateKeyToOpenSSH(privateKey: pki.PrivateKey, passphrase?: string): string; /** * @description Encodes (and optionally encrypts) a private RSA key as a Putty PPK file */ - function privateKeyToPutty(privateKey: pki.Key, passphrase?: string, comment?: string): string; + function privateKeyToPutty(privateKey: pki.PrivateKey, passphrase?: string, comment?: string): string; /** * @description Encodes a public RSA key as an OpenSSH file */ - function publicKeyToOpenSSH(publicKey: pki.Key, comment?: string): string | pki.PEM; + function publicKeyToOpenSSH(publicKey: pki.PublicKey, comment?: string): string | pki.PEM; /** * @description Gets the SSH fingerprint for the given public key */ - function getPublicKeyFingerprint(publicKey: pki.Key, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; + function getPublicKeyFingerprint(publicKey: pki.PublicKey, options?: FingerprintOptions): util.ByteStringBuffer | Hex | string; } namespace asn1 { @@ -346,7 +430,7 @@ declare module "node-forge" { function decodeUtf8(encoded: Utf8): string; function createBuffer(): ByteBuffer; - function createBuffer(input: string, encode: string): ByteBuffer; + function createBuffer(input: Bytes | ArrayBuffer | ArrayBufferView | ByteStringBuffer, encode: string): ByteBuffer; namespace binary { namespace raw { @@ -387,7 +471,7 @@ declare module "node-forge" { interface Bag { type: string; attributes: any; - key?: pki.Key; + key?: pki.PrivateKey; cert?: pki.Certificate; asn1: asn1.Asn1 } @@ -411,10 +495,33 @@ declare module "node-forge" { function pkcs12FromAsn1(obj: any, password?: string): Pkcs12Pfx; } + namespace pkcs7 { + interface PkcsSignedData { + content?: string | util.ByteBuffer; + contentInfo?: { value: any[] }; + + addCertificate(certificate: pki.Certificate): void; + addSigner(options: { + key: string; + certificate: pki.Certificate; + digestAlgorithm: string; + authenticatedAttributes: { type: string; value?: string }[]; + }): void; + sign(options?:{ + detached?: boolean + }): void; + toAsn1(): asn1.Asn1; + } + + function createSignedData(): PkcsSignedData; + } + namespace md { + type Encoding = "raw" | "utf8" + interface MessageDigest { - update(msg: string, encoding?: string): MessageDigest; + update(msg: string, encoding?: Encoding): MessageDigest; digest(): util.ByteStringBuffer; } @@ -426,6 +533,10 @@ declare module "node-forge" { function create(): MessageDigest; } + namespace sha512 { + function create(): MessageDigest; + } + namespace md5 { function create(): MessageDigest; } @@ -435,11 +546,14 @@ declare module "node-forge" { type Algorithm = "AES-ECB" | "AES-CBC" | "AES-CFB" | "AES-OFB" | "AES-CTR" | "AES-GCM" | "3DES-ECB" | "3DES-CBC" | "DES-ECB" | "DES-CBC"; - function createCipher(algorithm: Algorithm, payload: util.ByteBuffer): BlockCipher; - function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer): BlockCipher; + function createCipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher; + function createDecipher(algorithm: Algorithm, payload: util.ByteBuffer | Bytes): BlockCipher; interface StartOptions { - iv?: string; + iv?: Bytes; + tag?: util.ByteStringBuffer; + tagLength?: number; + additionalData?: string; } interface BlockCipher { @@ -447,6 +561,23 @@ declare module "node-forge" { update: (payload: util.ByteBuffer) => void; finish: () => boolean; output: util.ByteStringBuffer; + mode: Mode; + } + + interface Mode { + tag: util.ByteStringBuffer; + } + } + + namespace pss { + type PSS = any; + + function create(any: any): PSS; + } + + namespace mgf { + namespace mgf1 { + function create(any: any): any; } } } diff --git a/types/node-forge/node-forge-tests.ts b/types/node-forge/node-forge-tests.ts index 575661e9aa..62f0718c21 100644 --- a/types/node-forge/node-forge-tests.ts +++ b/types/node-forge/node-forge-tests.ts @@ -8,9 +8,7 @@ let x: string = forge.ssh.privateKeyToOpenSSH(key); let pemKey: forge.pki.PEM = publicKeyPem; let publicKeyRsa = forge.pki.publicKeyFromPem(pemKey); let privateKeyRsa = forge.pki.privateKeyFromPem(privateKeyPem); -let privateKeyRsa2 = forge.pki.privateKeyInfoToPem(privateKeyPem); -let byteBufferString = forge.pki.pemToDer(privateKeyRsa); -let certPem = forge.pki.certificateFromPem(pemKey); +let byteBufferString = forge.pki.pemToDer(privateKeyPem); let cert = forge.pki.createCertificate(); { @@ -118,6 +116,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin } { + let key = forge.random.getBytesSync(24) let payload = { asd: 'asd' }; let cipher = forge.cipher.createCipher('3DES-ECB', forge.util.createBuffer(key, 'raw')); cipher.start(); @@ -133,7 +132,7 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin let decrypted = decipher.output as forge.util.ByteStringBuffer; let content = JSON.parse(forge.util.encodeUtf8(decrypted.getBytes())); - if (content.asd == payload.asd) throw Error('forge.cipher.createCipher failed'); + if (content.asd !== payload.asd) throw Error('forge.cipher.createCipher failed'); } { @@ -189,3 +188,37 @@ if (forge.util.fillString('1', 5) !== '11111') throw Error('forge.util.fillStrin // self-sign certificate cert.sign(keypair.privateKey, forge.md.sha256.create()); } + +{ + let md: forge.md.MessageDigest; + let hex: string; + let signature: forge.Bytes + + md = forge.md.sha256.create(); + md = md.update('Test'); + hex = md.digest().toHex(); + + signature = keypair.privateKey.sign(md) + if (!keypair.publicKey.verify(md.digest().bytes(), signature)) { + 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-ral/node-ral-tests.ts b/types/node-ral/node-ral-tests.ts index a625c37da4..3c6f6cd9b1 100644 --- a/types/node-ral/node-ral-tests.ts +++ b/types/node-ral/node-ral-tests.ts @@ -17,7 +17,7 @@ class HashringBalance extends nodeRal.Balance { return 'hashring'; } fetchServer(balanceContext: nodeRal.Balance.BalanceContextClass, conf: {}, prevBackend: nodeRal.Server) { - return {}; + return {} as nodeRal.Server; } } diff --git a/types/node/index.d.ts b/types/node/index.d.ts index 5fb0c2895a..b9edae0587 100644 --- a/types/node/index.d.ts +++ b/types/node/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Node.js 10.11 +// Type definitions for Node.js 10.12 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript // DefinitelyTyped @@ -30,6 +30,8 @@ // Wilco Bakker // wwwy3y3 // Zane Hannan AU +// Jeremie Rodriguez +// Samuel Ainsworth // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /** inspector module types */ @@ -108,6 +110,10 @@ interface Console { * Stops a timer that was previously started by calling {@link console.time()} and prints the result to `stdout`. */ timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link console.time()}, prints the elapsed time and other `data` arguments to `stdout`. + */ + timeLog(label: string, ...data: any[]): void; /** * Prints to `stderr` the string 'Trace :', followed by the {@link util.format()} formatted message and stack trace to the current position in the code. */ @@ -154,7 +160,7 @@ interface ErrorConstructor { stackTraceLimit: number; } -// compat for TypeScript 1.8 +// compat for TypeScript 1.8 and default es5 target // if you use with --target es3 or --target es5 and use below definitions, // use the lib.es6.d.ts that is bundled with TypeScript 1.8. interface MapConstructor { } @@ -162,6 +168,9 @@ interface WeakMapConstructor { } interface SetConstructor { } interface WeakSetConstructor { } +interface Set {} +interface ReadonlySet {} + // Forward-declare needed types from lib.es2015.d.ts (in case users are using `--lib es5`) interface Iterable { } interface Iterator { @@ -200,20 +209,20 @@ declare var console: Console; declare var __filename: string; declare var __dirname: string; -declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; +declare function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; declare namespace setTimeout { function __promisify__(ms: number): Promise; function __promisify__(ms: number, value: T): Promise; } -declare function clearTimeout(timeoutId: NodeJS.Timer): void; -declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; -declare function clearInterval(intervalId: NodeJS.Timer): void; -declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; +declare function clearTimeout(timeoutId: NodeJS.Timeout): void; +declare function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; +declare function clearInterval(intervalId: NodeJS.Timeout): void; +declare function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; declare namespace setImmediate { function __promisify__(): Promise; function __promisify__(value: T): Promise; } -declare function clearImmediate(immediateId: any): void; +declare function clearImmediate(immediateId: NodeJS.Immediate): void; // TODO: change to `type NodeRequireFunction = (id: string) => any;` in next mayor version. interface NodeRequireFunction { @@ -486,11 +495,20 @@ declare namespace NodeJS { maxArrayLength?: number | null; breakLength?: number; compact?: boolean; + sorted?: boolean | ((a: string, b: string) => number); + } + + interface ConsoleConstructorOptions { + stdout: WritableStream; + stderr?: WritableStream; + ignoreErrors?: boolean; + colorMode?: boolean | 'auto'; } interface ConsoleConstructor { prototype: Console; - new(stdout: WritableStream, stderr?: WritableStream): Console; + new(stdout: WritableStream, stderr?: WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; } interface CallSite { @@ -684,6 +702,8 @@ declare namespace NodeJS { "SIGSTOP" | "SIGSYS" | "SIGTERM" | "SIGTRAP" | "SIGTSTP" | "SIGTTIN" | "SIGTTOU" | "SIGUNUSED" | "SIGURG" | "SIGUSR1" | "SIGUSR2" | "SIGVTALRM" | "SIGWINCH" | "SIGXCPU" | "SIGXFSZ" | "SIGBREAK" | "SIGLOST" | "SIGINFO"; + type MultipleResolveType = 'resolve' | 'reject'; + type BeforeExitListener = (code: number) => void; type DisconnectListener = () => void; type ExitListener = (code: number) => void; @@ -695,6 +715,7 @@ declare namespace NodeJS { type SignalsListener = (signal: Signals) => void; type NewListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; type RemoveListenerListener = (type: string | symbol, listener: (...args: any[]) => void) => void; + type MultipleResolveListener = (type: MultipleResolveType, promise: Promise, value: any) => void; interface Socket extends ReadWriteStream { isTTY?: true; @@ -811,8 +832,7 @@ declare namespace NodeJS { * read-only `Set` of flags allowable within the [`NODE_OPTIONS`][] * environment variable. */ - // TODO: This Set is readonly - allowedNodeEnvironmentFlags: Set; + allowedNodeEnvironmentFlags: ReadonlySet; /** * EventEmitter @@ -839,6 +859,7 @@ declare namespace NodeJS { addListener(event: Signals, listener: SignalsListener): this; addListener(event: "newListener", listener: NewListenerListener): this; addListener(event: "removeListener", listener: RemoveListenerListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; emit(event: "beforeExit", code: number): boolean; emit(event: "disconnect"): boolean; @@ -851,6 +872,7 @@ declare namespace NodeJS { emit(event: Signals, signal: Signals): boolean; emit(event: "newListener", eventName: string | symbol, listener: (...args: any[]) => void): this; emit(event: "removeListener", eventName: string, listener: (...args: any[]) => void): this; + emit(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: "beforeExit", listener: BeforeExitListener): this; on(event: "disconnect", listener: DisconnectListener): this; @@ -863,6 +885,7 @@ declare namespace NodeJS { on(event: Signals, listener: SignalsListener): this; on(event: "newListener", listener: NewListenerListener): this; on(event: "removeListener", listener: RemoveListenerListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; once(event: "beforeExit", listener: BeforeExitListener): this; once(event: "disconnect", listener: DisconnectListener): this; @@ -875,6 +898,7 @@ declare namespace NodeJS { once(event: Signals, listener: SignalsListener): this; once(event: "newListener", listener: NewListenerListener): this; once(event: "removeListener", listener: RemoveListenerListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; prependListener(event: "beforeExit", listener: BeforeExitListener): this; prependListener(event: "disconnect", listener: DisconnectListener): this; @@ -887,6 +911,7 @@ declare namespace NodeJS { prependListener(event: Signals, listener: SignalsListener): this; prependListener(event: "newListener", listener: NewListenerListener): this; prependListener(event: "removeListener", listener: RemoveListenerListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; prependOnceListener(event: "disconnect", listener: DisconnectListener): this; @@ -899,6 +924,7 @@ declare namespace NodeJS { prependOnceListener(event: Signals, listener: SignalsListener): this; prependOnceListener(event: "newListener", listener: NewListenerListener): this; prependOnceListener(event: "removeListener", listener: RemoveListenerListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; listeners(event: "beforeExit"): BeforeExitListener[]; listeners(event: "disconnect"): DisconnectListener[]; @@ -911,6 +937,7 @@ declare namespace NodeJS { listeners(event: Signals): SignalsListener[]; listeners(event: "newListener"): NewListenerListener[]; listeners(event: "removeListener"): RemoveListenerListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; } interface Global { @@ -953,9 +980,9 @@ declare namespace NodeJS { Uint8ClampedArray: Function; WeakMap: WeakMapConstructor; WeakSet: WeakSetConstructor; - clearImmediate: (immediateId: any) => void; - clearInterval: (intervalId: Timer) => void; - clearTimeout: (timeoutId: Timer) => void; + clearImmediate: (immediateId: Immediate) => void; + clearInterval: (intervalId: Timeout) => void; + clearTimeout: (timeoutId: Timeout) => void; console: typeof console; decodeURI: typeof decodeURI; decodeURIComponent: typeof decodeURIComponent; @@ -970,9 +997,9 @@ declare namespace NodeJS { parseInt: typeof parseInt; process: Process; root: Global; - setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => any; - setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timer; - setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timer; + setImmediate: (callback: (...args: any[]) => void, ...args: any[]) => Immediate; + setInterval: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; + setTimeout: (callback: (...args: any[]) => void, ms: number, ...args: any[]) => Timeout; undefined: typeof undefined; unescape: (str: string) => string; gc: () => void; @@ -981,12 +1008,26 @@ declare namespace NodeJS { interface Timer { ref(): void; + refresh(): void; + unref(): void; + } + + class Immediate { + ref(): void; + unref(): void; + _onImmediate: Function; // to distinguish it from the Timeout class + } + + class Timeout implements Timer { + ref(): void; + refresh(): void; unref(): void; } class Module { static runMain(): void; static wrap(code: string): string; + static createRequireFromPath(path: string): (path: string) => any; static builtinModules: string[]; static Module: typeof Module; @@ -1085,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; @@ -1098,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[]; @@ -1951,65 +2002,371 @@ declare module "punycode" { } declare module "repl" { - import * as stream from "stream"; - import * as readline from "readline"; + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ terminal?: boolean; - eval?: Function; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: any; - breakEvalOnSigint?: any; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; } - interface REPLServer extends readline.ReadLine { - context: any; - inputStream: NodeJS.ReadableStream; - outputStream: NodeJS.WritableStream; + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; - defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; /** * events.EventEmitter - * 1. exit - * 2. reset + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset */ addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (...args: any[]) => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; emit(event: "exit"): boolean; - emit(event: "reset", context: any): boolean; + emit(event: "reset", context: Context): boolean; on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (...args: any[]) => void): this; + on(event: "reset", listener: (context: Context) => void): this; once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (...args: any[]) => void): this; + once(event: "reset", listener: (context: Context) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (...args: any[]) => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (...args: any[]) => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol + + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ class Recoverable extends SyntaxError { err: Error; @@ -2029,12 +2386,33 @@ declare module "readline" { shift?: boolean; } - interface ReadLine extends events.EventEmitter { + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; + pause(): this; + resume(): this; close(): void; write(data: string | Buffer, key?: Key): void; @@ -2051,7 +2429,7 @@ declare module "readline" { addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: "close", listener: () => void): this; - addListener(event: "line", listener: (input: any) => void): this; + addListener(event: "line", listener: (input: string) => void): this; addListener(event: "pause", listener: () => void): this; addListener(event: "resume", listener: () => void): this; addListener(event: "SIGCONT", listener: () => void): this; @@ -2060,7 +2438,7 @@ declare module "readline" { emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; - emit(event: "line", input: any): boolean; + emit(event: "line", input: string): boolean; emit(event: "pause"): boolean; emit(event: "resume"): boolean; emit(event: "SIGCONT"): boolean; @@ -2069,7 +2447,7 @@ declare module "readline" { on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; - on(event: "line", listener: (input: any) => void): this; + on(event: "line", listener: (input: string) => void): this; on(event: "pause", listener: () => void): this; on(event: "resume", listener: () => void): this; on(event: "SIGCONT", listener: () => void): this; @@ -2078,7 +2456,7 @@ declare module "readline" { once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; - once(event: "line", listener: (input: any) => void): this; + once(event: "line", listener: (input: string) => void): this; once(event: "pause", listener: () => void): this; once(event: "resume", listener: () => void): this; once(event: "SIGCONT", listener: () => void): this; @@ -2087,7 +2465,7 @@ declare module "readline" { prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; - prependListener(event: "line", listener: (input: any) => void): this; + prependListener(event: "line", listener: (input: string) => void): this; prependListener(event: "pause", listener: () => void): this; prependListener(event: "resume", listener: () => void): this; prependListener(event: "SIGCONT", listener: () => void): this; @@ -2096,7 +2474,7 @@ declare module "readline" { prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "line", listener: (input: any) => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; prependOnceListener(event: "pause", listener: () => void): this; prependOnceListener(event: "resume", listener: () => void): this; prependOnceListener(event: "SIGCONT", listener: () => void): this; @@ -2104,6 +2482,8 @@ declare module "readline" { prependOnceListener(event: "SIGTSTP", listener: () => void): this; } + type ReadLine = Interface; // type forwarded for backwards compatiblity + type Completer = (line: string) => CompleterResult; type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; @@ -2120,18 +2500,20 @@ declare module "readline" { removeHistoryDuplicates?: boolean; } - function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine; - function createInterface(options: ReadLineOptions): ReadLine; + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; - function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; function clearLine(stream: NodeJS.WritableStream, dir: number): void; function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - interface Context { } + interface Context { + [key: string]: any; + } interface BaseOptions { /** * Specifies the filename used in stack traces produced by this script. @@ -2227,42 +2609,42 @@ declare module "child_process" { addListener(event: "close", listener: (code: number, signal: string) => void): this; addListener(event: "disconnect", listener: () => void): this; addListener(event: "error", listener: (err: Error) => void): this; - addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; addListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close", code: number, signal: string): boolean; emit(event: "disconnect"): boolean; emit(event: "error", err: Error): boolean; - emit(event: "exit", code: number, signal: string): boolean; + emit(event: "exit", code: number | null, signal: string | null): boolean; emit(event: "message", message: any, sendHandle: net.Socket | net.Server): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: (code: number, signal: string) => void): this; on(event: "disconnect", listener: () => void): this; on(event: "error", listener: (err: Error) => void): this; - on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "exit", listener: (code: number | null, signal: string | null) => void): this; on(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: (code: number, signal: string) => void): this; once(event: "disconnect", listener: () => void): this; once(event: "error", listener: (err: Error) => void): this; - once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "exit", listener: (code: number | null, signal: string | null) => void): this; once(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: (code: number, signal: string) => void): this; prependListener(event: "disconnect", listener: () => void): this; prependListener(event: "error", listener: (err: Error) => void): this; - prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; prependListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: (code: number, signal: string) => void): this; prependOnceListener(event: "disconnect", listener: () => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this; - prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "exit", listener: (code: number | null, signal: string | null) => void): this; prependOnceListener(event: "message", listener: (message: any, sendHandle: net.Socket | net.Server) => void): this; } @@ -2285,6 +2667,7 @@ declare module "child_process" { windowsHide?: boolean; } + function spawn(command: string, options?: SpawnOptions): ChildProcess; function spawn(command: string, args?: ReadonlyArray, options?: SpawnOptions): ChildProcess; interface ExecOptions { @@ -2599,6 +2982,20 @@ declare module "url" { function domainToASCII(domain: string): string; function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * @param url The file URL string or URL object to convert to a path. + */ + function fileURLToPath(url: string | URL): string; + + /** + * This function ensures that path is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * @param url The path to convert to a File URL. + */ + function pathToFileURL(url: string): URL; + interface URLFormatOptions { auth?: boolean; fragment?: boolean; @@ -2651,6 +3048,7 @@ declare module "dns" { family?: number; hints?: number; all?: boolean; + verbatim?: boolean; } interface LookupOneOptions extends LookupOptions { @@ -3974,12 +4372,26 @@ declare module "fs" { */ function rmdirSync(path: PathLike): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * @default false + */ + recursive?: boolean; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777. + */ + mode?: number; + } + /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function mkdir(path: PathLike, mode: number | string | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; + function mkdir(path: PathLike, options: number | string | MakeDirectoryOptions | undefined | null, callback: (err: NodeJS.ErrnoException) => void): void; /** * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. @@ -3992,17 +4404,19 @@ declare module "fs" { /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function __promisify__(path: PathLike, mode?: number | string | null): Promise; + function __promisify__(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; } /** * Synchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function mkdirSync(path: PathLike, mode?: number | string | null): void; + function mkdirSync(path: PathLike, options?: number | string | MakeDirectoryOptions | null): void; /** * Asynchronously creates a unique temporary directory. @@ -5299,9 +5713,10 @@ declare module "fs" { /** * Asynchronous mkdir(2) - create a directory. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. - * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. */ - function mkdir(path: PathLike, mode?: string | number): Promise; + function mkdir(path: PathLike, options?: number | string | MakeDirectoryOptions | null): Promise; /** * Asynchronous readdir(3) - read a directory. @@ -5606,7 +6021,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, * until an absolute path is found. If after using all {from} paths still no absolute path is found, @@ -5855,6 +6270,13 @@ declare module "tls" { * May be used to distinguish TLS sockets from regular ones. */ encrypted: boolean; + + /** + * String containing the selected ALPN protocol. + * When ALPN has no selected protocol, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol?: string; + /** * Returns an object representing the cipher name and the SSL/TLS protocol version of the current connection. * @returns Returns an object representing the cipher name @@ -6209,8 +6631,8 @@ declare module "crypto" { interface Signer extends NodeJS.WritableStream { update(data: string | Buffer | NodeJS.TypedArray | DataView): Signer; update(data: string, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }): Buffer; - sign(private_key: string | { key: string; passphrase: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }): Buffer; + sign(private_key: string | { key: string; passphrase?: string, padding?: number, saltLength?: number }, output_format: HexBase64Latin1Encoding): string; } function createVerify(algorith: string, options?: stream.WritableOptions): Verify; interface Verify extends NodeJS.WritableStream { @@ -6329,6 +6751,120 @@ declare module "crypto" { function timingSafeEqual(a: Buffer | NodeJS.TypedArray | DataView, b: Buffer | NodeJS.TypedArray | DataView): boolean; /** @deprecated since v10.0.0 */ const DEFAULT_ENCODING: string; + + export type KeyType = 'rsa' | 'dsa' | 'ec'; + export type KeyFormat = 'pem' | 'der'; + + interface BasePrivateKeyEncodingOptions { + format: T; + cipher: string; + passphrase: string; + } + + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * @default 0x10001 + */ + publicExponent?: number; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs1' | 'pkcs8'; + }; + } + + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + + publicKeyEncoding: { + type: 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'pkcs8'; + }; + } + + interface ECKeyPairOptions { + /** + * Name of the curve to use. + */ + namedCurve: string; + + publicKeyEncoding: { + type: 'pkcs1' | 'spki'; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: 'sec1' | 'pkcs8'; + }; + } + + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult; + function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult; + + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void; + function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void; + + namespace generateKeyPair { + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "rsa", options: RSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "dsa", options: DSAKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'pem'>): Promise<{ publicKey: string, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'pem', 'der'>): Promise<{ publicKey: string, privateKey: Buffer }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'pem'>): Promise<{ publicKey: Buffer, privateKey: string }>; + function __promisify__(type: "ec", options: ECKeyPairOptions<'der', 'der'>): Promise<{ publicKey: Buffer, privateKey: Buffer }>; + } } declare module "stream" { @@ -7204,20 +7740,20 @@ declare module "v8" { } declare module "timers" { - function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; + function setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; namespace setTimeout { function __promisify__(ms: number): Promise; function __promisify__(ms: number, value: T): Promise; } - function clearTimeout(timeoutId: NodeJS.Timer): void; - function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timer; - function clearInterval(intervalId: NodeJS.Timer): void; - function setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; + function clearTimeout(timeoutId: NodeJS.Timeout): void; + function setInterval(callback: (...args: any[]) => void, ms: number, ...args: any[]): NodeJS.Timeout; + function clearInterval(intervalId: NodeJS.Timeout): void; + function setImmediate(callback: (...args: any[]) => void, ...args: any[]): NodeJS.Immediate; namespace setImmediate { function __promisify__(): Promise; function __promisify__(value: T): Promise; } - function clearImmediate(immediateId: any): void; + function clearImmediate(immediateId: NodeJS.Immediate): void; } declare module "console" { @@ -7411,7 +7947,7 @@ declare module "http2" { export interface ServerStreamResponseOptions { endStream?: boolean; - getTrailers?: (trailers: OutgoingHttpHeaders) => void; + waitForTrailers?: boolean; } export interface StatOptions { @@ -7436,6 +7972,9 @@ declare module "http2" { readonly destroyed: boolean; readonly pending: boolean; readonly rstCode: number; + readonly sentHeaders: OutgoingHttpHeaders; + readonly sentInfoHeaders?: OutgoingHttpHeaders[]; + readonly sentTrailers?: OutgoingHttpHeaders; readonly session: Http2Session; readonly state: StreamState; /** @@ -7461,6 +8000,7 @@ declare module "http2" { addListener(event: "streamClosed", listener: (code: number) => void): this; addListener(event: "timeout", listener: () => void): this; addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "aborted"): boolean; @@ -7476,6 +8016,7 @@ declare module "http2" { emit(event: "streamClosed", code: number): boolean; emit(event: "timeout"): boolean; emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "aborted", listener: () => void): this; @@ -7491,6 +8032,7 @@ declare module "http2" { on(event: "streamClosed", listener: (code: number) => void): this; on(event: "timeout", listener: () => void): this; on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "aborted", listener: () => void): this; @@ -7506,6 +8048,7 @@ declare module "http2" { once(event: "streamClosed", listener: (code: number) => void): this; once(event: "timeout", listener: () => void): this; once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "aborted", listener: () => void): this; @@ -7521,6 +8064,7 @@ declare module "http2" { prependListener(event: "streamClosed", listener: (code: number) => void): this; prependListener(event: "timeout", listener: () => void): this; prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "aborted", listener: () => void): this; @@ -7536,6 +8080,9 @@ declare module "http2" { prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + + sendTrailers(headers: OutgoingHttpHeaders): this; } export interface ClientHttp2Stream extends Http2Stream { @@ -7645,6 +8192,7 @@ declare module "http2" { addListener(event: "localSettings", listener: (settings: Settings) => void): this; addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; addListener(event: "timeout", listener: () => void): this; + addListener(event: "ping", listener: () => void): this; emit(event: string | symbol, ...args: any[]): boolean; emit(event: "close"): boolean; @@ -7654,6 +8202,7 @@ declare module "http2" { emit(event: "localSettings", settings: Settings): boolean; emit(event: "remoteSettings", settings: Settings): boolean; emit(event: "timeout"): boolean; + emit(event: "ping"): boolean; on(event: string, listener: (...args: any[]) => void): this; on(event: "close", listener: () => void): this; @@ -7663,6 +8212,7 @@ declare module "http2" { on(event: "localSettings", listener: (settings: Settings) => void): this; on(event: "remoteSettings", listener: (settings: Settings) => void): this; on(event: "timeout", listener: () => void): this; + on(event: "ping", listener: () => void): this; once(event: string, listener: (...args: any[]) => void): this; once(event: "close", listener: () => void): this; @@ -7672,6 +8222,7 @@ declare module "http2" { once(event: "localSettings", listener: (settings: Settings) => void): this; once(event: "remoteSettings", listener: (settings: Settings) => void): this; once(event: "timeout", listener: () => void): this; + once(event: "ping", listener: () => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: "close", listener: () => void): this; @@ -7681,6 +8232,7 @@ declare module "http2" { prependListener(event: "localSettings", listener: (settings: Settings) => void): this; prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "ping", listener: () => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: "close", listener: () => void): this; @@ -7690,6 +8242,7 @@ declare module "http2" { prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "ping", listener: () => void): this; } export interface ClientHttp2Session extends Http2Session { @@ -7769,6 +8322,7 @@ declare module "http2" { peerMaxConcurrentStreams?: number; selectPadding?: (frameLen: number, maxFrameLen: number) => number; settings?: Settings; + createConnection?: (option: SessionOptions) => stream.Duplex; } export type ClientSessionOptions = SessionOptions; diff --git a/types/node/node-tests.ts b/types/node/node-tests.ts index 8c3a8f6f8b..c0f80728fc 100644 --- a/types/node/node-tests.ts +++ b/types/node/node-tests.ts @@ -414,6 +414,19 @@ import { Buffer as ImportedBuffer, SlowBuffer as ImportedSlowBuffer } from "buff const cf = util.promisify(fs.copyFile); cf('/path/to/src', '/path/to/dest', fs.constants.COPYFILE_EXCL).then(console.log); } + + { + fs.mkdir('some/test/path', { + recursive: true, + mode: 0o777, + }, () => { + }); + + fs.mkdirSync('some/test/path', { + recursive: true, + mode: 0o777, + }); + } } /////////////////////////////////////////////////////// @@ -763,6 +776,15 @@ function bufferTests() { ]); assert.equal(params.toString(), 'user=abc&query=first&query=second'); } + + { + let path: string = url.fileURLToPath('file://test'); + path = url.fileURLToPath(new url.URL('file://test')); + } + + { + const path: url.URL = url.pathToFileURL('file://test'); + } } ///////////////////////////////////////////////////// @@ -781,7 +803,10 @@ function bufferTests() { showProxy: true, maxArrayLength: 10, breakLength: 20, - compact: true + compact: true, + sorted(a, b) { + return b.localeCompare(a); + }, }); util.inspect(["This is nice"], { colors: true, @@ -790,7 +815,8 @@ function bufferTests() { showProxy: true, maxArrayLength: null, breakLength: Infinity, - compact: false + compact: false, + sorted: true, }); assert(typeof util.inspect.custom === 'symbol'); @@ -1475,6 +1501,161 @@ async function asyncStreamPipelineFinished() { ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "compressed"); ret = crypto.ECDH.convertKey(key, curve, "hex", "hex", "hybrid"); } + + { + const rsaRes: { + publicKey: Buffer; + privateKey: string; + } = crypto.generateKeyPairSync('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const dsaRes: { + publicKey: string; + privateKey: Buffer; + } = crypto.generateKeyPairSync('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const ecRes: { + publicKey: string; + privateKey: string; + } = crypto.generateKeyPairSync('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + } + + { + crypto.generateKeyPair('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: Buffer, privateKey: string) => {}); + + crypto.generateKeyPair('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: Buffer) => {}); + + crypto.generateKeyPair('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: string) => {}); + } + + { + const generateKeyPairPromisified = util.promisify(crypto.generateKeyPair); + + const rsaRes: Promise<{ + publicKey: Buffer; + privateKey: string; + }> = generateKeyPairPromisified('rsa', { + modulusLength: 123, + publicKeyEncoding: { + format: 'der', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const dsaRes: Promise<{ + publicKey: string; + privateKey: Buffer; + }> = generateKeyPairPromisified('dsa', { + modulusLength: 123, + divisorLength: 123, + publicKeyEncoding: { + format: 'pem', + type: 'spki', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'der', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + + const ecRes: Promise<{ + publicKey: string; + privateKey: string; + }> = generateKeyPairPromisified('ec', { + namedCurve: 'curve', + publicKeyEncoding: { + format: 'pem', + type: 'pkcs1', + }, + privateKeyEncoding: { + cipher: 'some-cipher', + format: 'pem', + passphrase: 'secret', + type: 'pkcs8', + }, + }); + } } ////////////////////////////////////////////////// @@ -2455,6 +2636,8 @@ async function asyncStreamPipelineFinished() { { childProcess.exec("echo test"); childProcess.exec("echo test", { windowsHide: true }); + childProcess.spawn("echo"); + childProcess.spawn("echo", { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true }); childProcess.spawn("echo", ["test"], { windowsHide: true, argv0: "echo-test" }); childProcess.spawn("echo", ["test"], { stdio: [0xdeadbeef, "inherit", undefined, "pipe"] }); @@ -3087,6 +3270,7 @@ import * as p from "process"; process.prependOnceListener("SIGBREAK", () => { }); process.on("newListener", (event: string | symbol, listener: Function) => { }); process.once("removeListener", (event: string | symbol, listener: Function) => { }); + process.on("multipleResolves", (type: NodeJS.MultipleResolveType, prom: Promise, value: any) => {}); const listeners = process.listeners('uncaughtException'); const oldHandler = listeners[listeners.length - 1]; @@ -3100,7 +3284,7 @@ import * as p from "process"; const b: boolean = process.hasUncaughtExceptionCaptureCallback(); } { - process.allowedNodeEnvironmentFlags.has('asdf'); + // process.allowedNodeEnvironmentFlags.has('asdf'); } } @@ -3115,7 +3299,23 @@ import * as p from "process"; } { const writeStream = fs.createWriteStream('./index.d.ts'); - const consoleInstance = new console.Console(writeStream); + let consoleInstance: Console = new console.Console(writeStream); + + consoleInstance = new console.Console(writeStream, writeStream); + consoleInstance = new console.Console(writeStream, writeStream, true); + consoleInstance = new console.Console({ + stdout: writeStream, + stderr: writeStream, + colorMode: 'auto', + ignoreErrors: true + }); + consoleInstance = new console.Console({ + stdout: writeStream, + colorMode: false + }); + consoleInstance = new console.Console({ + stdout: writeStream + }); } } @@ -3420,7 +3620,7 @@ import * as p from "process"; { let _server: repl.REPLServer; let _boolean: boolean; - const _ctx: any = 1; + const _ctx: vm.Context = {}; _server = _server.addListener("exit", () => { }); _server = _server.addListener("reset", () => { }); @@ -3443,9 +3643,46 @@ import * as p from "process"; _server.outputStream.write("test"); const line = _server.inputStream.read(); + _server.clearBufferedCommand(); + _server.displayPrompt(); + _server.displayPrompt(true); + _server.defineCommand("cmd", function(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + }); + _server.defineCommand("cmd", { + help: "", + action(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + } + }); + + repl.start({ + eval() { + // $ExpectType REPLServer + this; + }, + writer() { + // $ExpectType REPLServer + this; + return ""; + } + }); + function test() { throw new repl.Recoverable(new Error("test")); } + + _server.context['key0'] = 1; + _server.context['key1'] = ""; + _server.context['key2'] = true; + _server.context['key3'] = []; + _server.context['key4'] = {}; } } @@ -3491,6 +3728,10 @@ import * as p from "process"; const _err: NodeJS.ErrnoException = err; const _address: dns.LookupAddress[] = addresses; }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); function trueOrFalse(): boolean { return Math.random() > 0.5 ? true : false; @@ -3859,6 +4100,7 @@ import * as constants from 'constants'; http2Session.on('remoteSettings', (settings: http2.Settings) => {}); http2Session.on('stream', (stream: http2.Http2Stream, headers: http2.IncomingHttpHeaders, flags: number) => {}); http2Session.on('timeout', () => {}); + http2Session.on('ping', () => {}); http2Session.destroy(); @@ -3933,6 +4175,7 @@ import * as constants from 'constants'; http2Stream.on('streamClosed', (code: number) => {}); http2Stream.on('timeout', () => {}); http2Stream.on('trailers', (trailers: http2.IncomingHttpHeaders, flags: number) => {}); + http2Stream.on('wantTrailers', () => {}); const aborted: boolean = http2Stream.aborted; const closed: boolean = http2Stream.closed; @@ -3984,7 +4227,7 @@ import * as constants from 'constants'; const options: http2.ServerStreamResponseOptions = { endStream: true, - getTrailers: (trailers: http2.OutgoingHttpHeaders) => {} + waitForTrailers: true, }; serverHttp2Stream.respond(); serverHttp2Stream.respond(headers); @@ -4436,6 +4679,7 @@ import * as constants from 'constants'; //////////////////////////////////////////////////// /// module tests : http://nodejs.org/api/modules.html //////////////////////////////////////////////////// +import moduleModule = require('module'); { require.extensions[".ts"] = () => ""; @@ -4448,6 +4692,8 @@ import * as constants from 'constants'; const b: string[] = Module.builtinModules; let paths: string[] = module.paths; paths = m1.paths; + + moduleModule.createRequireFromPath('./test')('test'); } //////////////////////////////////////////////////// diff --git a/types/node/v0/index.d.ts b/types/node/v0/index.d.ts index 3bc1b3ed5d..1f29bbcc10 100644 --- a/types/node/v0/index.d.ts +++ b/types/node/v0/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for Node.js 0.12 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript , DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /************************************************ @@ -1482,7 +1483,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v0/tslint.json b/types/node/v0/tslint.json index c752378347..88843a11f1 100644 --- a/types/node/v0/tslint.json +++ b/types/node/v0/tslint.json @@ -8,7 +8,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "import-spacing": false, "interface-over-type-literal": false, "jsdoc-format": false, diff --git a/types/node/v4/index.d.ts b/types/node/v4/index.d.ts index 9d7421ff57..26210a1857 100644 --- a/types/node/v4/index.d.ts +++ b/types/node/v4/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Node.js 4.x +// Type definitions for Node.js 4.9 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Sebastian Silbermann // Sander Koenders // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -2055,7 +2055,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * diff --git a/types/node/v4/tslint.json b/types/node/v4/tslint.json index 518f58df03..fb3c172995 100644 --- a/types/node/v4/tslint.json +++ b/types/node/v4/tslint.json @@ -8,7 +8,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "import-spacing": false, "interface-over-type-literal": false, "jsdoc-format": false, diff --git a/types/node/v6/index.d.ts b/types/node/v6/index.d.ts index 9c3da40b2a..5ed74da702 100644 --- a/types/node/v6/index.d.ts +++ b/types/node/v6/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Node.js v6.x +// Type definitions for Node.js 6.14 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Wilco Bakker // Thomas Bouldin // Sebastian Silbermann @@ -3040,7 +3040,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * @@ -3617,8 +3617,8 @@ declare module "crypto" { export interface Signer extends NodeJS.WritableStream { update(data: string | Buffer): Signer; update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase?: string }): Buffer; + sign(private_key: string | { key: string; passphrase?: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { diff --git a/types/node/v6/tslint.json b/types/node/v6/tslint.json index 82d575f726..a1956bd303 100644 --- a/types/node/v6/tslint.json +++ b/types/node/v6/tslint.json @@ -8,7 +8,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "import-spacing": false, "interface-over-type-literal": false, "jsdoc-format": false, diff --git a/types/node/v7/index.d.ts b/types/node/v7/index.d.ts index 68046fe384..932d988912 100644 --- a/types/node/v7/index.d.ts +++ b/types/node/v7/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Node.js v7.x +// Type definitions for Node.js 7.10 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Parambir Singh // Christian Vaagland Tellnes // Wilco Bakker @@ -3065,7 +3065,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * @@ -3654,8 +3654,8 @@ declare module "crypto" { export interface Signer extends NodeJS.WritableStream { update(data: string | Buffer): Signer; update(data: string | Buffer, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase?: string }): Buffer; + sign(private_key: string | { key: string; passphrase?: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { diff --git a/types/node/v7/tslint.json b/types/node/v7/tslint.json index 518f58df03..fb3c172995 100644 --- a/types/node/v7/tslint.json +++ b/types/node/v7/tslint.json @@ -8,7 +8,6 @@ "ban-types": false, "callable-types": false, "comment-format": false, - "dt-header": false, "import-spacing": false, "interface-over-type-literal": false, "jsdoc-format": false, diff --git a/types/node/v8/index.d.ts b/types/node/v8/index.d.ts index 04069b2064..6a2ca10859 100644 --- a/types/node/v8/index.d.ts +++ b/types/node/v8/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Node.js 8.10.x +// Type definitions for Node.js 8.10 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Parambir Singh // Christian Vaagland Tellnes // Wilco Bakker @@ -2434,6 +2434,7 @@ declare module "dns" { family?: number; hints?: number; all?: boolean; + verbatim?: boolean; } export interface LookupOneOptions extends LookupOptions { @@ -4769,7 +4770,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * @@ -5326,8 +5327,8 @@ declare module "crypto" { export interface Signer extends NodeJS.WritableStream { update(data: string | Buffer | DataView): Signer; update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase?: string }): Buffer; + sign(private_key: string | { key: string; passphrase?: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { diff --git a/types/node/v8/node-tests.ts b/types/node/v8/node-tests.ts index e1d14b9089..aa67464043 100644 --- a/types/node/v8/node-tests.ts +++ b/types/node/v8/node-tests.ts @@ -3075,6 +3075,10 @@ namespace dns_tests { const _err: NodeJS.ErrnoException = err; const _address: dns.LookupAddress[] = addresses; }); + dns.lookup("nodejs.org", { all: true, verbatim: true }, (err, addresses) => { + const _err: NodeJS.ErrnoException = err; + const _address: dns.LookupAddress[] = addresses; + }); function trueOrFalse(): boolean { return Math.random() > 0.5 ? true : false; diff --git a/types/node/v8/tslint.json b/types/node/v8/tslint.json index 45064d266f..4c1432c003 100644 --- a/types/node/v8/tslint.json +++ b/types/node/v8/tslint.json @@ -14,6 +14,7 @@ "no-namespace": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, + "no-single-declare-module": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, diff --git a/types/node/v9/index.d.ts b/types/node/v9/index.d.ts index a1b7e58ad3..3660d87725 100644 --- a/types/node/v9/index.d.ts +++ b/types/node/v9/index.d.ts @@ -1,7 +1,7 @@ -// Type definitions for Node.js 9.6.x +// Type definitions for Node.js 9.6 // Project: http://nodejs.org/ -// Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitions by: Microsoft TypeScript +// DefinitelyTyped // Parambir Singh // Christian Vaagland Tellnes // Wilco Bakker @@ -1881,66 +1881,372 @@ declare module "punycode" { } declare module "repl" { - import * as stream from "stream"; - import * as readline from "readline"; + import { Interface, Completer, AsyncCompleter } from "readline"; + import { Context } from "vm"; + import { InspectOptions } from "util"; - export interface ReplOptions { + interface ReplOptions { + /** + * The input prompt to display. + * Default: `"> "` + */ prompt?: string; + /** + * The `Readable` stream from which REPL input will be read. + * Default: `process.stdin` + */ input?: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + * Default: `process.stdout` + */ output?: NodeJS.WritableStream; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ terminal?: boolean; - eval?: Function; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * Default: the REPL instance's `terminal` value. + */ useColors?: boolean; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * Default: `false`. + */ useGlobal?: boolean; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * Default: `false`. + */ ignoreUndefined?: boolean; - writer?: Function; - completer?: Function; - replMode?: any; - breakEvalOnSigint?: any; + /** + * The function to invoke to format the output of each command before writing to `output`. + * Default: a wrapper for `util.inspect`. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v11.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * Default: `false`. + */ + breakEvalOnSigint?: boolean; } - export interface REPLServer extends readline.ReadLine { - context: any; - inputStream: NodeJS.ReadableStream; - outputStream: NodeJS.WritableStream; + type REPLEval = (this: REPLServer, evalCmd: string, context: Context, file: string, cb: (err: Error | null, result: any) => void) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; - defineCommand(keyword: string, cmd: Function | { help: string, action: Function }): void; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { options: InspectOptions }; + + type REPLCommandAction = (this: REPLServer, text: string) => void; + + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + + /** + * Provides a customizable Read-Eval-Print-Loop (REPL). + * + * Instances of `repl.REPLServer` will accept individual lines of user input, evaluate those + * according to a user-defined evaluation function, then output the result. Input and output + * may be from `stdin` and `stdout`, respectively, or may be connected to any Node.js `stream`. + * + * Instances of `repl.REPLServer` support automatic completion of inputs, simplistic Emacs-style + * line editing, multi-line inputs, ANSI-styled output, saving and restoring current REPL session + * state, error recovery, and customizable evaluation functions. + * + * Instances of `repl.REPLServer` are created using the `repl.start()` method and _should not_ + * be created directly using the JavaScript `new` keyword. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_repl + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: { readonly [name: string]: REPLCommand | undefined }; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + + /** + * Used to add new `.`-prefixed commands to the REPL instance. Such commands are invoked + * by typing a `.` followed by the `keyword`. + * + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_replserver_definecommand_keyword_cmd + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * Readies the REPL instance for input from the user, printing the configured `prompt` to a + * new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the 'prompt'. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @param preserveCursor When `true`, the cursor placement will not be reset to `0`. + */ displayPrompt(preserveCursor?: boolean): void; + /** + * Clears any command that has been buffered but not yet executed. + * + * This method is primarily intended to be called from within the action function for + * commands registered using the `replServer.defineCommand()` method. + * + * @since v9.0.0 + */ + clearBufferedCommand(): void; /** * events.EventEmitter - * 1. exit - * 2. reset + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset */ addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; addListener(event: "exit", listener: () => void): this; - addListener(event: "reset", listener: (...args: any[]) => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; emit(event: "exit"): boolean; - emit(event: "reset", context: any): boolean; + emit(event: "reset", context: Context): boolean; on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; on(event: "exit", listener: () => void): this; - on(event: "reset", listener: (...args: any[]) => void): this; + on(event: "reset", listener: (context: Context) => void): this; once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; once(event: "exit", listener: () => void): this; - once(event: "reset", listener: (...args: any[]) => void): this; + once(event: "reset", listener: (context: Context) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; prependListener(event: "exit", listener: () => void): this; - prependListener(event: "reset", listener: (...args: any[]) => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; prependOnceListener(event: "exit", listener: () => void): this; - prependOnceListener(event: "reset", listener: (...args: any[]) => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; } - export function start(options?: string | ReplOptions): REPLServer; + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + export const REPL_MODE_SLOPPY: symbol; // TODO: unique symbol - export class Recoverable extends SyntaxError { + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + export const REPL_MODE_STRICT: symbol; // TODO: unique symbol + + /** + * Creates and starts a `repl.REPLServer` instance. + * + * @param options The options for the `REPLServer`. If `options` is a string, then it specifies + * the input prompt. + */ + function start(options?: string | ReplOptions): REPLServer; + + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { err: Error; constructor(err: Error); @@ -1951,7 +2257,7 @@ declare module "readline" { import * as events from "events"; import * as stream from "stream"; - export interface Key { + interface Key { sequence?: string; name?: string; ctrl?: boolean; @@ -1959,12 +2265,33 @@ declare module "readline" { shift?: boolean; } - export interface ReadLine extends events.EventEmitter { + class Interface extends events.EventEmitter { + readonly terminal: boolean; + + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v10.x/docs/api/readline.html#readline_class_interface + */ + protected constructor(options: ReadLineOptions); + setPrompt(prompt: string): void; prompt(preserveCursor?: boolean): void; question(query: string, callback: (answer: string) => void): void; - pause(): ReadLine; - resume(): ReadLine; + pause(): this; + resume(): this; close(): void; write(data: string | Buffer, key?: Key): void; @@ -2034,12 +2361,14 @@ declare module "readline" { prependOnceListener(event: "SIGTSTP", listener: () => void): this; } + type ReadLine = Interface; // type forwarded for backwards compatiblity + type Completer = (line: string) => CompleterResult; type AsyncCompleter = (line: string, callback: (err: any, result: CompleterResult) => void) => any; - export type CompleterResult = [string[], string]; + type CompleterResult = [string[], string]; - export interface ReadLineOptions { + interface ReadLineOptions { input: NodeJS.ReadableStream; output?: NodeJS.WritableStream; completer?: Completer | AsyncCompleter; @@ -2050,18 +2379,20 @@ declare module "readline" { removeHistoryDuplicates?: boolean; } - export function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): ReadLine; - export function createInterface(options: ReadLineOptions): ReadLine; + function createInterface(input: NodeJS.ReadableStream, output?: NodeJS.WritableStream, completer?: Completer | AsyncCompleter, terminal?: boolean): Interface; + function createInterface(options: ReadLineOptions): Interface; - export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; - export function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: ReadLine): void; - export function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; - export function clearLine(stream: NodeJS.WritableStream, dir: number): void; - export function clearScreenDown(stream: NodeJS.WritableStream): void; + function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number): void; + function emitKeypressEvents(stream: NodeJS.ReadableStream, interface?: Interface): void; + function moveCursor(stream: NodeJS.WritableStream, dx: number | string, dy: number | string): void; + function clearLine(stream: NodeJS.WritableStream, dir: number): void; + function clearScreenDown(stream: NodeJS.WritableStream): void; } declare module "vm" { - export interface Context { } + export interface Context { + [key: string]: any; + } export interface ScriptOptions { filename?: string; lineOffset?: number; @@ -4856,7 +5187,7 @@ declare module "path" { /** * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. * - * Starting from leftmost {from} paramter, resolves {to} to an absolute path. + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. * * If {to} isn't already absolute, {from} arguments are prepended in right to left order, until an absolute path is found. If after using all {from} paths still no absolute path is found, the current working directory is used as well. The resulting path is normalized, and trailing slashes are removed unless the path gets resolved to the root directory. * @@ -5397,8 +5728,8 @@ declare module "crypto" { export interface Signer extends NodeJS.WritableStream { update(data: string | Buffer | DataView): Signer; update(data: string | Buffer | DataView, input_encoding: Utf8AsciiLatin1Encoding): Signer; - sign(private_key: string | { key: string; passphrase: string }): Buffer; - sign(private_key: string | { key: string; passphrase: string }, output_format: HexBase64Latin1Encoding): string; + sign(private_key: string | { key: string; passphrase?: string }): Buffer; + sign(private_key: string | { key: string; passphrase?: string }, output_format: HexBase64Latin1Encoding): string; } export function createVerify(algorith: string): Verify; export interface Verify extends NodeJS.WritableStream { diff --git a/types/node/v9/node-tests.ts b/types/node/v9/node-tests.ts index 03f641e216..c93079b39f 100644 --- a/types/node/v9/node-tests.ts +++ b/types/node/v9/node-tests.ts @@ -3038,7 +3038,7 @@ namespace repl_tests { { let _server: repl.REPLServer; let _boolean: boolean; - let _ctx: any; + const _ctx: vm.Context = {}; _server = _server.addListener("exit", () => { }); _server = _server.addListener("reset", () => { }); @@ -3059,9 +3059,42 @@ namespace repl_tests { _server = _server.prependOnceListener("reset", () => { }); _server.outputStream.write("test"); - let line = _server.inputStream.read(); + const line = _server.inputStream.read(); - throw new repl.Recoverable(new Error("test")); + _server.clearBufferedCommand(); + _server.displayPrompt(); + _server.displayPrompt(true); + _server.defineCommand("cmd", function(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + }); + _server.defineCommand("cmd", { + help: "", + action(text) { + // $ExpectType string + text; + // $ExpectType REPLServer + this; + } + }); + + repl.start({ + eval() { + // $ExpectType REPLServer + this; + }, + writer() { + // $ExpectType REPLServer + this; + return ""; + } + }); + + function test() { + throw new repl.Recoverable(new Error("test")); + } } } diff --git a/types/node/v9/tslint.json b/types/node/v9/tslint.json index 45064d266f..4c1432c003 100644 --- a/types/node/v9/tslint.json +++ b/types/node/v9/tslint.json @@ -14,6 +14,7 @@ "no-namespace": false, "no-redundant-jsdoc": false, "no-redundant-jsdoc-2": false, + "no-single-declare-module": false, "no-unnecessary-class": false, "no-unnecessary-generics": false, "no-unnecessary-qualifier": false, diff --git a/types/nodegit/commit.d.ts b/types/nodegit/commit.d.ts index 11ab938130..57e8c55d87 100644 --- a/types/nodegit/commit.d.ts +++ b/types/nodegit/commit.d.ts @@ -9,6 +9,10 @@ import { Tree } from './tree'; import { TreeEntry } from './tree-entry'; import { Diff } from './diff'; +export interface HistoryEventEmitter extends EventEmitter { + start(): void; +} + export class Commit { static create(repo: Repository, updateRef: string, author: Signature, committer: Signature, messageEncoding: string, message: string, tree: Tree, parentCount: number, parents: any[]): Oid; static createV(id: Oid, repo: Repository, updateRef: string, author: Signature, committer: Signature, messageEncoding: string, message: string, tree: Tree, parentCount: number): number; @@ -75,11 +79,11 @@ export class Commit { /** * Walk the history from this commit backwards. * An EventEmitter is returned that will emit a "commit" event for each commit in the history, and one "end" - * event when the walk is completed. Don't forget to call start() on the returned event. + * event when the walk is completed. Don't forget to call start() on the returned EventEmitter. * * */ - history(): EventEmitter; + history(): HistoryEventEmitter; /** * Retrieve the commit's parents as commit objects. * diff --git a/types/nodegit/repository.d.ts b/types/nodegit/repository.d.ts index 20da9ce052..710c0531cd 100644 --- a/types/nodegit/repository.d.ts +++ b/types/nodegit/repository.d.ts @@ -78,7 +78,7 @@ export class Repository { /** * Creates a branch with the passed in name pointing to the commit */ - createBranch(name: string, commit: Commit | string | Oid, force: boolean): Promise; + createBranch(name: string, commit: Commit | string | Oid, force?: boolean): Promise; /** * Look up a refs's commit. */ @@ -175,7 +175,7 @@ export class Repository { * Fetches from all remotes. This is done in series due to deadlocking issues with fetching from many remotes that can happen. */ fetchAll(fetchOptions?: FetchOptions, callback?: Function): Promise; - mergeBranches(to: string | Reference, from: string | Reference, signature: Signature, mergePreference: Merge.PREFERENCE, mergeOptions?: MergeOptions): Promise; + mergeBranches(to: string | Reference, from: string | Reference, signature?: Signature, mergePreference?: Merge.PREFERENCE, mergeOptions?: MergeOptions): Promise; /** * Rebases a branch onto another branch */ diff --git a/types/nookies/index.d.ts b/types/nookies/index.d.ts new file mode 100644 index 0000000000..1eaab3ce64 --- /dev/null +++ b/types/nookies/index.d.ts @@ -0,0 +1,20 @@ +// Type definitions for nookies 1.1 +// Project: https://github.com/maticzav/nookies#readme +// Definitions by: Andreas Bergqvist +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { NextContext } from 'next'; +import { CookieParseOptions, CookieSerializeOptions } from 'cookie'; + +export function parseCookies(ctx: NextContext, options?: CookieParseOptions): { [key: string]: string }; +export function setCookie(ctx: NextContext, name: string, value: string, options?: CookieSerializeOptions): void; +export function destroyCookie(ctx: NextContext, name: string): void; + +declare const Nookies: { + set(ctx: NextContext, name: string, value: string, options?: CookieSerializeOptions): void; + get(ctx: NextContext, options?: CookieParseOptions): { [key: string]: string }; + destroy(ctx: NextContext, name: string): void; +}; + +export default Nookies; diff --git a/types/nookies/nookies-tests.ts b/types/nookies/nookies-tests.ts new file mode 100644 index 0000000000..2fe560affc --- /dev/null +++ b/types/nookies/nookies-tests.ts @@ -0,0 +1,9 @@ +import nookies, { parseCookies, setCookie, destroyCookie } from 'nookies'; + +nookies.set({ pathname: '', query: {}, asPath: ''}, 'test-cookie', 'test-value'); +nookies.get({ pathname: '', query: {}, asPath: ''}); +nookies.destroy({ pathname: '', query: {}, asPath: ''}, 'test-cookie'); + +parseCookies({ pathname: '', query: {}, asPath: ''}); +setCookie({ pathname: '', query: {}, asPath: ''}, 'test-cookie', 'test-value'); +destroyCookie({ pathname: '', query: {}, asPath: ''}, 'test-cookie'); diff --git a/types/nookies/tsconfig.json b/types/nookies/tsconfig.json new file mode 100644 index 0000000000..15118a6178 --- /dev/null +++ b/types/nookies/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "nookies-tests.ts" + ] +} diff --git a/types/nookies/tslint.json b/types/nookies/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/nookies/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/normalize-url/index.d.ts b/types/normalize-url/index.d.ts index ec70be130b..fd76c4f72a 100644 --- a/types/normalize-url/index.d.ts +++ b/types/normalize-url/index.d.ts @@ -1,14 +1,20 @@ -// Type definitions for normalize-url 1.9 +// Type definitions for normalize-url 3.3 // Project: https://github.com/sindresorhus/normalize-url // Definitions by: odin3 // BendingBender +// Mathieu M-Gosselin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped declare namespace normalizeUrl { interface Options { + defaultProtocol?: string; + forceHttp?: boolean; + forceHttps?: boolean; normalizeProtocol?: boolean; normalizeHttps?: boolean; + sortQueryParameters?: boolean; stripFragment?: boolean; + stripHash?: boolean; stripWWW?: boolean; removeQueryParameters?: Array; removeTrailingSlash?: boolean; diff --git a/types/novnc-core/tslint.json b/types/novnc-core/tslint.json index 3224b40b8b..22e051f9bf 100644 --- a/types/novnc-core/tslint.json +++ b/types/novnc-core/tslint.json @@ -1,6 +1,7 @@ { "extends": "dtslint/dt.json", "rules": { + "no-angle-bracket-type-assertion": false, "no-const-enum": false } } diff --git a/types/npm-package-arg/index.d.ts b/types/npm-package-arg/index.d.ts index bb1a0d8550..d83c95a6a7 100644 --- a/types/npm-package-arg/index.d.ts +++ b/types/npm-package-arg/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for npm-package-arg 5.1 +// Type definitions for npm-package-arg 6.1 // Project: https://github.com/npm/npm-package-arg // Definitions by: Melvin Groenhoff +// Jason // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 /** * Throws if the package name is invalid, a dist-tag is invalid or a URL's protocol is not supported. @@ -20,7 +22,12 @@ declare namespace npa { * Something like: 1.2, ^1.7.17, http://x.com/foo.tgz, git+https://github.com/user/foo, bitbucket:user/foo, file:foo.tar.gz or file:../foo/bar/. If not included then the default is latest. * @param where Optionally the path to resolve file paths relative to. Defaults to process.cwd() */ - function resolve(name: string, spec: string, where?: string): Result; + function resolve(name: string, spec: string, where?: string): + FileResult | + HostedGitResult | + URLResult | + AliasResult | + RegistryResult; class Result { /** @@ -33,52 +40,95 @@ declare namespace npa { * * directory - A local directory. * * remote - An http url (presumably to a tgz) */ - type: "git" | "tag" | "version" | "range" | "file" | "directory" | "remote"; - /** - * If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. - */ + type: + | "git" + | "tag" + | "version" + | "range" + | "file" + | "directory" + | "remote" + | "alias"; + + /** If true this specifier refers to a resource hosted on a registry. This is true for tag, version and range types. */ registry: boolean; - /** - * If known, the name field expected in the resulting pkg. - */ + + /** If known, the name field expected in the resulting pkg. */ name: string | null; - /** - * If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. - */ + + /** If a name is something like @org/module then the scope field will be set to @org. If it doesn't have a scoped name, then scope is null. */ scope: string | null; - /** - * A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. - */ + + /** A version of name escaped to match the npm scoped packages specification. Mostly used when making requests against a registry. When name is null, escapedName will also be null. */ escapedName: string | null; - /** - * The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). - */ + + /** The specifier part that was parsed out in calls to npa(arg), or the value of spec in calls to `npa.resolve(name, spec). */ rawSpec: string; - /** - * The normalized specifier, for saving to package.json files. null for registry dependencies. - */ + + /** The normalized specifier, for saving to package.json files. null for registry dependencies. */ saveSpec: string | null; - /** - * The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. - */ + + /** The version of the specifier to be used to fetch this resource. null for shortcuts to hosted git dependencies as there isn't just one URL to try with them. */ fetchSpec: string | null; - /** - * If set, this is a semver specifier to match against git tags with - */ + + /** If set, this is a semver specifier to match against git tags with */ gitRange?: string; - /** - * If set, this is the specific committish to use with a git dependency. - */ + + /** If set, this is the specific committish to use with a git dependency. */ gitCommittish?: string; - /** - * If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. - */ - hosted?: any; - /** - * The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. - */ + + /** If from === 'hosted' then this will be a hosted-git-info object. This property is not included when serializing the object as JSON. */ + hosted?: HostedGit; + + /** The original un-modified string that was provided. If called as npa.resolve(name, spec) then this will be name + '@' + spec. */ raw: string; } + + interface FileResult extends Result { + type: "file" | "directory"; + where: string; + saveSpec: string; + fetchSpec: null | string; + } + + interface HostedGitResult extends Result { + type: "git"; + hosted: HostedGit; + saveSpec: string; + fetchSpec: null | string; + gitRange: undefined | string; + gitCommittish: undefined | string; + } + + interface URLResult extends Result { + saveSpec: string; + type: "git" | "remote"; + fetchSpec: string; + gitCommittish: string | undefined; + gitRange: string | undefined; + } + + interface AliasResult extends Result { + subSpec: Result; + registry: true; + type: "alias"; + saveSpec: null; + fetchSpec: null; + } + + interface RegistryResult extends Result { + registry: true; + type: "version" | "range" | "tag"; + saveSpec: null; + fetchSpec: string; + } + + interface HostedGit { + type: string; + domain: string; + user: string; + project: string; + } } export = npa; diff --git a/types/nuka-carousel/index.d.ts b/types/nuka-carousel/index.d.ts index 8428f92616..97edd08a6d 100644 --- a/types/nuka-carousel/index.d.ts +++ b/types/nuka-carousel/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for nuka-carousel 4.3 +// Type definitions for nuka-carousel 4.4 // Project: https://github.com/FormidableLabs/nuka-carousel -// Definitions by: Roman Charugin , Alex Smith +// Definitions by: Roman Charugin +// Alex Smith +// matt-sungwook // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -17,38 +19,23 @@ export type CarouselSlidesToScrollProp = number | 'auto'; export type CarouselSlideWidthProp = string | number; export interface CarouselSlideRenderControlProps { + /** + * Space between slides, as an integer, but reflected as px + */ + cellSpacing: number; /** * Current slide index */ currentSlide: number; - /** - * Total amount of slides - */ - slideCount: number; /** * Current frame width (px) */ frameWidth: number; /** - * Current slide width (px) + * Go to X slide method + * @param index Slide's index to go */ - slideWidth: number; - /** - * Slides to scroll at once - */ - slidesToScroll: number; - /** - * Space between slides, as an integer, but reflected as px - */ - cellSpacing: number; - /** - * Slides to show at once - */ - slidesToShow: number; - /** - * Infinite mode enabled - */ - wrapAround: boolean; + goToSlide: (index: number) => void; /** * Go to the next slide method */ @@ -58,10 +45,25 @@ export interface CarouselSlideRenderControlProps { */ previousSlide: () => void; /** - * Go to X slide method - * @param index Slide's index to go + * Total amount of slides */ - goToSlide: (index: number) => void; + slideCount: number; + /** + * Slides to scroll at once + */ + slidesToScroll: number; + /** + * Slides to show at once + */ + slidesToShow: number; + /** + * Current slide width (px) + */ + slideWidth: number; + /** + * Infinite mode enabled + */ + wrapAround: boolean; } export type CarouselRenderControl = (props: CarouselSlideRenderControlProps) => JSX.Element; @@ -101,6 +103,11 @@ export interface CarouselProps { * Additional className */ className?: string; + /** + * When set to true, disable keyboard controls + * @default false + */ + disableKeyboardControls?: boolean; /** * Enable mouse swipe/dragging */ @@ -144,6 +151,11 @@ export interface CarouselProps { * Window onResize callback */ onResize?: () => void; + /** + * Pause autoPlay when mouse is over carousel + * @default true + */ + pauseOnHover?: boolean; /** * Function for rendering top left control */ @@ -238,6 +250,10 @@ export interface CarouselState { * Is dragging enabled */ dragging: boolean; + /** + * Easing function name + */ + easing: string; /** * Current frame width */ @@ -245,7 +261,10 @@ export interface CarouselState { /** * Current left value */ + isWrappingAround: boolean; left: number; + pauseOnHover: boolean; + resetWrapAroundPosition: boolean; /** * Total amount of slides */ @@ -262,14 +281,8 @@ export interface CarouselState { * Current top value */ top: number; - /** - * Easing function name - */ - easing: string; /** * Is infinite mode enabled */ - isWrappingAround: boolean; wrapToIndex: boolean; - resetWrapAroundPosition: boolean; } diff --git a/types/nw.js/nw.js-tests.ts b/types/nw.js/nw.js-tests.ts index 853feed3b8..b0387f97a4 100644 --- a/types/nw.js/nw.js-tests.ts +++ b/types/nw.js/nw.js-tests.ts @@ -164,7 +164,7 @@ nw.Screen.chooseDesktopMedia( ["window", "screen"], maxWidth: 1920, maxHeight: 1080 }, - optional: [] + optional: [] as any[] }; //navigator.webkitGetUserMedia( { audio: false, video: constraint }, success_func, fallback_func ); } diff --git a/types/nwmatcher/index.d.ts b/types/nwmatcher/index.d.ts new file mode 100644 index 0000000000..cd0f97360e --- /dev/null +++ b/types/nwmatcher/index.d.ts @@ -0,0 +1,33 @@ +// Type definitions for nwmatcher 1.4 +// Project: https://github.com/dperini/nwmatcher +// Definitions by: Wouter van Heeswijk +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare function nwmatcher(global: { document: Document }): nwmatcher.Matcher; + +declare namespace nwmatcher { + interface Matcher { + // DOM Selection + + first: (selector: string, context?: Element) => Element | null; + match: (element: Element, selector: string, context?: Element) => boolean; + select: (selector: string, context?: Element, callback?: (element: Element) => void) => Element[]; + + // DOM Helpers + + byId: (id: string, from?: Element) => Element | null; + byTag: (tag: string, from?: Element) => Element[]; + byClass: (className: string, from?: Element) => Element[]; + byName: (name: string, from?: Element) => Element[]; + getAttribute: (element: Element, attribute: string) => string | undefined; + hasAttribute: (element: Element, attribute: string) => boolean; + } +} + +declare global { + namespace NW { + const Dom: nwmatcher.Matcher; + } +} + +export = nwmatcher; diff --git a/types/nwmatcher/test/nwmatcher-global.test.ts b/types/nwmatcher/test/nwmatcher-global.test.ts new file mode 100644 index 0000000000..b58e3f2367 --- /dev/null +++ b/types/nwmatcher/test/nwmatcher-global.test.ts @@ -0,0 +1,42 @@ +const matcher = NW.Dom; + +/** + * Test matcher (select/first/...) functions. + */ + +const element: Element = {} as any; + +let resultElementOrNull: Element | null; +let resultStringOrUndefined: string | undefined; +let resultElementArray: Element[]; +let resultBoolean: boolean; + +resultElementOrNull = matcher.first('foo'); +resultElementOrNull = matcher.first('foo', element); +resultElementOrNull = matcher.first('foo'); +resultElementOrNull = matcher.first('foo', element); + +resultBoolean = matcher.match(element, 'foo'); +resultBoolean = matcher.match(element, 'foo', element); + +resultElementArray = matcher.select('foo'); +resultElementArray = matcher.select('foo', element); +resultElementArray = matcher.select('foo', element, (element: Element) => undefined); + +resultElementOrNull = matcher.byId('foo'); +resultElementOrNull = matcher.byId('foo', element); +resultElementOrNull = matcher.byId('foo'); +resultElementOrNull = matcher.byId('foo', element); + +resultElementArray = matcher.byTag('foo'); +resultElementArray = matcher.byTag('foo', element); + +resultElementArray = matcher.byClass('foo'); +resultElementArray = matcher.byClass('foo', element); + +resultElementArray = matcher.byName('foo'); +resultElementArray = matcher.byName('foo', element); + +resultStringOrUndefined = matcher.getAttribute(element, 'foo'); + +resultBoolean = matcher.hasAttribute(element, 'foo'); diff --git a/types/nwmatcher/test/nwmatcher-module.test.ts b/types/nwmatcher/test/nwmatcher-module.test.ts new file mode 100644 index 0000000000..9275502bfd --- /dev/null +++ b/types/nwmatcher/test/nwmatcher-module.test.ts @@ -0,0 +1,45 @@ +import nwmatcher = require('nwmatcher'); + +const global: { document: Document } = { document: {} as any }; +const matcher = nwmatcher(global); + +/** + * Test matcher (select/first/...) functions. + */ + +const element: Element = {} as any; + +let resultElementOrNull: Element | null; +let resultStringOrUndefined: string | undefined; +let resultElementArray: Element[]; +let resultBoolean: boolean; + +resultElementOrNull = matcher.first('foo'); +resultElementOrNull = matcher.first('foo', element); +resultElementOrNull = matcher.first('foo'); +resultElementOrNull = matcher.first('foo', element); + +resultBoolean = matcher.match(element, 'foo'); +resultBoolean = matcher.match(element, 'foo', element); + +resultElementArray = matcher.select('foo'); +resultElementArray = matcher.select('foo', element); +resultElementArray = matcher.select('foo', element, (element: Element) => undefined); + +resultElementOrNull = matcher.byId('foo'); +resultElementOrNull = matcher.byId('foo', element); +resultElementOrNull = matcher.byId('foo'); +resultElementOrNull = matcher.byId('foo', element); + +resultElementArray = matcher.byTag('foo'); +resultElementArray = matcher.byTag('foo', element); + +resultElementArray = matcher.byClass('foo'); +resultElementArray = matcher.byClass('foo', element); + +resultElementArray = matcher.byName('foo'); +resultElementArray = matcher.byName('foo', element); + +resultStringOrUndefined = matcher.getAttribute(element, 'foo'); + +resultBoolean = matcher.hasAttribute(element, 'foo'); diff --git a/types/nwmatcher/tsconfig.json b/types/nwmatcher/tsconfig.json new file mode 100644 index 0000000000..b70d5c6fc3 --- /dev/null +++ b/types/nwmatcher/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 + }, + "files": [ + "index.d.ts", + "test/nwmatcher-global.test.ts", + "test/nwmatcher-module.test.ts" + ] +} \ No newline at end of file diff --git a/types/nwmatcher/tslint.json b/types/nwmatcher/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/nwmatcher/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/oauth-shim/index.d.ts b/types/oauth-shim/index.d.ts new file mode 100644 index 0000000000..a5016aed9f --- /dev/null +++ b/types/oauth-shim/index.d.ts @@ -0,0 +1,47 @@ +// Type definitions for oauth-shim 1.1 +// Project: https://github.com/MrSwitch/node-oauth-shim +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 + +import * as express from "express"; + +export = oauthShim; + +declare const oauthShim: oauthShim.Handler; + +declare namespace oauthShim { + interface Handler extends express.RequestHandler { + interpret: express.RequestHandler; + proxy: express.RequestHandler; + redirect: express.RequestHandler; + unhandled: express.RequestHandler; + + credentials: { + get(query: any, cb: (success: false | object) => void): void; + }; + + init(configs: Config[]): void; + } + + interface Request extends express.Request { + oauthshim?: { + options?: { + [key: string]: any; + path?: string; + }; + redirect?: string; + data?: { + [key: string]: any; + access_token?: string; + }; + }; + } + + interface Config { + client_id: string; + client_secret: string; + grant_url: string; + domain: string; + } +} diff --git a/types/oauth-shim/oauth-shim-tests.ts b/types/oauth-shim/oauth-shim-tests.ts new file mode 100644 index 0000000000..2a287f8bda --- /dev/null +++ b/types/oauth-shim/oauth-shim-tests.ts @@ -0,0 +1,51 @@ +import oauthshim = require("oauth-shim"); +import express = require("express"); + +const app = express(); +app.listen(3000); +app.all("/oauthproxy", oauthshim); + +oauthshim.init([ + { + client_id: "12345", + client_secret: "secret678910", + grant_url: "https://linkedIn.com", + domain: "test.com, example.com/redirect", + }, +]); + +function customHandler(req: oauthshim.Request, res: express.Response, next: express.NextFunction) { + if ( + req.oauthshim && + req.oauthshim.redirect && + req.oauthshim.data && + req.oauthshim.data.access_token && + req.oauthshim.options && + !req.oauthshim.options.path + ) {} + + next(); +} + +app.all( + "/oauthproxy", + oauthshim.interpret, + customHandler, + oauthshim.proxy, + oauthshim.redirect, + oauthshim.unhandled +); + +oauthshim.credentials.get = (query, callback) => { + if (query.client_id === "12345") { + callback({ + client_secret: "secret678910", + }); + } else if (query.client_id === "abcde") { + callback({ + client_secret: "secret123456", + }); + } else { + callback(false); + } +}; diff --git a/types/oauth-shim/tsconfig.json b/types/oauth-shim/tsconfig.json new file mode 100644 index 0000000000..3c7fc0ad5a --- /dev/null +++ b/types/oauth-shim/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", + "oauth-shim-tests.ts" + ] +} diff --git a/types/oauth-shim/tslint.json b/types/oauth-shim/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/oauth-shim/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/oauth/index.d.ts b/types/oauth/index.d.ts index 21b74369e9..9f747e8b84 100644 --- a/types/oauth/index.d.ts +++ b/types/oauth/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for oauth 0.9 // Project: https://github.com/ciaranj/node-oauth#readme // Definitions by: nonAlgebraic +// Eduardo AC // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -25,8 +26,8 @@ export type oauth2tokenCallback = ( export type dataCallback = ( err: {statusCode: number, data?: any}, - result: string | Buffer, - response: IncomingMessage + result?: string | Buffer, + response?: IncomingMessage ) => any; export class OAuth { @@ -285,7 +286,7 @@ export class OAuth2 { get(url: string, access_token: string, - callback: string + callback: dataCallback ): void; protected _getAccessTokenUrl(): string; diff --git a/types/oauth2-server/index.d.ts b/types/oauth2-server/index.d.ts index 27a863051f..a846c489a2 100644 --- a/types/oauth2-server/index.d.ts +++ b/types/oauth2-server/index.d.ts @@ -2,7 +2,8 @@ // Project: https://github.com/oauthjs/node-oauth2-server // Definitions by: Robbie Van Gorkom , // Charles Irick , -// Daniel Fischer +// Daniel Fischer , +// Vitor Santos // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -112,6 +113,56 @@ declare namespace OAuth2Server { redirect(url: string): void; } + abstract class AbstractGrantType { + /** + * Instantiates AbstractGrantType using the supplied options. + * + */ + constructor(options: TokenOptions) + + /** + * Generate access token. Calls Model#generateAccessToken() if implemented. + * + */ + generateAccessToken(client: Client, user: User, scope: string | string[]): Promise; + + /** + * Generate refresh token. Calls Model#generateRefreshToken() if implemented. + * + */ + generateRefreshToken(client: Client, user: User, scope: string | string[]): Promise; + + /** + * Get access token expiration date. + * + */ + getAccessTokenExpiresAt(): Date; + + /** + * Get refresh token expiration date. + * + */ + getRefreshTokenExpiresAt(): Date; + + /** + * Get scope from the request body. + * + */ + getScope(request: Request): string; + + /** + * Validate requested scope. Calls Model#validateScope() if implemented. + * + */ + validateScope(user: User, client: Client, scope: string | string[]): Promise; + + /** + * Retrieve info from the request and client and return token + * + */ + abstract handle(request: Request, client: Client): Promise; + } + interface ServerOptions extends AuthenticateOptions, AuthorizeOptions, TokenOptions { /** * Model object @@ -183,6 +234,11 @@ declare namespace OAuth2Server { * Always revoke the used refresh token and issue a new one for the refresh_token grant. */ alwaysIssueNewRefreshToken?: boolean; + + /** + * Additional supported grant types. + */ + extendedGrantTypes?: { [key: string]: typeof AbstractGrantType }; } /** 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/obelisk.js/tslint.json b/types/obelisk.js/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/obelisk.js/tslint.json +++ b/types/obelisk.js/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/oembed-parser/index.d.ts b/types/oembed-parser/index.d.ts new file mode 100644 index 0000000000..82e37b07f2 --- /dev/null +++ b/types/oembed-parser/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for oembed-parser 1.2 +// Project: https://www.npmjs.com/package/oembed-parser +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function extract(url: string): Promise; + +export function hasProvider(url: string): boolean; + +export interface OembedData { + type: string; + version: string; + html: string; + provider_url: string; + provider_name: string; +} diff --git a/types/oembed-parser/oembed-parser-tests.ts b/types/oembed-parser/oembed-parser-tests.ts new file mode 100644 index 0000000000..9d9ff34470 --- /dev/null +++ b/types/oembed-parser/oembed-parser-tests.ts @@ -0,0 +1,9 @@ +import { extract, hasProvider, OembedData } from "oembed-parser"; + +const url = "https://www.youtube.com/watch?v=8jPQjjsBbIc"; + +extract(url).then(data => { + const parsedData: OembedData = data; +}); + +const providerExists: boolean = hasProvider(url); diff --git a/types/oembed-parser/tsconfig.json b/types/oembed-parser/tsconfig.json new file mode 100644 index 0000000000..fc66a47c65 --- /dev/null +++ b/types/oembed-parser/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", + "oembed-parser-tests.ts" + ] +} diff --git a/types/oembed-parser/tslint.json b/types/oembed-parser/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/oembed-parser/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/office-js/index.d.ts b/types/office-js/index.d.ts index 0bb6cf22b4..3e7f64375f 100644 --- a/types/office-js/index.d.ts +++ b/types/office-js/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for Office.js -// Project: http://dev.office.com +// Project: https://github.com/OfficeDev/office-js // Definitions by: OfficeDev , Lance Austin , Michael Zlatkovsky , Kim Brandl , Ricky Kirkham , Alex Jerabek , Elizabeth Samuel // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -252,7 +252,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -288,7 +288,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -326,7 +326,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -356,7 +356,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -390,7 +390,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -421,7 +421,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Project Y
          Word Y Y
          - * + * * * * @@ -476,7 +476,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          OneNote Y Y
          - * + * * * * @@ -540,7 +540,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          OneNote Y Y
          - * + * * * * @@ -551,7 +551,7 @@ declare namespace Office { */ asyncContext: any; /** - * Gets an {@link Office.Error} object that provides a description of the error, if any error occurred. + * Gets an object that may provide additional information if an error occurred. * * @remarks * @@ -566,6 +566,37 @@ declare namespace Office { * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          * + * + *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Outlook Y (Mailbox Preview)
          + * + * *Supported APIs* + * + * `Office.context.mailbox.item.getCallbackTokenAsync`, `Office.context.mailbox.item.getUserIdentityTokenAsync` + * + * *Supported errors* + * + * + * + * + *
          `AsyncResult.error.name` `AsyncResult.error.message` Description of diagnostics object returned
          HTTPRequestFailure The request has failed. Please look at the diagnostics object for the HTTP error code. The HTTP error code in a JSON object e.g., `{"HTTPCode":"401"}`
          InternalServerErrorThe Exchange server returned an error. Please look at the diagnostics object for more information.The error message from the Exchange server in a JSON object e.g., `{"ErrorText": "The mailbox database is temporarily unavailable"}`
          + */ + diagnostics: any; + /** + * Gets an {@link Office.Error} object that provides a description of the error, if any error occurred. + * + * @remarks + * + * **Support details** + * + * A capital Y in the following matrix indicates that this property is supported in the corresponding Office host application. + * An empty cell indicates that the Office host application doesn't support this enumeration. + * + * For more information about Office host application and server requirements, see + * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. + * + * *Supported hosts, by platform* + * + * * * * @@ -620,7 +651,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -657,9 +688,9 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * - * - * + * + * + * *
          Office for iPad
          Excel Y
          Word Y
          Office for iPad
          Excel Y
          Word Y
          */ commerceAllowed: boolean; @@ -667,7 +698,7 @@ declare namespace Office { * Gets the locale (language) specified by the user for editing the document or item. * * @remarks - * The `contentLanguage` value reflects the **Editing Language** setting specified with **File > Options > Language** in the Office host + * The `contentLanguage` value reflects the **Editing Language** setting specified with **File \> Options \> Language** in the Office host * application. * * In content add-ins for Access web apps, the `contentLanguage` property gets the add-in culture (e.g., "en-GB"). @@ -682,7 +713,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -703,7 +734,7 @@ declare namespace Office { * * The returned value is a string in the RFC 1766 Language tag format, such as en-US. * - * The `displayLanguage` value reflects the current **Display Language** setting specified with **File > Options > Language** in the Office + * The `displayLanguage` value reflects the current **Display Language** setting specified with **File \> Options \> Language** in the Office * host application. * * In content add-ins for Access web apps, the `displayLanguage property` gets the add-in language (e.g., "en-US"). @@ -720,7 +751,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -745,7 +776,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * + * * * * @@ -825,7 +856,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          - * + * * * * @@ -854,7 +885,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for iPad
          Office for iPad
          Excel Y
          PowerPoint Y
          Word Y
          - * + * * * * @@ -905,8 +936,8 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Outlook Y (Mailbox 1.3)
          Office for Windows desktop Office Online (in browser) Office for iPad
          Outlook Y (Mailbox 1.3)
          */ source:Source; @@ -938,7 +969,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1035,6 +1066,10 @@ declare namespace Office { * * * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Outlook Y (Mailbox 1.3)
          PowerPoint Y Y Y
          12007A dialog box is already opened from the task pane. A task pane add-in can only have one dialog box open at a time.
          12009The user chose to ignore the dialog box. This error can occur in online versions of Office, where users may choose not to allow an add-in to present a dialog.
          * * In the callback function passed to the displayDialogAsync method, you can use the properties of the AsyncResult object to return the @@ -1070,9 +1105,9 @@ declare namespace Office { displayDialogAsync(startAddress: string, options?: DialogOptions, callback?: (result: AsyncResult) => void): void; /** * Delivers a message from the dialog box to its parent/opener page. The page calling this API must be on the same domain as the parent. - * @param messageObject Accepts a message from the dialog to deliver to the add-in. + * @param message Accepts a message from the dialog to deliver to the add-in. In addition to a boolean, anything that can serialized to a string including JSON and XML can be sent. */ - messageParent(messageObject: any): void; + messageParent(message: boolean | string): void; /** * Closes the UI container where the JavaScript is executing. * @@ -1083,8 +1118,8 @@ declare namespace Office { * * - Called from a UI-less command button: No effect. Any dialog opened by displayDialogAsync will remain open. * - * - Called from a taskpane: The taskpane will close. Any dialog opened by displayDialogAsync will also close. - * If the taskpane supports pinning and was pinned by the user, it will be un-pinned. + * - Called from a task pane: The task pane will close. Any dialog opened by displayDialogAsync will also close. + * If the task pane supports pinning and was pinned by the user, it will be un-pinned. * * - Called from a module extension: No effect. */ @@ -1122,6 +1157,13 @@ declare namespace Office { * This is best for user experience and performance. */ displayInIframe?: boolean + /** + * Determines if the pop-up blocker dialog will be shown to the user. Defaults to true. + * + * `true` - The framework displays a pop-up to trigger the navigation and avoid the browser's pop-up blocker. + * `false` - The dialog will not be shown and the developer must handle pop-ups (by providing a user interface artifact to trigger the navigation). + */ + promptBeforeOpen?: boolean; /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ @@ -1212,7 +1254,7 @@ declare namespace Office { * * Example: `[{cells: Office.Table.Data, format: {fontColor: "yellow"}}, {cells: {row: 3, column: 4}, format: {borderColor: "white", fontStyle: "bold"}}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -1220,7 +1262,7 @@ declare namespace Office { /** * Only for table bindings in content add-ins for Access. Array of strings. Specifies the column names. */ - columns?: Array + columns?: string[] /** * Only for table bindings in content add-ins for Access. Specifies the pre-defined string "thisRow" to get data in the currently selected row. */ @@ -1250,17 +1292,17 @@ declare namespace Office { */ interface RangeFormatConfiguration { /** - * Specifies the range. Example of using Office.Table enum: Office.Table.All. Example of using RangeCoordinates: {row: 3, column: 4} specifies + * Specifies the range. Example of using Office.Table enum: Office.Table.All. Example of using RangeCoordinates: `{row: 3, column: 4}` specifies * the cell in the 3rd (zero-based) row in the 4th (zero-based) column. */ cells: Office.Table | RangeCoordinates /** - * Specifies the formatting as key-value pairs. Example: {borderColor: "white", fontStyle: "bold"} + * Specifies the formatting as key-value pairs. Example: `{borderColor: "white", fontStyle: "bold"}` */ format: object } /** - * Specifies a cell, or row, or column, by its zero-based row and/or column number. Example: {row: 3, column: 4} specifies the cell in the 3rd + * Specifies a cell, or row, or column, by its zero-based row and/or column number. Example: `{row: 3, column: 4}` specifies the cell in the 3rd * (zero-based) row in the 4th (zero-based) column. */ interface RangeCoordinates { @@ -1334,7 +1376,7 @@ declare namespace Office { /** * The names of the columns involved in the binding. */ - columns?: Array + columns?: string[] /** * A user-defined item of any type that is returned, unchanged, in the asyncContext property of the AsyncResult object that is passed to a callback. */ @@ -1407,7 +1449,7 @@ declare namespace Office { * * Example: `[{cells: Office.Table.Data, format: {fontColor: "yellow"}}, {cells: {row: 3, column: 4}, format: {borderColor: "white", fontStyle: "bold"}}]` */ - cellFormat?: Array + cellFormat?: RangeFormatConfiguration[] /** * Explicitly sets the shape of the data object. If not supplied is inferred from the data type. */ @@ -1460,8 +1502,8 @@ declare namespace Office { /** * Provides access to the properties for Office theme colors. * - * Using Office theme colors lets you coordinate the color scheme of your add-in with the current Office theme selected by the user with File > - * Office Account > Office Theme UI, which is applied across all Office host applications. Using Office theme colors is appropriate for mail and + * Using Office theme colors lets you coordinate the color scheme of your add-in with the current Office theme selected by the user with File \> + * Office Account \> Office Theme UI, which is applied across all Office host applications. Using Office theme colors is appropriate for mail and * task pane add-ins. * * @remarks @@ -1476,7 +1518,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1543,10 +1585,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop
          Office for Windows desktop
          Excel Y
          Outlook Y (in preview)
          PowerPoint Y
          - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y
          */ function select(expression: string, callback?: (result: AsyncResult) => void): Binding; @@ -1565,8 +1607,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          PowerPoint Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          PowerPoint Y Y Y Y
          */ enum ActiveView { @@ -1593,10 +1635,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ enum BindingType { @@ -1632,7 +1674,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1681,7 +1723,7 @@ declare namespace Office { SlideRange, /** * Data is returned or set as an image stream. - * Note: Only applies to data in Excel, Word and PowerPoint. + * Note: Only applies to data in Excel, Word, and PowerPoint. */ Image } @@ -1702,11 +1744,11 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Office for Windows desktop Office Online (in browser) Office for iPad OWA for Devices Office for Mac
          Access Y
          Excel Y Y Y
          Outlook Y Y Y Y
          - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Project Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Project Y
          Word Y Y Y
          */ enum DocumentMode { @@ -1735,8 +1777,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ enum CustomXMLNodeType { @@ -1789,7 +1831,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1811,7 +1853,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Outlook Y Y Y
          PowerPoint Y Y
          - * + * * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          PowerPoint Y Y Y
          */ @@ -1822,6 +1864,14 @@ declare namespace Office { * [Api set: Mailbox 1.7] */ AppointmentTimeChanged, + /** + * Triggers when an attachment is added to or removed from an item. + * + * [Api set: Mailbox Preview] + * + * @beta + */ + AttachmentsChanged, /** * Occurs when data within the binding is changed. * To add an event handler for the BindingDataChanged event of a binding, use the addHandlerAsync method of the Binding object. @@ -1839,10 +1889,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          */ BindingDataChanged, @@ -1862,10 +1912,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          */ BindingSelectionChanged, @@ -1890,16 +1940,16 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          Word Y Y
          */ DocumentSelectionChanged, /** - * Triggers when the selected Outlook item is changed. + * Triggers when a different Outlook item is selected for viewing while the task pane is pinned. * - * [Api set: Mailbox 1.1] + * [Api set: Mailbox 1.5] */ ItemChanged, /** @@ -1918,6 +1968,8 @@ declare namespace Office { * Triggers when the OfficeTheme is changed in Outlook. * * [Api set: Mailbox Preview] + * + * @beta */ OfficeThemeChanged, /** @@ -1949,7 +2001,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -1982,10 +2034,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          */ enum FileType { @@ -2017,10 +2069,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Project Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Project Y
          Word Y Y
          */ enum FilterType { @@ -2048,7 +2100,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -2096,7 +2148,7 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y
          - * + * * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          PowerPoint Y Y Y
          */ @@ -2133,7 +2185,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -2168,10 +2220,10 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y
          Word Y Y
          - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Project Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Project Y
          Word Y Y
          */ enum ValueFormat { @@ -2189,7 +2241,7 @@ declare namespace Office { * Represents a binding to a section of the document. * * @remarks - *
          Requirement SetsMatrixBinding, TableBinding, TextBinding
          + *
          Requirement SetsMatrixBindings, TableBindings, TextBindings
          * * The Binding object exposes the functionality possessed by all bindings regardless of type. * @@ -2209,10 +2261,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ interface Binding { @@ -2496,10 +2548,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ document: Document; @@ -2537,10 +2589,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * @param itemName Name of the bindable object in the document. For Example 'MyExpenses' table in Excel." * @param bindingType The {@link Office.BindingType} for the data. The method returns null if the selected object cannot be coerced into the specified type. @@ -2568,9 +2620,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          * * @param bindingType Specifies the type of the binding object to create. Required. @@ -2603,10 +2655,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param bindingType Specifies the type of the binding object to create. Required. @@ -2632,10 +2684,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -2661,10 +2713,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param id Specifies the unique name of the binding object. Required. @@ -2691,10 +2743,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param id Specifies the unique name to be used to identify the binding object. Required. @@ -2719,8 +2771,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface CustomXmlNode { @@ -2842,8 +2894,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface CustomXmlPart { @@ -2934,8 +2986,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface NodeDeletedEventArgs { @@ -2971,8 +3023,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface NodeInsertedEventArgs { @@ -3002,8 +3054,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface NodeReplacedEventArgs { @@ -3042,8 +3094,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y
          */ interface CustomXmlParts { @@ -3093,8 +3145,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ interface CustomXmlPrefixMappings { @@ -3163,10 +3215,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          */ bindings: Bindings; @@ -3185,8 +3237,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Word Y Y Y Y
          */ customXmlParts: CustomXmlParts; @@ -3205,11 +3257,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          */ mode: DocumentMode; @@ -3228,11 +3280,12 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          OneNote Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          */ settings: Settings; @@ -3251,7 +3304,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * * @@ -3277,11 +3330,12 @@ declare namespace Office { * * *Supported hosts, by platform* *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y
          - * - * - * - * - * + * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Project Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          OneNote Y
          PowerPoint Y Y Y Y
          Project Y
          Word Y Y Y Y
          * * @param eventType For a Document object event, the eventType parameter can be specified as `Office.EventType.Document.SelectionChanged` or @@ -3309,10 +3363,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          PowerPoint Y Y Y
          Word Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          PowerPoint Y Y Y Y
          * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3336,13 +3388,13 @@ declare namespace Office { * The fileType parameter can be specified by using the {@link Office.FileType} enumeration or text values. But the possible values vary with * the host: * - * Excel Online, Win32, Mac, and iOS: `Office.FileType.Compressed` + * Excel for Windows desktop, iPad, and Excel Online: `Office.FileType.Compressed` + * + * Excel for Mac: `Office.FileType.Compressed`, `Office.FileType.Pdf` * - * PowerPoint on Windows desktop, Mac, and iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` + * PowerPoint for Windows desktop, Mac, iPad, and PowerPoint Online: `Office.FileType.Compressed`, `Office.FileType.Pdf` * - * Word on Windows desktop, Word on Mac, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` - * - * Word on iPad: `Office.FileType.Compressed`, `Office.FileType.Text` + * Word for Windows desktop, Mac, iPad, and Word Online: `Office.FileType.Compressed`, `Office.FileType.Pdf`, `Office.FileType.Text` * * **Support details** * @@ -3354,10 +3406,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          PowerPoint Y Y Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param fileType The format in which the file will be returned @@ -3384,10 +3436,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -3435,15 +3487,15 @@ declare namespace Office { * Supported coercionType * * - * Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online + * Excel, PowerPoint, Project, and Word * `Office.CoercionType.Text` (string) * * - * Excel, Word, and Word Online + * Excel and Word * `Office.CoercionType.Matrix` (array of arrays) * * - * Access, Excel, Word, and Word Online + * Access, Excel, and Word * `Office.CoercionType.Table` (TableData object) * * @@ -3451,7 +3503,7 @@ declare namespace Office { * `Office.CoercionType.Html` * * - * Word and Word Online + * Word * `Office.CoercionType.Ooxml` (Office Open XML) * * @@ -3470,12 +3522,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Project Y Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Project Y
          Word Y Y Y Y
          * * @param coercionType The type of data structure to return. See the remarks section for each host's supported coercion types. @@ -3517,10 +3568,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y
          * * @param id The identifier of the object or location to go to. @@ -3546,10 +3597,12 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          OneNote Y
          PowerPoint Y Y Y Y
          Project Y
          Word Y Y Y Y
          * * @param eventType The event type. For document can be 'Document.SelectionChanged' or 'Document.ActiveViewChanged'. @@ -3598,15 +3651,15 @@ declare namespace Office { * Supported coercionType * * - * Excel, Excel Online, PowerPoint, PowerPoint Online, Word, and Word Online + * Excel, PowerPoint, Project, and Word * `Office.CoercionType.Text` (string) * * - * Excel, Word, and Word Online + * Excel and Word * `Office.CoercionType.Matrix` (array of arrays) * * - * Access, Excel, Word, and Word Online + * Access, Excel, and Word * `Office.CoercionType.Table` (TableData object) * * @@ -3614,7 +3667,7 @@ declare namespace Office { * `Office.CoercionType.Html` * * - * Word and Word Online + * Word * `Office.CoercionType.Ooxml` (Office Open XML) * * @@ -3633,11 +3686,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Project Y
          Word Y Y Y Y
          * * @param data The data to be set. Either a string or {@link Office.CoercionType} value, 2d array or TableData object. @@ -3689,8 +3742,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getProjectFieldAsync(fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3714,8 +3767,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getResourceFieldAsync(resourceId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3737,8 +3790,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getSelectedResourceAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3760,8 +3813,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getSelectedTaskAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3785,8 +3838,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getSelectedViewAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3812,8 +3865,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getTaskAsync(taskId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3837,8 +3890,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getTaskFieldAsync(taskId: string, fieldId: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3862,8 +3915,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getWSSUrlAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3914,8 +3967,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getMaxTaskIndexAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3941,8 +3994,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getResourceByIndexAsync(resourceIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3968,8 +4021,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ getTaskByIndexAsync(taskIndex: number, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -3996,8 +4049,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ setResourceFieldAsync(resourceId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4024,8 +4077,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ setTaskFieldAsync(taskId: string, fieldId: number, fieldValue: string | number | boolean | object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4059,9 +4112,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          */ interface File { @@ -4177,9 +4231,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          Word Y Y Y Y
          */ interface MatrixBinding extends Binding { @@ -4272,8 +4326,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y
          */ addHandlerAsync(eventType: Office.EventType, handler: any, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; @@ -4293,11 +4348,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param settingName The case-sensitive name of the setting to retrieve. @@ -4353,11 +4408,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Excel Y Y
          PowerPoint Y Y
          Word Y Y
          * * @param callback Optional. A function that is invoked when the callback returns, whose only parameter is of type {@link Office.AsyncResult}. @@ -4386,11 +4441,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param settingName The case-sensitive name of the setting to remove. @@ -4422,10 +4477,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y
          * * @param eventType Specifies the type of event to remove. Required. @@ -4479,11 +4533,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param options Provides options for saving settings. @@ -4515,11 +4569,11 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * - * + * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          PowerPoint Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          PowerPoint Y Y Y Y
          Word Y Y Y Y
          * * @param settingName The case-sensitive name of the setting to set or create. @@ -4558,9 +4612,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          Word Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y
          Word Y Y
          */ interface SettingsChangedEventArgs { @@ -4591,7 +4645,7 @@ declare namespace Office { * * *Supported hosts, by platform* * - * + * * * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Office for Windows desktop Office Online (in browser) Office for iPad
          PowerPoint Y Y Y
          Word Y Y Y
          @@ -4643,10 +4697,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ columnCount: number; @@ -4665,10 +4719,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ hasHeaders: boolean; @@ -4700,10 +4754,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          */ rowCount: number; @@ -4733,15 +4787,16 @@ declare namespace Office { * * A capital Y in the following matrix indicates that this method is supported in the corresponding Office host application. * An empty cell indicates that the Office host application doesn't support this method. - * + * * For more information about Office host application and server requirements, see * {@link https://docs.microsoft.com/office/dev/add-ins/concepts/requirements-for-running-office-add-ins | Requirements for running Office Add-ins}. * * *Supported hosts, by platform* * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param tableData An array of arrays ("matrix") or a TableData object that contains one or more columns of data to add to the table. Required. @@ -4778,10 +4833,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param rows An array of arrays ("matrix") or a TableData object that contains one or more rows of data to add to the table. Required. @@ -4806,10 +4861,10 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * - * + * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Access Y
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Access Y
          Excel Y Y Y Y
          Word Y Y Y Y
          * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -4832,8 +4887,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          * * @param options Provides an option for preserving context data of any type, unchanged, for use in a callback. @@ -4859,32 +4914,33 @@ declare namespace Office { * Description * * - * {row: n} + * `{row: n}` * Specifies the range that is the zero-based nth row of data in the table. * * - * {column: n} + * `{column: n}` * Specifies the range that is the zero-based nth column of data in the table. * * - * {row: i, column: j} + * `{row: i, column: j}` * Specifies the single cell that is the ith row and jth column of the table. * * - * Office.Table.All + * `Office.Table.All` * Specifies the entire table, including column headers, data, and totals (if any). * * - * Office.Table.Data + * `Office.Table.Data` * Specifies only the data in the table (no headers and totals). * * - * Office.Table.Headers + * `Office.Table.Headers` * Specifies only the header row. * * * - * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel (Right-click > Format Cells or Home > Format > Format Cells). + * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel + * (Right-click \> Format Cells or Home \> Format \> Format Cells). * * @param cellReference An object literal containing name-value pairs that specify the range of cells to get formatting from. * @param formats An array specifying the format properties to get. @@ -4916,33 +4972,33 @@ declare namespace Office { * Description * * - * {row: n} + * `{row: n}` * Specifies the range that is the zero-based nth row of data in the table. * * - * {column: n} + * `{column: n}` * Specifies the range that is the zero-based nth column of data in the table. * * - * {row: i, column: j} + * `{row: i, column: j}` * Specifies the single cell that is the ith row and jth column of the table. * * - * Office.Table.All + * `Office.Table.All` * Specifies the entire table, including column headers, data, and totals (if any). * * - * Office.Table.Data + * `Office.Table.Data` * Specifies only the data in the table (no headers and totals). * * - * Office.Table.Headers + * `Office.Table.Headers` * Specifies only the header row. * * * * The `format:` property specifies values that correspond to a subset of the settings available in the Format Cells dialog box in Excel - * (Right-click > Format Cells or Home > Format > Format Cells). + * (Right-click \> Format Cells or Home \> Format \> Format Cells). * * You specify the value of the `format:` property as a list of one or more property name - value pairs in a JavaScript object literal. The * property name specifies the name of the formatting property to set, and value specifies the property value. @@ -4997,8 +5053,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          * * @param cellFormat An array that contains one or more JavaScript objects that specify which cells to target and the formatting to apply to them. @@ -5049,8 +5105,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          * * @param tableOptions An object literal containing a list of property name-value pairs that define the table options to apply. @@ -5091,8 +5147,8 @@ declare namespace Office { */ headers: any[]; /** - * Gets or sets the rows in the table. Returns an array of arrays that contains the data in the table. Returns an empty array ``, if there are - * no rows. + * Gets or sets the rows in the table. Returns an array of arrays that contains the data in the table. + * Returns an empty array if there are no rows. * * @remarks * @@ -5127,8 +5183,8 @@ declare namespace Office { * * *Supported hosts, by platform* *
          HostsExcel, Word
          - * - * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          */ enum Table { @@ -5164,9 +5220,9 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * - * + * + * + * *
          Office for Windows desktop Office Online (in browser) Office for iPad
          Excel Y Y Y
          Word Y Y Y
          Office for Windows desktop Office Online (in browser) Office for iPad Office for Mac
          Excel Y Y Y Y
          Word Y Y Y Y
          */ interface TextBinding extends Binding { } @@ -5187,8 +5243,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ enum ProjectProjectFields { @@ -5263,8 +5319,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ enum ProjectResourceFields { @@ -6090,8 +6146,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ enum ProjectTaskFields { @@ -7252,8 +7308,8 @@ declare namespace Office { * * *Supported hosts, by platform* * - * - * + * + * *
          Office for Windows desktop Office Online (in browser)
          Project Y
          Office for Windows desktop Office Online (in browser)
          Project Y
          */ enum ProjectViewTypes { @@ -7339,6 +7395,62 @@ declare namespace Office { declare namespace Office { namespace MailboxEnums { + /** + * Specifies the formatting that applies to an attachment's content. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
          + * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} + * Compose or read
          + * + * @beta + */ + enum AttachmentContentFormat { + /** + * The content of the attachment is returned as a base64-encoded string. + */ + Base64 = "base64", + + /** + * The content of the attachment is returned as a string representing a URL. + */ + Url = "url", + + /** + * The content of the attachment is returned as a string representing an .eml formatted file. + */ + Eml = "eml", + + /** + * The content of the attachment is returned as a string representing an .icalendar formatted file. + */ + ICalendar = "iCalendar" + } + /** + * Specifies whether an attachment was added to or removed from an item. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
          + * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode} + * Compose or read
          + * + * @beta + */ + enum AttachmentStatus { + /** + * An attachment was added to the item. + */ + Added = "added", + + /** + * An attachment was removed from the item. + */ + Removed = "removed" + } /** * Specifies an attachment's type. * @@ -8493,6 +8605,36 @@ declare namespace Office { */ subject: string; } + /** + * Represents the content of an attachment on a message or appointment item. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          + * + * @beta + */ + interface AttachmentContent { + /** + * The content of an attachment as a string. + */ + content: string; + /** + * The string format to use for an attachment's content. + * + * For file attachments, the formatting is a base64-encoded string. + * + * For item attachments that represent messages, the formatting is a string representing an .eml formatted file. + * + * For item attachments that represent calendar items, the formatting is a string representing an .icalendar file. + * + * For cloud attachments, the formatting is a URL string. + */ + format: Office.MailboxEnums.AttachmentContentFormat; + } /** * Represents an attachment on an item from the server. Read mode only. * @@ -8561,7 +8703,7 @@ declare namespace Office { * * In addition to this signature, this method also has the following signature: * - * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` + * `getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void;` * * @param coercionType The format for the returned body. * @param options Optional. An object literal that contains one or more of the following properties: @@ -8569,7 +8711,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Returns the current body in a specified format. * @@ -8590,7 +8732,7 @@ declare namespace Office { * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. * The body is provided in the requested format in the asyncResult.value property. */ - getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; + getAsync(coerciontype: Office.CoercionType, callback: (result: AsyncResult) => void): void; /** * Gets a value that indicates whether the content is in HTML or text format. @@ -8614,7 +8756,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8648,7 +8790,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8672,7 +8814,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8693,7 +8835,7 @@ declare namespace Office { * The prependAsync method inserts the specified string at the beginning of the item body. * After insertion, the cursor is returned to its original place, relative to the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8713,7 +8855,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8748,7 +8890,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8773,7 +8915,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8797,7 +8939,7 @@ declare namespace Office { * The value returned from the getAsync method will not necessarily be exactly the same as the value that was passed in the setAsync method * previously. The client may modify the value passed to setAsync in order to make it render efficiently with its rendering engine. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.3] @@ -8820,7 +8962,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8855,7 +8997,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8880,7 +9022,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8904,7 +9046,7 @@ declare namespace Office { * the editor, it replaces the selected text. If the cursor was never in the body of the item, or if the body of the item lost focus in the * UI, the string will be inserted at the top of the body content. After insertion, the cursor is placed at the end of the inserted content. * - * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor () to "LPNoLP" + * When including links in HTML markup, you can disable online link preview by setting the id attribute on the anchor (\) to "LPNoLP" * (please see the Examples section for a sample). * * [Api set: Mailbox 1.1] @@ -8937,7 +9079,7 @@ declare namespace Office { /** * An array of strings containing the mailing and street addresses associated with the contact. Nullable. */ - addresses: Array; + addresses: string[]; /** * A string containing the name of the business associated with the contact. Nullable. */ @@ -8945,7 +9087,7 @@ declare namespace Office { /** * An array of strings containing the SMTP email addresses associated with the contact. Nullable, */ - emailAddresses: Array; + emailAddresses: string[]; /** * A string containing the name of the person associated with the contact. Nullable. */ @@ -8953,11 +9095,11 @@ declare namespace Office { /** * An array containing a PhoneNumber object for each phone number associated with the contact. Nullable. */ - phoneNumbers: Array; + phoneNumbers: PhoneNumber[]; /** * An array of strings containing the Internet URLs associated with the contact. Nullable. */ - urls: Array; + urls: string[]; } /** * The CustomProperties object represents custom properties that are specific to a particular item and specific to a mail add-in for Outlook. @@ -9278,6 +9420,154 @@ declare namespace Office { getAsync(callback?: (result: AsyncResult) => void): void; } + /** + * The InternetHeaders object represents properties that are preserved after the item leaves Exchange and 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. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          + * + * @beta + */ + export interface InternetHeaders { + /** + * Given an array of internet header names, this method returns a dictionary containing those internet headers and their values. + * If the add-in requests an x-header that is not available, that x-header will not be returned in the results. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          + * + * In addition to this signature, this method also has the following signature: + * + * `getAsync(names: string[], callback: (result: AsyncResult) => void): void;` + * + * @param names The names of the internet headers to be returned. + * @param options Optional. An object literal that contains one or more of the following properties: + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + getAsync(names: string[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method returns a dictionary containing those internet headers and their values. + * If the add-in requests an x-header that is not available, that x-header will not be returned in the results. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          + * + * @param names The names of the internet headers to be returned. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + getAsync(names: string[], callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method removes the specified headers from the internet header collection. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * In addition to this signature, this method also has the following signature: + * + * `removeAsync(names: string[], callback: (result: AsyncResult) => void): void;` + * + * @param names The names of the internet headers to be removed. + * @param options Optional. An object literal that contains one or more of the following properties: + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + removeAsync(names: string[], options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Given an array of internet header names, this method removes the specified headers from the internet header collection. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * @param names The names of the internet headers to be removed. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. + * + * @beta + */ + removeAsync(names: string[], callback?: (result: AsyncResult) => void): void; + /** + * Sets the specified internet headers to the specified values. + * + * The setAsync method creates a new header if the specified header does not already exist; otherwise, the existing value is replaced with + * the new value. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * In addition to this signature, this method also has the following signatures: + * + * `setAsync(headers: string, callback: (result: AsyncResult) => void): void;` + * + * @param headers The names and corresponding values of the headers to be set. Should be a dictionary object with keys being the names of the + * internet headers and values being the values of the internet headers. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. + * Any errors encountered will be provided in the asyncResult.error property. + * + * @beta + */ + setAsync(headers: Object, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + /** + * Sets the specified internet headers to the specified values. + * + * The setAsync method creates a new header if the specified header does not already exist; otherwise, the existing value is replaced with + * the new value. + * + * [Api set: Mailbox Preview] + * + * @remarks + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * + * + * @param headers The names and corresponding values of the headers to be set. Should be a dictionary object with keys being the names of the + * internet headers and values being the values of the internet headers. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. + * Any errors encountered will be provided in the asyncResult.error property. + * + * @beta + */ + setAsync(headers: Object, callback?: (result: AsyncResult) => void): void; + } + /** * Represents the appointment organizer, even if an alias or a delegate was used to create the appointment. * This object provides a method to get the organizer value of an appointment in an Outlook add-in. @@ -9668,7 +9958,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -9695,7 +9986,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -9854,6 +10145,26 @@ declare namespace Office { *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadWriteItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer
          */ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -9962,8 +10273,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -9996,8 +10307,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10018,8 +10329,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10043,8 +10354,8 @@ declare namespace Office { * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. * In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -10066,7 +10377,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10080,7 +10391,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -10092,7 +10403,8 @@ declare namespace Office { /** * Removes an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10102,7 +10414,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Organizer * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -10146,13 +10458,13 @@ declare namespace Office { * * `saveAsync(options: Office.AsyncContextOptions): void;` * - * `saveAsync(callback: (result: AsyncResult) => void): void;` + * `saveAsync(callback: (result: AsyncResult) => void): void;` * * @param options Optional. An object literal that contains one or more of the following properties. * asyncContext: Developers can provide any object they wish to access in the callback method. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; + saveAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Asynchronously saves an item. * @@ -10253,7 +10565,7 @@ declare namespace Office { * * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of type Office.AsyncResult. */ - saveAsync(callback: (result: AsyncResult) => void): void; + saveAsync(callback: (result: AsyncResult) => void): void; /** * Asynchronously inserts data into the body or subject of a message. * @@ -10377,7 +10689,7 @@ declare namespace Office { */ interface AppointmentRead extends Appointment, ItemRead { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -10681,7 +10993,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -10709,7 +11021,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11062,7 +11374,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11076,7 +11388,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -11089,7 +11401,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11099,7 +11411,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Appointment Attendee * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -11236,7 +11548,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11263,7 +11576,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11280,6 +11594,36 @@ declare namespace Office { * asyncResult, which is an Office.AsyncResult object. */ addHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void; + + /** + * Gets an attachment from a message or appointment and returns it as an `Office.AttachmentContent` object. + * + * The `getAttachmentContentAsync` method gets the attachment with the specified identifier from the item. As a best practice, you should use + * the identifier to retrieve an attachment in the same session that the attachmentIds were retrieved with the `getAttachmentsAsync` or + * `item.attachments` call. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          ErrorsInvalidAttachmentId - The attachment identifier does not exist.
          + * + * @param attachmentId The identifier of the attachment you want to get. The maximum length of the string is 100 characters. + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, + * asyncResult, which is an Office.AsyncResult object. If the call fails, the asyncResult.error property will contain and error code + * with the reason for the failure. + * + * @beta + */ + getAttachmentContentAsync(attachmentId: string, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is {@link https://docs.microsoft.com/outlook/actionable-messages/invoke-add-in-from-actionable-message | activated by an actionable message}. @@ -11383,7 +11727,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11397,7 +11741,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType: Office.EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -11411,7 +11755,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -11421,7 +11765,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -11731,6 +12075,26 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose */ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -11817,8 +12181,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11852,8 +12216,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11874,8 +12238,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -11898,8 +12262,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -12191,7 +12555,7 @@ declare namespace Office { */ interface ItemRead extends Item { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -12739,6 +13103,22 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ from: Office.From; + /** + * Sets the internet headers of a message. + * + * The internetHeaders property returns an InternetHeaders object that provides methods to manage the internet headers on the message. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose
          + * + * @beta + */ + internetHeaders: Office.InternetHeaders; /** * Gets the type of item that an instance represents. * @@ -12977,7 +13357,8 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and `Office.EventType.RecurrenceChanged`. + * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13004,7 +13385,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13165,6 +13546,26 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose */ close(): void; + /** + * Gets the item's attachments as an array. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose
          + * + * @param options Optional. An object literal that contains one or more of the following properties. + * asyncContext: Developers can provide any object they wish to access in the callback method. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. If the call fails, the asyncResult.error property will contain and error code with the reason for + * the failure. + * + * @beta + */ + getAttachmentsAsync(options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; /** * Gets initialization data passed when the add-in is activated by an actionable message. * @@ -13277,8 +13678,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13312,8 +13713,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13334,8 +13735,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13358,8 +13759,8 @@ declare namespace Office { * The removeAttachmentAsync method removes the attachment with the specified identifier from the item. * As a best practice, you should use the attachment identifier to remove an attachment only if the same mail app has added that attachment * in the same session. In Outlook Web App and OWA for Devices, the attachment identifier is valid only within the same session. - * A session is over when the user closes the app, or if the user starts composing in an inline form and subsequently pops out the inline form - * to continue in a separate window. + * A session is over when the user closes the app, or if the user starts composing an inline form then subsequently pops out the form to + * continue in a separate window. * * [Api set: Mailbox 1.1] * @@ -13381,7 +13782,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13395,7 +13796,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -13408,7 +13809,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -13418,7 +13819,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Compose * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -13693,7 +14094,7 @@ declare namespace Office { */ interface MessageRead extends Message, ItemRead { /** - * Gets an array of attachments for the item. + * Gets the item's attachments as an array. * * [Api set: Mailbox 1.0] * @@ -13801,6 +14202,22 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read */ from: EmailAddressDetails; + /** + * Gets the internet headers of a message. + * + * The internetHeaders property returns an InternetHeaders object that provides methods to manage the internet headers on the message. + * + * [Api set: Mailbox Preview] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read
          + * + * @beta + */ + internetHeaders: Office.InternetHeaders; /** * Gets the Internet message identifier for an email message. * @@ -14013,7 +14430,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14041,7 +14458,7 @@ declare namespace Office { * Adds an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14398,7 +14815,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14412,7 +14829,7 @@ declare namespace Office { * * `removeHandlerAsync(eventType:EventType, handler: any, callback?: (result: AsyncResult) => void): void;` * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param options Optional. An object literal that contains one or more of the following properties. @@ -14425,7 +14842,7 @@ declare namespace Office { * Removes an event handler for a supported event. * * Currently the supported event types are `Office.EventType.AppointmentTimeChanged`, `Office.EventType.RecipientsChanged`, and - * `Office.EventType.RecurrenceChanged`. + * `Office.EventType.RecurrenceChanged`. In Preview, `Office.EventType.AttachmentsChanged` is also supported. * * [Api set: Mailbox 1.7] * @@ -14435,7 +14852,7 @@ declare namespace Office { * * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Message Read * - * @param eventType The event that should invoke the handler. + * @param eventType The event that should revoke the handler. * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. * The type property on the parameter will match the eventType parameter passed to removeHandlerAsync. * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter, @@ -14724,7 +15141,7 @@ declare namespace Office { */ restUrl: string; /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * More information is under {@link Office.UserProfile} */ @@ -14732,7 +15149,7 @@ declare namespace Office { /** * Adds an event handler for a supported event. * - * Currently, the supported event types are `Office.EventType.ItemChanged` and `Office.EventType.OfficeThemeChanged`. + * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. * * [Api set: Mailbox 1.5] * @@ -15005,7 +15422,8 @@ declare namespace Office { * isRest: Determines if the token provided will be used for the Outlook REST APIs or Exchange Web Services. Default value is false. * asyncContext: Any state data that is passed to the asynchronous method. * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of - * type Office.AsyncResult. The token is provided as a string in the asyncResult.value property. + * type Office.AsyncResult. The token is provided as a string in the `asyncResult.value` property. + * If there was an error, then the `asyncResult.error` and `asyncResult.diagnostics` properties may provide additional information. */ getCallbackTokenAsync(options: Office.AsyncContextOptions & { isRest?: boolean }, callback: (result: AsyncResult) => void): void; /** @@ -15032,7 +15450,8 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose and read * * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of type AsyncResult. - * The token is provided as a string in the asyncResult.value property. + * The token is provided as a string in the `asyncResult.value` property. + * If there was an error, then the `asyncResult.error` and `asyncResult.diagnostics` properties may provide additional information. */ getCallbackTokenAsync(callback: (result: AsyncResult) => void): void; /** @@ -15059,7 +15478,8 @@ declare namespace Office { * {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose and read * * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of - * type Office.AsyncResult. The token is provided as a string in the asyncResult.value property. + * type Office.AsyncResult. The token is provided as a string in the `asyncResult.value` property. + * If there was an error, then the `asyncResult.error` and `asyncResult.diagnostics` properties may provide additional information. * @param userContext Optional. Any state data that is passed to the asynchronous method. */ getCallbackTokenAsync(callback: (result: AsyncResult) => void, userContext?: any): void; @@ -15081,7 +15501,8 @@ declare namespace Office { * * @param callback When the method completes, the function passed in the callback parameter is called with a single parameter of * type Office.AsyncResult. - * The token is provided as a string in the asyncResult.value property. + * The token is provided as a string in the `asyncResult.value` property. + * If there was an error, then the `asyncResult.error` and `asyncResult.diagnostics` properties may provide additional information. * @param userContext Optional. Any state data that is passed to the asynchronous method.| */ getUserIdentityTokenAsync(callback: (result: AsyncResult) => void, userContext?: any): void; @@ -15094,7 +15515,7 @@ declare namespace Office { * * You cannot request Folder Associated Items with the makeEwsRequestAsync method. * - * The XML request must specify UTF-8 encoding. + * The XML request must specify UTF-8 encoding. \ * * Your add-in must have the ReadWriteMailbox permission to use the makeEwsRequestAsync method. * For information about using the ReadWriteMailbox permission and the EWS operations that you can call with the makeEwsRequestAsync method, @@ -15138,6 +15559,27 @@ declare namespace Office { * @param userContext Optional. Any state data that is passed to the asynchronous method. */ makeEwsRequestAsync(data: any, callback: (result: AsyncResult) => void, userContext?: any): void; + /** + * Removes an event handler for a supported event. + * + * Currently, the only supported event type is `Office.EventType.ItemChanged`. In Preview, `Office.EventType.OfficeThemeChanged` is also supported. + * + * [Api set: Mailbox 1.5] + * + * @remarks + * + * + * + *
          {@link https://docs.microsoft.com/outlook/add-ins/understanding-outlook-add-in-permissions | Minimum permission level}ReadItem
          {@link https://docs.microsoft.com/outlook/add-ins/#extension-points | Applicable Outlook mode}Compose or read
          + * + * @param eventType The event that should revoke the handler. + * @param handler The function to handle the event. The function must accept a single parameter, which is an object literal. + * The type property on the parameter will match the eventType parameter passed to addHandlerAsync. + * @param options Optional. Provides an option for preserving context data of any type, unchanged, for use in a callback. + * @param callback Optional. When the method completes, the function passed in the callback parameter is called with a single parameter of + * type Office.AsyncResult. + */ + removeHandlerAsync(eventType: Office.EventType, handler: (type: EventType) => void, options?: Office.AsyncContextOptions, callback?: (result: AsyncResult) => void): void; } /** @@ -16204,7 +16646,7 @@ declare namespace Office { * The set method creates a new setting of the specified name if it does not already exist, or sets an existing setting of the specified name. * The value is stored in the document as the serialized JSON representation of its data type. * - * A maximum of 2MB is available for the settings of each add-in, and each individual setting is limited to 32KB. + * A maximum of 32KB is available for the settings of each add-in. * * Any changes made to settings using the set function will not be saved to the server until the saveAsync function is called. * @@ -16443,7 +16885,7 @@ declare namespace Office { */ owner: String; /** - * The remote REST url related to the owner’s mailbox. + * The remote REST URL related to the owner’s mailbox. */ restUrl: String; /** @@ -16767,7 +17209,7 @@ declare namespace Office { } /** - * Information about the user associated with the mailbox. This includes their account type, display name, email adddress, and time zone. + * Information about the user associated with the mailbox. This includes their account type, display name, email address, and time zone. * * [Api set: Mailbox 1.0] * @@ -17103,7 +17545,7 @@ declare namespace OfficeExtension { * If there was an error, this contains all trace messages that were executed before the error occurred. * These messages can help you monitor the program execution sequence and detect the case of the error. */ - traceMessages: Array; + traceMessages: string[]; /** Debug info (useful for detailed logging of the error, i.e., via `JSON.stringify(...)`). */ debugInfo: DebugInfo; /** Inner error, if applicable. */ @@ -19890,7 +20332,7 @@ declare namespace Excel { * @param key The Key of the new setting. * @param value The Value for the new setting. */ - add(key: string, value: string | number | boolean | Date | Array | any): Excel.Setting; + add(key: string, value: string | number | boolean | Date | any[] | any): Excel.Setting; /** * * Gets the number of Settings in the collection. @@ -21323,18 +21765,19 @@ declare namespace Excel { interface BasicDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * For example, setting formula1 to 10 and operator to GreaterThan means that valid data for the range must be greater than 10. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | number | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a number, a range object, or a string formula (where the string is either a stringified number, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ @@ -21356,18 +21799,18 @@ declare namespace Excel { interface DateTimeDataValidation { /** * - * Gets or sets the Formula1, i.e. minimum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * Specifies the right-hand operand when the operator property is set to a binary operator such as GreaterThan (the left-hand operand is the value the user tries to enter in the cell). With the ternary operators Between and NotBetween, specifies the lower bound operand. + * When setting the value, it can be passed in as a Date, a Range object, or a string formula (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ formula1: string | Date | Range; /** * - * Gets or sets the Formula2, i.e. maximum value or value depending of the operator. - When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). - When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. + * With the ternary operators Between and NotBetween, specifies the upper bound operand. Is not used with the binary operators, such as GreaterThan. + * When setting the value, it can be passed in as a Date, a Range object, or a string (where the string is either a stringified date/time in ISO8601 format, a cell reference like "=A1", or a formula like "=MIN(A1, B1)"). + * When retrieving the value, it will always be returned as a string formula, for example: "=10", "=A1", "=SUM(A1:B5)", etc. * * [Api set: ExcelApi 1.8] */ @@ -21396,12 +21839,11 @@ declare namespace Excel { inCellDropDown: boolean; /** * - * Source of the list for data validation - When setting the value, it can be passed in as a Excel Range object, or a string that contains comma separated number, boolean or date. + * The source of the list for data validation. The value is a string, which can either be a range reference (e.g. `"=Names!$A$1:$A$3"`) or a comma-separated list of the values themselves. * * [Api set: ExcelApi 1.8] */ - source: string | Range; + source: string; } /** * @@ -22167,8 +22609,7 @@ declare namespace Excel { readonly worksheet: Excel.Worksheet; /** * - * Returns or sets a ChartCategoryLabelLevel enumeration constant referring to - the level of where the category labels are being sourced from. Read/Write. + * Returns or sets a ChartCategoryLabelLevel enumeration constant referring to the level of where the category labels are being sourced from. Read/Write. * * [Api set: ExcelApi 1.8] */ @@ -22231,8 +22672,7 @@ declare namespace Excel { plotVisibleOnly: boolean; /** * - * Returns or sets a ChartSeriesNameLevel enumeration constant referring to - the level of where the series names are being sourced from. Read/Write. + * Returns or sets a ChartSeriesNameLevel enumeration constant referring to the level of where the series names are being sourced from. Read/Write. * * [Api set: ExcelApi 1.8] */ @@ -23316,7 +23756,7 @@ declare namespace Excel { position: Excel.ChartAxisPosition | "Automatic" | "Maximum" | "Minimum" | "Custom"; /** * - * Represents the specified axis position where the other axis crosses at. Read Only. Set to this property should use SetPositionAt(double) method. + * Represents the specified axis position where the other axis crosses at. You should use the SetPositionAt(double) method to set this property. * * [Api set: ExcelApi 1.8] */ @@ -23682,15 +24122,14 @@ declare namespace Excel { readonly format: Excel.ChartDataLabelFormat; /** * - * Represents whether data labels automatically generates appropriate text based on context. + * Represents whether data labels automatically generate appropriate text based on context. * * [Api set: ExcelApi 1.8] */ autoText: boolean; /** * - * Represents the horizontal alignment for chart data label. See Excel.ChartTextHorizontalAlignment for details. - This property is valid only when TextOrientation of data label is 0. + * Represents the horizontal alignment for chart data label. See Excel.ChartTextHorizontalAlignment for details. This property is valid only when TextOrientation of data label is 0. * * [Api set: ExcelApi 1.8] */ @@ -23767,8 +24206,7 @@ declare namespace Excel { textOrientation: number; /** * - * Represents the vertical alignment of chart data label. See Excel.ChartTextVerticalAlignment for details. - This property is valid only when TextOrientation of data label is 90, -90 or 180. + * Represents the vertical alignment of chart data label. See Excel.ChartTextVerticalAlignment for details. This property is valid only when TextOrientation of data label is -90, 90, or 180. * * [Api set: ExcelApi 1.8] */ @@ -50399,7 +50837,7 @@ declare namespace Word { getRange(rangeLocation?: "Whole" | "Start" | "End" | "Before" | "After" | "Content"): Word.Range; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50409,7 +50847,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.2] * @@ -50426,7 +50864,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50436,7 +50874,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts a document at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a document at the specified location. * * [Api set: WordApi 1.2] * @@ -50446,7 +50884,7 @@ declare namespace Word { insertFileFromBase64(base64File: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50456,7 +50894,7 @@ declare namespace Word { insertHtml(html: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts HTML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts HTML at the specified location. * * [Api set: WordApi 1.2] * @@ -50486,7 +50924,7 @@ declare namespace Word { insertInlinePictureFromBase64(base64EncodedImage: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.InlinePicture; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50496,7 +50934,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts OOXML at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts OOXML at the specified location. * * [Api set: WordApi 1.2] * @@ -50506,7 +50944,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50516,7 +50954,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.2] * @@ -50526,7 +50964,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -50536,7 +50974,7 @@ declare namespace Word { insertText(text: string, insertLocation: Word.InsertLocation): Word.Range; /** * - * Inserts text at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts text at the specified location. * * [Api set: WordApi 1.2] * @@ -51347,7 +51785,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51357,7 +51795,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51454,7 +51892,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51464,7 +51902,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -51474,7 +51912,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -51486,7 +51924,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -51925,7 +52363,7 @@ declare namespace Word { getTextRanges(endingMarks: string[], trimSpacing?: boolean): Word.RangeCollection; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -51935,7 +52373,7 @@ declare namespace Word { insertBreak(breakType: Word.BreakType, insertLocation: Word.InsertLocation): void; /** * - * Inserts a break at the specified location in the main document. The insertLocation value can be 'Before' or 'After'. + * Inserts a break at the specified location in the main document. * * [Api set: WordApi 1.1] * @@ -52032,7 +52470,7 @@ declare namespace Word { insertOoxml(ooxml: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Range; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52042,7 +52480,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.1] * @@ -52052,7 +52490,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52064,7 +52502,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52927,7 +53365,7 @@ declare namespace Word { insertContentControl(): Word.ContentControl; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -52937,7 +53375,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: Word.InsertLocation): Word.Paragraph; /** * - * Inserts a paragraph at the specified location. The insertLocation value can be 'Before' or 'After'. + * Inserts a paragraph at the specified location. * * [Api set: WordApi 1.3] * @@ -52947,7 +53385,7 @@ declare namespace Word { insertParagraph(paragraphText: string, insertLocation: "Before" | "After" | "Start" | "End" | "Replace"): Word.Paragraph; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * @@ -52959,7 +53397,7 @@ declare namespace Word { insertTable(rowCount: number, columnCount: number, insertLocation: Word.InsertLocation, values?: string[][]): Word.Table; /** * - * Inserts a table with the specified number of rows and columns. The insertLocation value can be 'Before' or 'After'. + * Inserts a table with the specified number of rows and columns. * * [Api set: WordApi 1.3] * diff --git a/types/office-runtime/index.d.ts b/types/office-runtime/index.d.ts index 8b22ce17c2..31c3dded97 100644 --- a/types/office-runtime/index.d.ts +++ b/types/office-runtime/index.d.ts @@ -1,5 +1,5 @@ // Type definitions for office-runtime 1.0 -// Project: http://dev.office.com/ +// Project: https://github.com/OfficeDev/office-js // Definitions by: Michael Zlatskovsky , Michelle Scharlock // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // Typescript Version: 2.4 @@ -49,11 +49,6 @@ declare namespace OfficeRuntime { * Removes an item for specified key and invokes a callback when finished. Returns a Promise. */ removeItem(key: string, callback?: (error?: Error) => void): Promise; - /** - * @beta - * Erases all AsyncStorage. Returns a Promise. - */ - clear(callback?: (error?: Error) => void): Promise; /** * @beta * Returns a Promise with all keys. diff --git a/types/office-runtime/office-runtime-tests.ts b/types/office-runtime/office-runtime-tests.ts index dbccca7370..b0e0457bae 100644 --- a/types/office-runtime/office-runtime-tests.ts +++ b/types/office-runtime/office-runtime-tests.ts @@ -18,11 +18,6 @@ OfficeRuntime.AsyncStorage.removeItem("foo", () => { // perform an action }); -OfficeRuntime.AsyncStorage.clear(); -OfficeRuntime.AsyncStorage.clear(() => { - // perform an action -}); - OfficeRuntime.AsyncStorage.getAllKeys().then(keys => { keys.forEach(item => console.log(item)); }); diff --git a/types/okta__okta-vue/tsconfig.json b/types/okta__okta-vue/tsconfig.json index f114dc0fe8..ffd7c33703 100644 --- a/types/okta__okta-vue/tsconfig.json +++ b/types/okta__okta-vue/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/ol/ol-tests.ts b/types/ol/ol-tests.ts index fbfed7e90f..be19e61a2b 100644 --- a/types/ol/ol-tests.ts +++ b/types/ol/ol-tests.ts @@ -303,11 +303,11 @@ import VectorTile from 'ol/vectortile'; import View from 'ol/view'; // Map -const map: ol.Map = new Map( {}); -const mapView: View = {}; -const layerBase: LayerBase = {}; -const control: ControlControl = {}; -const interaction: InteractionInteraction = {}; +const map: ol.Map = new Map({} as any); +declare const mapView: View; +declare const layerBase: LayerBase; +declare const control: ControlControl; +declare const interaction: InteractionInteraction; map.setView(mapView); map.addLayer(layerBase); map.addControl(control); @@ -315,11 +315,11 @@ map.addInteraction(interaction); // View let view: View; -const coordinate: ol.Coordinate = {}; -const size: ol.Size = {}; -const position: ol.Pixel = {}; +declare const coordinate: ol.Coordinate; +declare const size: ol.Size; +declare const position: ol.Pixel; view = map.getView(); view.getProjection(); -view.animate( {}); -view.calculateExtent( 'size'); +view.animate({} as any); +view.calculateExtent('size' as any); view.centerOn(coordinate, size, position); diff --git a/types/on-wake-up/index.d.ts b/types/on-wake-up/index.d.ts new file mode 100644 index 0000000000..c9568404b8 --- /dev/null +++ b/types/on-wake-up/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for on-wake-up 1.0 +// Project: https://github.com/mafintosh/on-wake-up +// Definitions by: Klaus Meinhardt +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/** + * Register a callback when the device presumably wakes up from sleep. + * @param cb The callback to execute + * @returns Function to unregister the callback + */ +declare function onWakeUp(cb: () => void): () => void; + +export = onWakeUp; diff --git a/types/on-wake-up/on-wake-up-tests.ts b/types/on-wake-up/on-wake-up-tests.ts new file mode 100644 index 0000000000..985d415063 --- /dev/null +++ b/types/on-wake-up/on-wake-up-tests.ts @@ -0,0 +1,4 @@ +import onWakeUp = require('on-wake-up'); + +const unregister = onWakeUp(() => void 0); +unregister(); diff --git a/types/on-wake-up/tsconfig.json b/types/on-wake-up/tsconfig.json new file mode 100644 index 0000000000..691fba15c1 --- /dev/null +++ b/types/on-wake-up/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", + "on-wake-up-tests.ts" + ] +} diff --git a/types/on-wake-up/tslint.json b/types/on-wake-up/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/on-wake-up/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/onoff/index.d.ts b/types/onoff/index.d.ts index 72c25d11f5..f4eba3ffb6 100644 --- a/types/onoff/index.d.ts +++ b/types/onoff/index.d.ts @@ -1,6 +1,7 @@ -// Type definitions for onoff +// Type definitions for onoff v3.2 // Project: https://github.com/fivdi/onoff // Definitions by: Marcel Ernst +// Kallu609 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -8,47 +9,56 @@ export = __ONOFF; declare namespace __ONOFF { - - var version:string; - + var version: string; + interface GpioOptions { - debounceTimeout?:number; - activeLow?:boolean; + debounceTimeout?: number; + activeLow?: boolean; } - + + type Direction = 'in' | 'out' | 'high' | 'low'; + type Edge = 'none' | 'falling' | 'rising' | 'both'; + class Gpio { - constructor(gpio:number, direction:string); - constructor(gpio:number, direction:string, edge:string); - constructor(gpio:number, direction:string, edge:string, options:GpioOptions); - constructor(gpio:number, direction:string, options:GpioOptions); + constructor(gpio: number, direction: Direction, options?: GpioOptions); + constructor( + gpio: number, + direction: Direction, + edge?: Edge, + options?: GpioOptions + ); + + static accessible: boolean; - gpio:number - gpioPath:string; - opts:GpioOptions; - readBuffer:Buffer; - listeners:Array<(error:Error, value:number) => void>; - valueFd:number; - - read(cb:(err:Error, value:number) => void):void; - readSync():number; - - write(value:number, cb:(err:Error, value:number) => void):void; - writeSync(value:number):void; - - watch(cb:(error:Error, value:number) => void):void; - unwatch():void; - unwatch(cb:(error:Error, value:number) => void):void; - unwatchAll():void; - - direction():string; - setDirection(value:string):void; - - edge():string; - setEdge(value:string):void; - - options():GpioOptions; - - unexport():void; + gpio: number; + gpioPath: string; + opts: GpioOptions; + readBuffer: Buffer; + listeners: Array<(err: Error, value: number) => void>; + _valueFd: number; + + read(cb: (err: Error, value: number) => void): void; + readSync(): number; + + write(value: number, cb: (err: Error, value: number) => void): void; + writeSync(value: number): void; + + watch(cb: (err: Error, value: number) => void): void; + unwatch(): void; + unwatch(cb: (err: Error, value: number) => void): void; + unwatchAll(): void; + + direction(): Direction; + setDirection(value: Direction): void; + + edge(): Edge; + setEdge(value: Edge): void; + + activeLow(): boolean; + setActiveLow(invert?: boolean): void; + + options(): GpioOptions; + + unexport(): void; } - } diff --git a/types/onoff/onoff-tests.ts b/types/onoff/onoff-tests.ts index 21b47e7f99..776b577348 100644 --- a/types/onoff/onoff-tests.ts +++ b/types/onoff/onoff-tests.ts @@ -14,3 +14,5 @@ setTimeout(function() { led.writeSync(0); led.unexport(); }, 2000); + +var accessible:boolean = onoff.Gpio.accessible; 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/_v2/api/application/application.d.ts b/types/openfin/_v2/api/application/application.d.ts index 616501834d..37263a9a63 100644 --- a/types/openfin/_v2/api/application/application.d.ts +++ b/types/openfin/_v2/api/application/application.d.ts @@ -1,10 +1,12 @@ -import { EmitterBase, Base, Reply, RuntimeEvent } from '../base'; +import { EmitterBase, Base, Reply } from '../base'; import { Identity } from '../../identity'; import { _Window } from '../window/window'; import { Point } from '../system/point'; import { MonitorInfo } from '../system/monitor'; import Transport from '../../transport/transport'; import Bounds from '../window/bounds'; +import { ApplicationEvents } from '../events/application'; +import { ApplicationOption } from './applicationOption'; export interface TrayIconClickReply extends Point, Reply<'application', 'tray-icon-clicked'> { button: number; monitorInfo: MonitorInfo; @@ -21,7 +23,7 @@ export declare class NavigationRejectedReply extends Reply<'window-navigation-re sourceName: string; url: string; } -export interface ConfigInterface { +export interface ShortCutConfig { desktop?: boolean; startMenu?: boolean; systemStartup?: boolean; @@ -32,32 +34,54 @@ export interface TrayInfo { x: number; y: number; } +/** + * @lends Application + */ export default class ApplicationModule extends Base { /** - * Returns an Application object that represents an existing application. - * @param { Identity } indentity + * Asynchronously returns an Application object that represents an existing application. + * @param { Identity } identity * @return {Promise.} * @tutorial Application.wrap + * @static */ wrap(identity: Identity): Promise; + /** + * Synchronously returns an Application object that represents an existing application. + * @param { Identity } identity + * @return {Application} + * @tutorial Application.wrapSync + * @static + */ + wrapSync(identity: Identity): Application; /** * Creates a new Application. - * @param {*} appOptions + * @param { ApplicationOption } appOptions * @return {Promise.} * @tutorial Application.create + * @static */ - create(appOptions: any): Promise; + create(appOptions: ApplicationOption): Promise; /** - * Returns an Application object that represents the current application + * Asynchronously returns an Application object that represents the current application * @return {Promise.} * @tutorial Application.getCurrent + * @static */ getCurrent(): Promise; + /** + * Synchronously returns an Application object that represents the current application + * @return {Application} + * @tutorial Application.getCurrentSync + * @static + */ + getCurrentSync(): Application; /** * Retrieves application's manifest and returns a wrapped application. * @param {string} manifestUrl - The URL of app's manifest. * @return {Promise.} * @tutorial Application.createFromManifest + * @static */ createFromManifest(manifestUrl: string): Promise; } @@ -66,12 +90,11 @@ export default class ApplicationModule extends Base { * execute, show/close an application as well as listen to application events. * @class */ -export declare class Application extends EmitterBase { +export declare class Application extends EmitterBase { identity: Identity; _manifestUrl?: string; private window; constructor(wire: Transport, identity: Identity); - protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; private windowListFromIdentityList; /** * Determines if the application is currently running. @@ -116,10 +139,16 @@ export declare class Application extends EmitterBase { getParentUuid(): Promise; /** * Retrieves current application's shortcut configuration. - * @return {Promise.} + * @return {Promise.} * @tutorial Application.getShortcuts */ - getShortcuts(): Promise; + getShortcuts(): Promise; + /** + * Returns the current zoom level of the application. + * @return {Promise.} + * @tutorial Application.getZoomLevel + */ + getZoomLevel(): Promise; /** * Returns an instance of the main Window of the application * @return {Promise.<_Window>} @@ -174,7 +203,15 @@ export declare class Application extends EmitterBase { * @return {Promise.} * @tutorial Application.setShortcuts */ - setShortcuts(config: ConfigInterface): Promise; + setShortcuts(config: ShortCutConfig): Promise; + /** + * Sets the zoom level of the application. The original size is 0 and each increment above or below represents zooming 20% + * larger or smaller to default limits of 300% and 50% of original size, respectively. + * @param { number } level The zoom level + * @return {Promise.} + * @tutorial Application.setZoomLevel + */ + setZoomLevel(level: number): Promise; /** * @summary Retrieves information about the system tray. * @desc The only information currently returned is the position and dimensions. @@ -203,21 +240,3 @@ export declare class Application extends EmitterBase { */ getInfo(): Promise; } -export interface Application { - on(type: 'closed', listener: (data: Reply<'application', 'closed'>) => void): Promise; - on(type: 'initialized', listener: (data: Reply<'application', 'initialized'>) => void): Promise; - on(type: 'connected', listener: (data: Reply<'application', 'connected'>) => void): Promise; - on(type: 'crashed', listener: (data: Reply<'application', 'crashed'>) => void): Promise; - on(type: 'error', listener: (data: Reply<'application', 'error'>) => void): Promise; - on(type: 'not-responding', listener: (data: Reply<'application', 'not-responding'>) => void): Promise; - on(type: 'out-of-memory', listener: (data: Reply<'application', 'out-of-memory'>) => void): Promise; - on(type: 'responding', listener: (data: Reply<'application', 'responding'>) => void): Promise; - on(type: 'started', listener: (data: Reply<'application', 'started'>) => void): Promise; - on(type: 'run-requested', listener: (data: Reply<'application', 'run-requested'>) => void): Promise; - on(type: 'window-navigation-rejected', listener: (data: NavigationRejectedReply) => void): Promise; - on(type: 'window-created', listener: (data: Reply<'application', 'window-created'>) => void): Promise; - on(type: 'window-closed', listener: (data: Reply<'application', 'window-closed'>) => void): Promise; - on(type: 'tray-icon-clicked', listener: (data: TrayIconClickReply) => void): Promise; - on(type: 'removeListener', listener: (eventType: string) => void): Promise; - on(type: 'newListener', listener: (eventType: string) => void): Promise; -} diff --git a/types/openfin/_v2/api/application/applicationOption.d.ts b/types/openfin/_v2/api/application/applicationOption.d.ts new file mode 100644 index 0000000000..134e4482d6 --- /dev/null +++ b/types/openfin/_v2/api/application/applicationOption.d.ts @@ -0,0 +1,50 @@ +import { WindowOption, CustomRequestHeaders } from '../window/windowOption'; +import { DownloadPreloadOption } from '../system/download-preload'; +export interface ApplicationOption { + disableIabSecureLogging?: boolean; + loadErrorMessage?: string; + mainWindowOptions?: WindowOption; + name?: string; + nonPersistent?: boolean; + plugins?: boolean; + spellCheck?: boolean; + url?: string; + uuid: string; + webSecurity?: boolean; + accelerator?: object; + alwaysOnTop?: boolean; + api?: object; + aspectRatio?: number; + autoShow?: boolean; + backgroundColor?: string; + contentNavigation?: object; + contextMenu?: boolean; + cornerRounding?: object; + customData?: string; + customRequestHeaders?: Array; + defaultCentered?: boolean; + defaultHeight?: number; + defaultLeft?: number; + defaultTop?: number; + defaultWidth?: number; + frame?: boolean; + hideOnClose?: boolean; + icon?: string; + maxHeight?: number; + maximizable?: boolean; + maxWidth?: number; + minHeight?: number; + minimizable?: boolean; + minWidth?: number; + opacity?: number; + preloadScripts?: Array; + resizable?: boolean; + resizeRegion?: object; + saveWindowState?: boolean; + shadow?: boolean; + showTaskbarIcon?: boolean; + smallWindow?: boolean; + state?: string; + taskbarIconGroup?: string; + waitForPageLoad?: boolean; +} diff --git a/types/openfin/_v2/api/base.d.ts b/types/openfin/_v2/api/base.d.ts index 1f17e1f24f..5cbb8658a7 100644 --- a/types/openfin/_v2/api/base.d.ts +++ b/types/openfin/_v2/api/base.d.ts @@ -1,10 +1,11 @@ /// -import Transport, { Message } from '../transport/transport'; +import Transport from '../transport/transport'; import { Identity } from '../identity'; import { EventEmitter } from 'events'; -export interface RuntimeEvent extends Identity { - topic: string; - type: string | symbol; +import { EmitterAccessor } from './events/emitterMap'; +import { BaseEventMap } from './events/base'; +interface SubOptions { + timestamp?: number; } export declare class Base { wire: Transport; @@ -14,26 +15,27 @@ export declare class Base { readonly me: Identity; protected isNodeEnvironment: () => boolean; protected isOpenFinEnvironment: () => boolean; - protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; } -export declare class EmitterBase extends Base { +export declare class EmitterBase extends Base { + private emitterAccessor; protected identity: Identity; - protected emitter: EventEmitter; - listeners: (event: string | symbol) => Function[]; + constructor(wire: Transport, emitterAccessor: EmitterAccessor); + eventNames: () => (string | symbol)[]; + emit: >(eventName: E, payload: E extends Extract ? EventTypes[E] : any, ...args: any[]) => boolean; + private hasEmitter; + private getEmitter; + listeners: (type: string | symbol) => Function[]; listenerCount: (type: string | symbol) => number; - constructor(wire: Transport); - emit: (eventName: string | symbol, ...args: any[]) => void; - protected onmessage: (message: Message) => boolean; - protected registerEventListener: (listener: RuntimeEvent) => Promise>; - protected deregisterEventListener: (listener: RuntimeEvent) => Promise>; - on(eventType: string, listener: (...args: any[]) => void): Promise; - addListener: (eventType: string, listener: (...args: any[]) => void) => Promise; - once(eventType: string, listener: (...args: any[]) => void): Promise; - prependListener(eventType: string, listener: (...args: any[]) => void): Promise; - prependOnceListener(eventType: string, listener: (...args: any[]) => void): Promise; - removeListener(eventType: string, listener: (...args: any[]) => void): Promise; - protected deregisterAllListeners: (eventType: string | symbol) => Promise>; - removeAllListeners(eventType?: string): Promise; + protected registerEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; + protected deregisterEventListener: (eventType: string | symbol | Extract, options?: SubOptions) => Promise; + on | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + addListener: >(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions) => Promise; + once | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + prependListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + prependOnceListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + removeListener | string | symbol>(eventType: E, listener: (payload: E extends keyof EventTypes ? EventTypes[E] : any, ...args: any[]) => void, options?: SubOptions): Promise; + protected deregisterAllListeners: (eventType: string | symbol | Extract) => Promise; + removeAllListeners(eventType?: Extract | string | symbol): Promise; } export declare class Reply implements Identity { topic: TOPIC; @@ -41,3 +43,4 @@ export declare class Reply imp uuid: string; name?: string; } +export {}; diff --git a/types/openfin/_v2/api/events/application.d.ts b/types/openfin/_v2/api/events/application.d.ts new file mode 100644 index 0000000000..444d358cbd --- /dev/null +++ b/types/openfin/_v2/api/events/application.d.ts @@ -0,0 +1,56 @@ +import { WindowEvent, BaseEventMap, ApplicationEvent } from './base'; +import { WindowAlertRequestedEvent, WindowAuthRequestedEvent, WindowEndLoadEvent, PropagatedWindowEvents } from './window'; +export interface CrashedEvent { + reason: 'normal-termination' | 'abnormal-termination' | 'killed' | 'crashed' | 'still-running' | 'launch-failed' | 'out-of-memory'; +} +export interface RunRequestedEvent extends ApplicationEvent { + userAppConfigArgs: any; +} +export interface TrayIconClicked extends ApplicationEvent { + button: 0 | 1 | 2; + x: number; + y: number; + monitorInfo: any; +} +export interface ApplicationEventMapping extends BaseEventMap { + 'closed': ApplicationEvent; + 'connected': ApplicationEvent; + 'crashed': CrashedEvent & ApplicationEvent; + 'initialized': ApplicationEvent; + 'manifest-changed': ApplicationEvent; + 'not-responding': ApplicationEvent; + 'responding': ApplicationEvent; + 'run-requested': RunRequestedEvent; + 'started': ApplicationEvent; + 'tray-icon-clicked': TrayIconClicked; + 'window-alert-requested': WindowAlertRequestedEvent; + 'window-auth-requested': WindowAuthRequestedEvent; + 'window-created': WindowEvent; + 'window-end-load': WindowEndLoadEvent; + 'window-not-responding': WindowEvent; + 'window-responding': WindowEvent; + 'window-show-requested': WindowEvent; + 'window-start-load': WindowEvent; +} +export interface PropagatedApplicationEventMapping { + 'application-closed': ApplicationEvent; + 'application-connected': ApplicationEvent; + 'application-crashed': CrashedEvent & ApplicationEvent; + 'application-initialized': ApplicationEvent; + 'application-manifest-changed': ApplicationEvent; + 'application-not-responding': ApplicationEvent; + 'application-responding': ApplicationEvent; + 'application-started': ApplicationEvent; + 'application-tray-icon-clicked': TrayIconClicked; + 'window-created': WindowEvent; + 'window-end-load': WindowEndLoadEvent; + 'window-not-responding': WindowEvent; + 'window-responding': WindowEvent; + 'window-start-load': WindowEvent; +} +export declare type ApplicationEvents = PropagatedWindowEvents<'application'> & { + [Type in keyof ApplicationEventMapping]: ApplicationEventMapping<'application', Type>[Type]; +}; +export declare type PropagatedApplicationEvents = { + [Type in keyof PropagatedApplicationEventMapping]: PropagatedApplicationEventMapping[Type]; +}; diff --git a/types/openfin/_v2/api/events/base.d.ts b/types/openfin/_v2/api/events/base.d.ts new file mode 100644 index 0000000000..700f82679b --- /dev/null +++ b/types/openfin/_v2/api/events/base.d.ts @@ -0,0 +1,18 @@ +import { FrameEvent } from './frame'; +export declare type RuntimeEvent = Topic extends 'window' ? WindowEvent : Topic extends 'frame' ? FrameEvent : Topic extends 'application' ? ApplicationEvent : BaseEvent; +export interface BaseEvent { + topic: Topic; + type: Type; +} +export interface ApplicationEvent extends BaseEvent { + uuid: string; +} +export interface WindowEvent extends ApplicationEvent { + name: string; +} +export declare function getTopic(e: RuntimeEvent): string; +export interface BaseEventMap { + [name: string]: any; + 'newListener': string; + 'listenerRemoved': string; +} diff --git a/types/openfin/_v2/api/events/channel.d.ts b/types/openfin/_v2/api/events/channel.d.ts new file mode 100644 index 0000000000..3c448071cb --- /dev/null +++ b/types/openfin/_v2/api/events/channel.d.ts @@ -0,0 +1,10 @@ +import { BaseEventMap, ApplicationEvent } from './base'; +export interface ChannelEvent extends ApplicationEvent<'channel', Type> { + channelName: string; + channelId: string; + name?: string; +} +export interface ChannelEvents extends BaseEventMap { + 'connected': ChannelEvent<'connected'>; + 'disconnected': ChannelEvent<'disconnected'>; +} diff --git a/types/openfin/_v2/api/events/emitterMap.d.ts b/types/openfin/_v2/api/events/emitterMap.d.ts new file mode 100644 index 0000000000..aa3fb498e8 --- /dev/null +++ b/types/openfin/_v2/api/events/emitterMap.d.ts @@ -0,0 +1,15 @@ +/// +import { EventEmitter } from 'events'; +export declare class EmitterMap { + private storage; + constructor(); + private hashKeys; + get(keys: EmitterAccessor): EventEmitter; + has(keys: EmitterAccessor): boolean; + delete(keys: EmitterAccessor): boolean; +} +export declare type SystemEmitterAccessor = ['system']; +export declare type ApplicationEmitterAccessor = ['application', string]; +export declare type WindowEmitterAccessor = ['window', string, string]; +export declare type HotkeyEmitterAccessor = ['global-hotkey']; +export declare type EmitterAccessor = SystemEmitterAccessor | ApplicationEmitterAccessor | WindowEmitterAccessor | HotkeyEmitterAccessor | string[]; diff --git a/types/openfin/_v2/api/events/eventAggregator.d.ts b/types/openfin/_v2/api/events/eventAggregator.d.ts new file mode 100644 index 0000000000..ac7b7ca1b2 --- /dev/null +++ b/types/openfin/_v2/api/events/eventAggregator.d.ts @@ -0,0 +1,5 @@ +import { Message } from '../../transport/transport'; +import { EmitterMap } from './emitterMap'; +export declare class EventAggregator extends EmitterMap { + dispatchEvent: (message: Message) => boolean; +} diff --git a/types/openfin/_v2/api/events/externalApplication.d.ts b/types/openfin/_v2/api/events/externalApplication.d.ts new file mode 100644 index 0000000000..f7cd85f45d --- /dev/null +++ b/types/openfin/_v2/api/events/externalApplication.d.ts @@ -0,0 +1,5 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +export interface ExternalApplicationEvents extends BaseEventMap { + connected: RuntimeEvent<'externalapplication', 'connected'>; + disconnected: RuntimeEvent<'externalapplication', 'disconnected'>; +} diff --git a/types/openfin/_v2/api/events/frame.d.ts b/types/openfin/_v2/api/events/frame.d.ts new file mode 100644 index 0000000000..c31933e557 --- /dev/null +++ b/types/openfin/_v2/api/events/frame.d.ts @@ -0,0 +1,9 @@ +import { BaseEventMap, WindowEvent } from './base'; +export interface FrameEvent extends WindowEvent<'frame', Type> { + entityType: 'iframe'; + frameName: string; +} +export interface FrameEvents extends BaseEventMap { + connected: FrameEvent<'connected'>; + disconnected: FrameEvent<'disconnected'>; +} diff --git a/types/openfin/_v2/api/events/globalHotkey.d.ts b/types/openfin/_v2/api/events/globalHotkey.d.ts new file mode 100644 index 0000000000..561baba446 --- /dev/null +++ b/types/openfin/_v2/api/events/globalHotkey.d.ts @@ -0,0 +1,11 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +import { Identity } from '../../identity'; +import { nonHotkeyEvents } from '../global-hotkey'; +export interface GlobalHotkeyEvent extends RuntimeEvent<'global-hotkey', Type> { + identity: Identity; + hotkey: string; +} +export interface GlobalHotkeyEvents extends BaseEventMap { + [nonHotkeyEvents.REGISTERED]: GlobalHotkeyEvent; + [nonHotkeyEvents.UNREGISTERED]: GlobalHotkeyEvent; +} diff --git a/types/openfin/_v2/api/events/notifications.d.ts b/types/openfin/_v2/api/events/notifications.d.ts new file mode 100644 index 0000000000..a269817222 --- /dev/null +++ b/types/openfin/_v2/api/events/notifications.d.ts @@ -0,0 +1,8 @@ +import { RuntimeEvent, BaseEventMap } from './base'; +export interface NotificationEvents extends BaseEventMap { + show: RuntimeEvent<'notification', 'show'>; + close: RuntimeEvent<'notification', 'close'>; + error: RuntimeEvent<'notification', 'error'>; + click: RuntimeEvent<'notification', 'click'>; + message: RuntimeEvent<'notification', 'message'>; +} diff --git a/types/openfin/_v2/api/events/system.d.ts b/types/openfin/_v2/api/events/system.d.ts new file mode 100644 index 0000000000..20285a8862 --- /dev/null +++ b/types/openfin/_v2/api/events/system.d.ts @@ -0,0 +1,22 @@ +import { BaseEvent, ApplicationEvent, BaseEventMap } from './base'; +import { MonitorInfo } from '../system/monitor'; +import { PropagatedWindowEvents } from './window'; +import { PropagatedApplicationEvents } from './application'; +export interface IdleEvent extends BaseEvent { + elapsedTime: number; + isIdle: boolean; +} +export declare type MonitorEvent = MonitorInfo & BaseEvent; +export interface SessionChangedEvent extends BaseEvent { + reason: 'lock' | 'unlock' | 'remote-connect' | 'remote-disconnect' | 'unknown'; +} +export interface SystemEventMapping extends BaseEventMap { + 'application-created': ApplicationEvent; + 'desktop-icon-clicked': ApplicationEvent; + 'idle-state-changed': IdleEvent; + 'monitor-info-changed': MonitorEvent; + 'session-changed': SessionChangedEvent; +} +export declare type SystemEvents = PropagatedWindowEvents<'system'> & PropagatedApplicationEvents<'system'> & { + [Type in keyof SystemEventMapping]: SystemEventMapping<'system', Type>[Type]; +}; diff --git a/types/openfin/_v2/api/events/window.d.ts b/types/openfin/_v2/api/events/window.d.ts new file mode 100644 index 0000000000..85d4d553f0 --- /dev/null +++ b/types/openfin/_v2/api/events/window.d.ts @@ -0,0 +1,176 @@ +import { CrashedEvent } from './application'; +import { WindowEvent, BaseEventMap } from './base'; +export declare type SpecificWindowEvent = WindowEvent<'window', Type>; +export interface WindowAlertRequestedEvent extends WindowEvent { + message: string; + url: string; +} +export interface WindowAuthRequestedEvent extends WindowEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; +} +export interface WindowEndLoadEvent extends WindowEvent { + documentName: string; + isMain: boolean; +} +export interface WindowNavigationRejectedEvent extends WindowEvent { + sourceName: string; + url: string; +} +export interface WindowReloadedEvent extends WindowEvent { + url: string; +} +export interface WindowExternalProcessExitedEvent extends WindowEvent { + processUuid: string; + exitCode: number; +} +export interface WindowExternalProcessStartedEvent extends WindowEvent { + processUuid: string; +} +export interface WindowHiddenEvent extends WindowEvent { + reason: 'closing' | 'hide' | 'hide-on-close'; +} +export interface PreloadScriptInfoRunning { + state: 'load-started' | // started loading preload script + 'load-failed' | // preload script failed to load + 'load-succeeded' | // preload script is loaded and ready to be eval'ed + 'failed' | // preload script failed to eval + 'succeeded'; +} +export interface PreloadScriptInfo { + state: 'load-failed' | // preload script failed to load + 'failed' | // preload script failed to eval + 'succeeded'; +} +export interface WindowPreloadScriptsStateChangeEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfoRunning & any)[]; +} +export interface WindowPreloadScriptsStateChangedEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfoRunning & any)[]; +} +export interface WindowPreloadScriptsStateChangedEvent extends WindowEvent { + preloadScripts: (PreloadScriptInfo & any)[]; +} +export interface WindowResourceLoadFailedEvent extends WindowEvent { + errorCode: number; + errorDescription: string; + validatedURL: string; + isMainFrame: boolean; +} +export interface WindowResourceResponseReceivedEvent extends WindowEvent { + status: boolean; + newUrl: string; + originalUrl: string; + httpResponseCode: number; + requestMethod: string; + referrer: string; + headers: any; + resourceType: 'mainFrame' | 'subFrame' | 'styleSheet' | 'script' | 'image' | 'object' | 'xhr' | 'other'; +} +export interface WindowBeginBoundsChangingEvent extends WindowEvent { + height: number; + left: number; + top: number; + width: number; + windowState: 'minimized' | 'normal' | 'maximized'; +} +export interface WindowBoundsChange extends WindowEvent { + changeType: 0 | 1 | 2; + deferred: boolean; + height: number; + left: number; + top: number; + width: number; +} +export interface WindowGroupChanged extends WindowEvent { + memberOf: 'source' | 'target' | 'nothing'; + reason: 'leave' | 'join' | 'merge' | 'disband'; + sourceGroup: { + appUuid: string; + windowName: string; + }[]; + sourceWindowAppUuid: string; + sourceWindowName: string; + targetGroup: { + appUuid: string; + windowName: string; + }[]; + targetWindowAppUuid: string; + targetWindowName: string; +} +export interface WindowEventMapping extends BaseEventMap { + 'auth-requested': WindowAuthRequestedEvent; + 'begin-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'blurred': WindowEvent; + 'bounds-changed': WindowBoundsChange; + 'bounds-changing': WindowBoundsChange; + 'close-requested': WindowEvent; + 'closed': WindowEvent; + 'closing': WindowEvent; + 'crashed': CrashedEvent & WindowEvent; + 'disabled-frame-bounds-changed': WindowBoundsChange; + 'disabled-frame-bounds-changing': WindowBoundsChange; + 'embedded': WindowEvent; + 'end-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'external-process-exited': WindowExternalProcessExitedEvent; + 'external-process-started': WindowExternalProcessStartedEvent; + 'focused': WindowEvent; + 'frame-disabled': WindowEvent; + 'frame-enabled': WindowEvent; + 'group-changed': WindowGroupChanged; + 'hidden': WindowHiddenEvent; + 'initialized': WindowEvent; + 'maximized': WindowEvent; + 'minimized': WindowEvent; + 'navigation-rejected': WindowNavigationRejectedEvent; + 'preload-scripts-state-changed': WindowPreloadScriptsStateChangeEvent; + 'preload-scripts-state-changing': WindowPreloadScriptsStateChangeEvent; + 'resource-load-failed': WindowResourceLoadFailedEvent; + 'resource-response-received': WindowResourceResponseReceivedEvent; + 'reloaded': WindowReloadedEvent; + 'restored': WindowEvent; + 'show-requested': WindowEvent; + 'shown': WindowEvent; +} +export interface PropagatedWindowEventMapping extends BaseEventMap { + 'window-begin-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'window-blurred': WindowEvent; + 'window-bounds-changed': WindowBoundsChange; + 'window-bounds-changing': WindowBoundsChange; + 'window-closed': WindowEvent; + 'window-closing': WindowEvent; + 'window-crashed': CrashedEvent & WindowEvent; + 'window-disabled-frame-bounds-changed': WindowBoundsChange; + 'window-disabled-frame-bounds-changing': WindowBoundsChange; + 'window-embedded': WindowEvent; + 'window-end-user-bounds-changing': WindowBeginBoundsChangingEvent; + 'window-external-process-exited': WindowExternalProcessExitedEvent; + 'window-external-process-started': WindowExternalProcessStartedEvent; + 'window-focused': WindowEvent; + 'window-frame-disabled': WindowEvent; + 'window-frame-enabled': WindowEvent; + 'window-group-changed': WindowGroupChanged; + 'window-hidden': WindowHiddenEvent; + 'window-initialized': WindowEvent; + 'window-maximized': WindowEvent; + 'window-minimized': WindowEvent; + 'window-navigation-rejected': WindowNavigationRejectedEvent; + 'window-preload-scripts-state-changed': WindowPreloadScriptsStateChangeEvent; + 'window-preload-scripts-state-changing': WindowPreloadScriptsStateChangedEvent; + 'window-resource-load-failed': WindowResourceLoadFailedEvent; + 'window-resource-response-received': WindowResourceResponseReceivedEvent; + 'window-reloaded': WindowReloadedEvent; + 'window-restored': WindowEvent; + 'window-shown': WindowEvent; +} +export declare type WindowEvents = { + [Type in keyof WindowEventMapping]: WindowEventMapping<'window', Type>[Type]; +}; +export declare type PropagatedWindowEvents = { + [Type in keyof PropagatedWindowEventMapping]: PropagatedWindowEventMapping[Type]; +}; diff --git a/types/openfin/_v2/api/external-application/external-application.d.ts b/types/openfin/_v2/api/external-application/external-application.d.ts index 2d1f46e0f3..a4f44851e9 100644 --- a/types/openfin/_v2/api/external-application/external-application.d.ts +++ b/types/openfin/_v2/api/external-application/external-application.d.ts @@ -1,16 +1,30 @@ -import { Base, EmitterBase, Reply } from '../base'; +import { Base, EmitterBase } from '../base'; import { Identity } from '../../identity'; import Transport from '../../transport/transport'; +import { ExternalApplicationEvents } from '../events/externalApplication'; export interface ExternalApplicationInfo { parent: Identity; } +/** + * @lends ExternalApplication + */ export default class ExternalApplicationModule extends Base { /** - * Returns an External Application object that represents an existing external application. + * Asynchronously returns an External Application object that represents an existing external application. * @param {string} uuid The UUID of the external application to be wrapped * @return {Promise.} + * @tutorial ExternalApplication.wrap + * @static */ wrap(uuid: string): Promise; + /** + * Synchronously returns an External Application object that represents an existing external application. + * @param {string} uuid The UUID of the external application to be wrapped + * @return {ExternalApplication} + * @tutorial ExternalApplication.wrapSync + * @static + */ + wrapSync(uuid: string): ExternalApplication; } /** * @classdesc An ExternalApplication object representing an application. Allows @@ -18,7 +32,7 @@ export default class ExternalApplicationModule extends Base { * well as listen to application events. * @class */ -export declare class ExternalApplication extends EmitterBase { +export declare class ExternalApplication extends EmitterBase { identity: Identity; constructor(wire: Transport, identity: Identity); /** @@ -28,9 +42,3 @@ export declare class ExternalApplication extends EmitterBase { */ getInfo(): Promise; } -export interface ExternalApplication { - on(type: 'connected', listener: (data: Reply<'externalapplication', 'connected'>) => void): Promise; - on(type: 'disconnected', listener: (data: Reply<'externalapplication', 'disconnected'>) => void): Promise; - on(type: 'removeListener', listener: (eventType: string) => void): Promise; - on(type: 'newListener', listener: (eventType: string) => void): Promise; -} diff --git a/types/openfin/_v2/api/frame/frame.d.ts b/types/openfin/_v2/api/frame/frame.d.ts index 4a5ab971de..8795ae190b 100644 --- a/types/openfin/_v2/api/frame/frame.d.ts +++ b/types/openfin/_v2/api/frame/frame.d.ts @@ -1,6 +1,7 @@ import { Base, EmitterBase } from '../base'; import { Identity } from '../../identity'; import Transport from '../../transport/transport'; +import { FrameEvents } from '../events/frame'; export declare type EntityType = 'window' | 'iframe' | 'external connection' | 'unknown'; export interface FrameInfo { uuid: string; @@ -8,19 +9,40 @@ export interface FrameInfo { entityType: EntityType; parent: Identity; } +/** + * @lends Frame + */ export default class _FrameModule extends Base { /** - * Gets a reference to the specified frame. The frame does not have to exist - * @param {string} uuid - uuid of the frame you want to wrap - * @param {string} name - name of the frame you want to wrap + * Asynchronously returns a reference to the specified frame. The frame does not have to exist + * @param {Identity} identity - the identity of the frame you want to wrap * @return {Promise.<_Frame>} + * @tutorial Frame.wrap + * @static */ - wrap(uuid: string, name: string): Promise<_Frame>; + wrap(identity: Identity): Promise<_Frame>; /** - * Get a reference to the current frame + * Synchronously returns a reference to the specified frame. The frame does not have to exist + * @param {Identity} identity - the identity of the frame you want to wrap + * @return {_Frame} + * @tutorial Frame.wrapSync + * @static + */ + wrapSync(identity: Identity): _Frame; + /** + * Asynchronously returns a reference to the current frame * @return {Promise.<_Frame>} + * @tutorial Frame.getCurrent + * @static */ getCurrent(): Promise<_Frame>; + /** + * Synchronously returns a reference to the current frame + * @return {_Frame} + * @tutorial Frame.getCurrentSync + * @static + */ + getCurrentSync(): _Frame; } /** * @classdesc Represents a way to interact with `iframes`. Facilitates discovery of current context @@ -28,7 +50,7 @@ export default class _FrameModule extends Base { * @class * @alias Frame */ -export declare class _Frame extends EmitterBase { +export declare class _Frame extends EmitterBase { identity: Identity; constructor(wire: Transport, identity: Identity); /** @@ -45,7 +67,3 @@ export declare class _Frame extends EmitterBase { */ getParentWindow(): Promise; } -export interface _Frame { - on(type: 'connected', listener: (eventType: string) => void): Promise; - on(type: 'disconnected', listener: (eventType: string) => void): Promise; -} diff --git a/types/openfin/_v2/api/global-hotkey/index.d.ts b/types/openfin/_v2/api/global-hotkey/index.d.ts index 148ddff7e9..7aa08d6f20 100644 --- a/types/openfin/_v2/api/global-hotkey/index.d.ts +++ b/types/openfin/_v2/api/global-hotkey/index.d.ts @@ -1,10 +1,15 @@ import { EmitterBase } from '../base'; import Transport from '../../transport/transport'; +import { GlobalHotkeyEvents } from '../events/globalHotkey'; +export declare const enum nonHotkeyEvents { + REGISTERED = "registered", + UNREGISTERED = "unregistered" +} /** * The GlobalHotkey module can register/unregister a global hotkeys. * @namespace */ -export default class GlobalHotkey extends EmitterBase { +export default class GlobalHotkey extends EmitterBase { constructor(wire: Transport); /** * Registers a global hotkey with the operating system. diff --git a/types/openfin/_v2/api/interappbus/channel/index.d.ts b/types/openfin/_v2/api/interappbus/channel/index.d.ts index 1297d2c5ea..2b2d963932 100644 --- a/types/openfin/_v2/api/interappbus/channel/index.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/index.d.ts @@ -4,30 +4,29 @@ import { ChannelProvider } from './provider'; import { EmitterBase } from '../../base'; import Transport, { Message, Payload } from '../../../transport/transport'; import { ProviderIdentity } from './channel'; -export interface Options { +import { ChannelEvents } from '../../events/channel'; +export interface ConnectOptions { wait?: boolean; - uuid: string; - name?: string; payload?: any; } export interface ChannelPayload { payload: Payload; } -export interface ChannelMessage { +export interface ChannelMessage extends Message { senderIdentity: Identity; ackToSender: any; - providerIdentity: Identity; + providerIdentity: ProviderIdentity; connectAction: boolean; } -export declare class Channel extends EmitterBase { +export declare class Channel extends EmitterBase { private channelMap; constructor(wire: Transport); getAllChannels(): Promise; - onChannelConnect(listener: Function): Promise; - onChannelDisconnect(listener: Function): Promise; - connect(options: Options): Promise; - create(channelName?: string): Promise; - onmessage: (msg: Message) => boolean; + onChannelConnect(listener: (...args: any[]) => void): Promise; + onChannelDisconnect(listener: (...args: any[]) => void): Promise; + connect(channelName: string, options?: ConnectOptions): Promise; + create(channelName: string): Promise; + onmessage: (msg: ChannelMessage) => boolean; private processChannelMessage; private processChannelConnection; } diff --git a/types/openfin/_v2/api/interappbus/channel/provider.d.ts b/types/openfin/_v2/api/interappbus/channel/provider.d.ts index a869928ac2..4b978c2781 100644 --- a/types/openfin/_v2/api/interappbus/channel/provider.d.ts +++ b/types/openfin/_v2/api/interappbus/channel/provider.d.ts @@ -1,13 +1,15 @@ import { ChannelBase, ProviderIdentity } from './channel'; import Transport from '../../../transport/transport'; -export declare type ConnectionListener = (adapterIdentity: ProviderIdentity, connectionMessage?: any) => any; +import { Identity } from '../../../main'; +export declare type ConnectionListener = (identity: Identity, connectionMessage?: any) => any; export declare class ChannelProvider extends ChannelBase { private connectListener; private disconnectListener; - connections: ProviderIdentity[]; + connections: Identity[]; constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); - dispatch(to: ProviderIdentity, action: string, payload: any): Promise; - processConnection(senderId: ProviderIdentity, payload: any): Promise; + dispatch(to: Identity, action: string, payload: any): Promise; + processConnection(senderId: Identity, payload: any): Promise; publish(action: string, payload: any): Promise[]; onConnection(listener: ConnectionListener): void; + onDisconnection(listener: ConnectionListener): void; } diff --git a/types/openfin/_v2/api/notification/notification.d.ts b/types/openfin/_v2/api/notification/notification.d.ts index 8deec180ba..9a6bee7076 100644 --- a/types/openfin/_v2/api/notification/notification.d.ts +++ b/types/openfin/_v2/api/notification/notification.d.ts @@ -1,6 +1,7 @@ import { Base, EmitterBase } from '../base'; import { Identity } from '../../identity'; import Transport from '../../transport/transport'; +import { NotificationEvents } from '../events/notifications'; export declare class NotificationOptions { url: string; message: string; @@ -22,14 +23,12 @@ export interface NotificationCallback { * @class * @alias Notification */ -export declare class _Notification extends EmitterBase { +export declare class _Notification extends EmitterBase { private listenerList; private unhookAllListeners; - private buildLocalPayload; protected options: NotificationOptions; protected generalListener: (msg: any) => void; protected notificationId: number; - protected onmessage: (message: any) => boolean; constructor(wire: Transport, options: NotificationOptions); url: string; timeout: number | string; diff --git a/types/openfin/_v2/api/system/application.d.ts b/types/openfin/_v2/api/system/application.d.ts index 9d7ea09b67..0e14602942 100644 --- a/types/openfin/_v2/api/system/application.d.ts +++ b/types/openfin/_v2/api/system/application.d.ts @@ -1,4 +1,5 @@ export interface ApplicationInfo { isRunning: boolean; uuid: string; + parentUuid?: string; } diff --git a/types/openfin/_v2/api/system/external-process.d.ts b/types/openfin/_v2/api/system/external-process.d.ts index 8a68f1eae3..624c93ea18 100644 --- a/types/openfin/_v2/api/system/external-process.d.ts +++ b/types/openfin/_v2/api/system/external-process.d.ts @@ -1,7 +1,17 @@ export interface ExternalProcessRequestType { - path: string; - arguments: string; - listener: LaunchExternalProcessListener; + path?: string; + alias?: string; + arguments?: string; + listener?: LaunchExternalProcessListener; + lifetime?: string; + certificate?: CertificationInfo; +} +export interface CertificationInfo { + serial?: string; + subject?: string; + publickey?: string; + thumbprint?: string; + trusted?: boolean; } export interface ExitCode { topic: string; @@ -20,3 +30,7 @@ export interface ExternalConnection { token: string; uuid: string; } +export interface ExternalProcessInfo { + pid: number; + listener?: LaunchExternalProcessListener; +} diff --git a/types/openfin/_v2/api/system/host-specs.d.ts b/types/openfin/_v2/api/system/host-specs.d.ts index 2c5a134aea..dfd3e665fd 100644 --- a/types/openfin/_v2/api/system/host-specs.d.ts +++ b/types/openfin/_v2/api/system/host-specs.d.ts @@ -14,9 +14,11 @@ export interface GpuInfo { name: string; } export interface HostSpecs { - cpu: CpuInfo[]; - memory: number; + aeroGlassEnabled?: boolean; arch: string; - name: string; + cpus: CpuInfo[]; gpu: GpuInfo; + memory: number; + name: string; + screenSaver?: boolean; } diff --git a/types/openfin/_v2/api/system/process.d.ts b/types/openfin/_v2/api/system/process.d.ts index 8a513ceecd..98901db137 100644 --- a/types/openfin/_v2/api/system/process.d.ts +++ b/types/openfin/_v2/api/system/process.d.ts @@ -1,15 +1,15 @@ export interface ProcessInfo { - cpuUsage: number; - name: string; - nonPagedPoolUsage: number; - pageFaultCount: number; - pagedPoolUsage: number; - pagefileUsage: number; - peakNonPagedPoolUsage: number; - peakPagedPoolUsage: number; - peakPagefileUsage: number; - peakWorkingSetSize: number; - processId: number; - uuid: string; - workingSetSize: number; + cpuUsage?: number; + name?: string; + nonPagedPoolUsage?: number; + pageFaultCount?: number; + pagedPoolUsage?: number; + pagefileUsage?: number; + peakNonPagedPoolUsage?: number; + peakPagedPoolUsage?: number; + peakPagefileUsage?: number; + peakWorkingSetSize?: number; + processId?: number; + uuid?: string; + workingSetSize?: number; } diff --git a/types/openfin/_v2/api/system/proxy.d.ts b/types/openfin/_v2/api/system/proxy.d.ts index 597afa6548..2f8a945903 100644 --- a/types/openfin/_v2/api/system/proxy.d.ts +++ b/types/openfin/_v2/api/system/proxy.d.ts @@ -1,14 +1,15 @@ export interface ProxyInfo { config: ProxyConfig; - system: { - autoConfigUrl: string; - bypass: ''; - enabled: boolean; - proxy: string; - }; + system: ProxySystemInfo; } export interface ProxyConfig { proxyAddress: string; proxyPort: number; type: string; } +export interface ProxySystemInfo { + autoConfigUrl: string; + bypass: string; + enabled: boolean; + proxy: string; +} diff --git a/types/openfin/_v2/api/system/rvm.d.ts b/types/openfin/_v2/api/system/rvm.d.ts index 42fc0b94db..fb8737a081 100644 --- a/types/openfin/_v2/api/system/rvm.d.ts +++ b/types/openfin/_v2/api/system/rvm.d.ts @@ -1,5 +1,8 @@ export interface RVMInfo { action: string; + appLogDirectory: string; + path: string; 'start-time': string; version: string; + 'working-dir': string; } diff --git a/types/openfin/_v2/api/system/system.d.ts b/types/openfin/_v2/api/system/system.d.ts index 8c0bc7d3b6..76f244cabf 100644 --- a/types/openfin/_v2/api/system/system.d.ts +++ b/types/openfin/_v2/api/system/system.d.ts @@ -12,13 +12,14 @@ import { RVMInfo } from './rvm'; import { RuntimeInfo } from './runtime-info'; import { Entity, EntityInfo } from './entity'; import { HostSpecs } from './host-specs'; -import { ExternalProcessRequestType, TerminateExternalRequestType, ExternalConnection } from './external-process'; +import { ExternalProcessRequestType, TerminateExternalRequestType, ExternalConnection, ExternalProcessInfo } from './external-process'; import Transport from '../../transport/transport'; import { CookieInfo, CookieOption } from './cookie'; import { RegistryInfo } from './registry-info'; import { DownloadPreloadOption, DownloadPreloadInfo } from './download-preload'; import { ClearCacheOption } from './clearCacheOption'; import { CrashReporterOption } from './crashReporterOption'; +import { SystemEvents } from '../events/system'; /** * AppAssetInfo interface * @typedef { Object } AppAssetInfo @@ -35,6 +36,23 @@ import { CrashReporterOption } from './crashReporterOption'; * @typedef { Object } AppAssetRequest * @property { string } alias The name of the asset */ +/** + * ApplicationInfo interface + * @typedef { Object } ApplicationInfo + * @property { boolean } isRunning true when the application is running + * @property { string } uuid uuid of the application + * @property { string } parentUuid uuid of the application that launches this application + */ +/** + * @typedef { Object } ClearCacheOption + * @summary Clear cache options. + * @desc These are the options required by the clearCache function. + * + * @property {boolean} appcache html5 application cache + * @property {boolean} cache browser data cache for html files and images + * @property {boolean} cookies browser cookies + * @property {boolean} localStorage browser data that can be used across sessions + */ /** * CookieInfo interface * @typedef { Object } CookieInfo @@ -48,18 +66,33 @@ import { CrashReporterOption } from './crashReporterOption'; * @property { string } name The name of the cookie */ /** - * ExternalConnection interface - * @typedef { Object } ExternalConnection - * @property { string } token The token to broker an external connection - * @property { string } uuid The uuid of the external connection + * CpuInfo interface + * @typedef { Object } CpuInfo + * @property { string } model The model of the cpu + * @property { number } speed The number in MHz + * @property { Time } times The numbers of milliseconds the CPU has spent in different modes. */ /** -* ExternalProcessRequestType interface -* @typedef { Object } ExternalProcessRequestType -* @property { string } path The file path to where the running application resides -* @property { string } arguments The argument passed to the running application -* @property { Object } listener This is described in the {LaunchExternalProcessListner} type definition +* CrashReporterOption interface +* @typedef { Object } CrashReporterOption +* @property { boolean } diagnosticMode In diagnostic mode the crash reporter will send diagnostic logs to +* the OpenFin reporting service on runtime shutdown +* @property { boolean } isRunning check if it's running */ +/** + * DownloadPreloadInfo interface + * @typedef { Object } DownloadPreloadInfo + * @desc downloadPreloadScripts function return value + * @property { string } url url to the preload script + * @property { string } error error during preload script acquisition + * @property { boolean } succeess download operation success + */ +/** + * DownloadPreloadOption interface + * @typedef { Object } DownloadPreloadOption + * @desc These are the options object required by the downloadPreloadScripts function + * @property { string } url url to the preload script + */ /** * Entity interface * @typedef { Object } Entity @@ -75,18 +108,54 @@ import { CrashReporterOption } from './crashReporterOption'; * @property { string } entityType The type of the entity */ /** -* GetLogRequestType interface -* @typedef { Object } GetLogRequestType -* @property { string } name The name of the running application -* @property { number } endFile The file length of the log file -* @property { number } sizeLimit The set size limit of the log file -*/ + * ExternalConnection interface + * @typedef { Object } ExternalConnection + * @property { string } token The token to broker an external connection + * @property { string } uuid The uuid of the external connection + */ +/** + * ExternalProcessRequestType interface + * @typedef { Object } ExternalProcessRequestType + * @property { string } path The file path to where the running application resides + * @property { string } arguments The argument passed to the running application + * @property { Object } listener This is described in the {LaunchExternalProcessListner} type definition + */ +/** + * GetLogRequestType interface + * @typedef { Object } GetLogRequestType + * @property { string } name The name of the running application + * @property { number } endFile The file length of the log file + * @property { number } sizeLimit The set size limit of the log file + */ +/** + * GpuInfo interface + * @typedef { Object } GpuInfo + * @property { string } name The graphics card name + */ +/** + * HostSpecs interface + * @typedef { Object } HostSpecs + * @property { boolean } aeroGlassEnabled Value to check if Aero Glass theme is supported on Windows platforms + * @property { string } arch "x86" for 32-bit or "x86_64" for 64-bit + * @property { Array } cpus The same payload as Node's os.cpus() + * @property { GpuInfo } gpu The graphics card name + * @property { number } memory The same payload as Node's os.totalmem() + * @property { string } name The OS name and version/edition + * @property { boolean } screenSaver Value to check if screensaver is running. Supported on Windows only + */ /** * Identity interface * @typedef { Object } Identity * @property { string } name The name of the application * @property { string } uuid The uuid of the application */ +/** + * LogInfo interface + * @typedef { Object } LogInfo + * @property { string } name The filename of the log + * @property { number } size The size of the log in bytes + * @property { string } date The unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)"" + */ /** * @typedef { verbose | info | warning | error | fatal } LogLevel * @summary Log verbosity levels. @@ -98,12 +167,49 @@ import { CrashReporterOption } from './crashReporterOption'; * @property { string } error error and above * @property { string } fatal fatal only, indicates a crash is imminent */ +/** + * PointTopLeft interface + * @typedef { Object } PointTopLeft + * @property { number } top The mouse top position in virtual screen coordinates + * @property { number } left The mouse left position in virtual screen coordinates + */ +/** + * ProcessInfo interface + * @typedef { Object } ProcessInfo + * @property { numder } cpuUsage The percentage of total CPU usage + * @property { string } name The application name + * @property { number } nonPagedPoolUsage The current nonpaged pool usage in bytes + * @property { number } pageFaultCount The number of page faults + * @property { number } pagedPoolUsage The current paged pool usage in bytes + * @property { number } pagefileUsage The total amount of memory in bytes that the memory manager has committed + * @property { number } peakNonPagedPoolUsage The peak nonpaged pool usage in bytes + * @property { number } peakPagedPoolUsage The peak paged pool usage in bytes + * @property { number } peakPagefileUsage The peak value in bytes of pagefileUsage during the lifetime of this process + * @property { number } peakWorkingSetSize The peak working set size in bytes + * @property { number } processId The native process identifier + * @property { string } uuid The application UUID + * @property { nubmer } workingSetSize The current working set size (both shared and private data) in bytes + */ /** * ProxyConfig interface * @typedef { Object } ProxyConfig - * @property { numder } proxyPort The port number of the running application - * @property { string } proxyAddress The address of the running application - * @property { string } type + * @property { string } proxyAddress The configured proxy address + * @property { numder } proxyPort The configured proxy port + * @property { string } type The proxy Type + */ +/** + * ProxyInfo interface + * @typedef { Object } ProxyInfo + * @property { ProxyConfig } config The proxy config + * @property { ProxySystemInfo } system The proxy system info + */ +/** + * ProxySystemInfo interface + * @typedef { Object } ProxySystemInfo + * @property { string } autoConfigUrl The auto configuration url + * @property { string } bypass The proxy bypass info + * @property { boolean } enabled Value to check if a proxy is enabled + * @property { string } proxy The proxy info */ /** * RegistryInfo interface @@ -120,6 +226,16 @@ import { CrashReporterOption } from './crashReporterOption'; * @desc These are the options object required by the downloadRuntime function. * @property { string } version The given version to download */ +/** + * RVMInfo interface + * @typedef { Object } RVMInfo + * @property { string } action The name of action: "get-rvm-info" + * @property { string } appLogDirectory The app log directory + * @property { string } path The path of OpenfinRVM.exe + * @property { string } 'start-time' The start time of RVM + * @property { string } version The version of RVM + * @property { string } 'working-dir' The working directory + */ /** * TerminateExternalRequestType interface * @typedef { Object } TerminateExternalRequestType @@ -128,43 +244,41 @@ import { CrashReporterOption } from './crashReporterOption'; * @property { boolean } killtree Value to terminate the running application */ /** - * DownloadPreloadOption interface - * @typedef { Object } DownloadPreloadOption - * @desc These are the options object required by the downloadPreloadScripts function - * @property { string } url url to the preload script + * Time interface + * @typedef { Object } Time + * @property { number } user The number of milliseconds the CPU has spent in user mode + * @property { number } nice The number of milliseconds the CPU has spent in nice mode + * @property { number } sys The number of milliseconds the CPU has spent in sys mode + * @property { number } idle The number of milliseconds the CPU has spent in idle mode + * @property { number } irq The number of milliseconds the CPU has spent in irq mode */ /** - * DownloadPreloadInfo interface - * @typedef { Object } DownloadPreloadInfo - * @desc downloadPreloadScripts function return value - * @property { string } url url to the preload script - * @property { string } error error during preload script acquisition - * @property { boolean } succeess download operation success + * WindowDetail interface + * @typedef { Object } WindowDetail + * @property { number } bottom The bottom-most coordinate of the window + * @property { number } height The height of the window + * @property { boolean } isShowing Value to check if the window is showing + * @property { number } left The left-most coordinate of the window + * @property { string } name The name of the window + * @property { number } right The right-most coordinate of the window + * @property { string } state The window state + * @property { number } top The top-most coordinate of the window + * @property { number } width The width of the window */ /** - * @typedef { Object } ClearCacheOption - * @summary Clear cache options. - * @desc These are the options required by the clearCache function. - * - * @property {boolean} appcache html5 application cache - * @property {boolean} cache browser data cache for html files and images - * @property {boolean} cookies browser cookies - * @property {boolean} localStorage browser data that can be used across sessions + * WindowInfo interface + * @typedef { Object } WindowInfo + * @property { Array } childWindows The array of child windows details + * @property { WindowDetail } mainWindow The main window detail + * @property { string } uuid The uuid of the application */ -/** -* CrashReporterOption interface -* @typedef { Object } CrashReporterOption -* @property { boolean } diagnosticMode In diagnostic mode the crash reporter will send diagnostic logs to -* the OpenFin reporting service on runtime shutdown -* @property { boolean } isRunning check if it's running -*/ /** * An object representing the core of OpenFin Runtime. Allows the developer * to perform system-level actions, such as accessing logs, viewing processes, * clearing the cache and exiting the runtime. * @namespace */ -export default class System extends EmitterBase { +export default class System extends EmitterBase { constructor(wire: Transport); /** * Returns the version of the runtime. The version contains the major, minor, @@ -224,13 +338,6 @@ export default class System extends EmitterBase { * @tutorial System.getCrashReporterState */ getCrashReporterState(): Promise; - /** - * Returns a unique identifier (UUID) for the machine (SHA256 hash of the system's MAC address). - * This call will return the same value on subsequent calls on the same machine(host). - * The values will be different on different machines, and should be considered globally unique. - * @return {Promise.} - * @tutorial System.getDeviceId - */ getDeviceId(): Promise; /** * Start the crash reporter for the browser process if not already running. @@ -275,6 +382,12 @@ export default class System extends EmitterBase { * @tutorial System.getLog */ getLog(options: GetLogRequestType): Promise; + /** + * Returns a unique identifier (UUID) provided by the machine. + * @return {Promise.} + * @tutorial System.getMachineId + */ + getMachineId(): Promise; /** * Returns the minimum (inclusive) logging level that is currently being written to the log. * @return {Promise.} @@ -328,7 +441,7 @@ export default class System extends EmitterBase { getRvmInfo(): Promise; /** * Retrieves system information. - * @return {Promise.} + * @return {Promise.} * @tutorial System.getHostSpecs */ getHostSpecs(): Promise; @@ -341,11 +454,11 @@ export default class System extends EmitterBase { launchExternalProcess(options: ExternalProcessRequestType): Promise; /** * Monitors a running process. - * @param { number } pid See tutorial for more details + * @param { ExternalProcessInfo } options See tutorial for more details * @return {Promise.} * @tutorial System.monitorExternalProcess */ - monitorExternalProcess(pid: number): Promise; + monitorExternalProcess(options: ExternalProcessInfo): Promise; /** * Writes the passed message into both the log file and the console. * @param { string } level The log level for the entry. Can be either "info", "warning" or "error" diff --git a/types/openfin/_v2/api/system/window.d.ts b/types/openfin/_v2/api/system/window.d.ts index 886084fad6..7b2a3b858b 100644 --- a/types/openfin/_v2/api/system/window.d.ts +++ b/types/openfin/_v2/api/system/window.d.ts @@ -1,14 +1,16 @@ export interface WindowInfo { - uuid: string; - mainWindow: WindowDetail; childWindows: Array; + mainWindow: WindowDetail; + uuid: string; } export interface WindowDetail { - name: string; - top: number; - right: number; bottom: number; height: number; - width: number; + isShowing: boolean; left: number; + name: string; + right: number; + state: string; + top: number; + width: number; } diff --git a/types/openfin/_v2/api/window/anchor-type.d.ts b/types/openfin/_v2/api/window/anchor-type.d.ts new file mode 100644 index 0000000000..4e09af40ab --- /dev/null +++ b/types/openfin/_v2/api/window/anchor-type.d.ts @@ -0,0 +1 @@ +export declare type AnchorType = 'top-left' | 'top-right' | 'bottom-left' | 'bottom-right'; diff --git a/types/openfin/_v2/api/window/window.d.ts b/types/openfin/_v2/api/window/window.d.ts index 8d597a6446..fcefc4fa5d 100644 --- a/types/openfin/_v2/api/window/window.d.ts +++ b/types/openfin/_v2/api/window/window.d.ts @@ -1,32 +1,54 @@ -import { Base, EmitterBase, RuntimeEvent } from '../base'; +import { Base, EmitterBase } from '../base'; import { Identity } from '../../identity'; import Bounds from './bounds'; -import BoundsChangedReply from './bounds-changed'; import { Transition, TransitionOptions } from './transition'; import { Application } from '../application/application'; import Transport from '../../transport/transport'; +import { WindowEvents } from '../events/window'; +import { AnchorType } from './anchor-type'; +import { WindowOption } from './windowOption'; +/** + * @lends Window + */ export default class _WindowModule extends Base { - private instance; /** - * Returns a Window object that represents an existing window. - * @param { Identity } indentity + * Asynchronously returns a Window object that represents an existing window. + * @param { Identity } identity * @return {Promise.<_Window>} * @tutorial Window.wrap + * @static */ wrap(identity: Identity): Promise<_Window>; + /** + * Synchronously returns a Window object that represents an existing window. + * @param { Identity } identity + * @return {_Window} + * @tutorial Window.wrapSync + * @static + */ + wrapSync(identity: Identity): _Window; /** * Creates a new Window. - * @param { * } options - Window creation options + * @param { WindowOption } options - Window creation options * @return {Promise.<_Window>} * @tutorial Window.create + * @static */ - create(options: any): Promise<_Window>; + create(options: WindowOption): Promise<_Window>; /** - * Returns a Window object that represents the current window - * @return {Promise.} - * @tutorial window.getCurrent + * Asynchronously returns a Window object that represents the current window + * @return {Promise.<_Window>} + * @tutorial Window.getCurrent + * @static */ getCurrent(): Promise<_Window>; + /** + * Synchronously returns a Window object that represents the current window + * @return {_Window} + * @tutorial Window.getCurrentSync + * @static + */ + getCurrentSync(): _Window; } export interface CloseEventShape { name: string; @@ -47,6 +69,19 @@ export interface FrameInfo { entityType: string; parent?: Identity; } +export interface Area { + height: number; + width: number; + x: number; + y: number; +} +/** + * @typedef { Object } Area + * @property { number } height Area's height + * @property { number } width Area's width + * @property { number } x X coordinate of area's starting point + * @property { number } y Y coordinate of area's starting point + */ /** * @typedef {object} Transition * @property {Opacity} opacity - The Opacity transition @@ -98,7 +133,7 @@ this animation onto the end of the animation queue. * @class * @alias Window */ -export declare class _Window extends EmitterBase { +export declare class _Window extends EmitterBase { identity: Identity; /** * Raised when a window within this application requires credentials from the user. @@ -425,10 +460,8 @@ export declare class _Window extends EmitterBase { * @property {string} state - The preload script state: "load-failed", "failed", "succeeded" */ - private nativeWindow; constructor(wire: Transport, identity: Identity); - createWindow(options: any): Promise<_Window>; - protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; + createWindow(options: WindowOption): Promise<_Window>; private windowListFromNameList; /** * Retrieves an array of frame info objects representing the main frame and any @@ -443,12 +476,6 @@ export declare class _Window extends EmitterBase { * @tutorial Window.getBounds */ getBounds(): Promise; - /** - * Returns the native JavaScript "window" object for the window. - * @return {Promise.} - * @tutorial Window.getNativeWindow - */ - getNativeWindow(): Promise; /** * Gives focus to the window. * @return {Promise.} @@ -561,11 +588,13 @@ export declare class _Window extends EmitterBase { */ getParentWindow(): Promise<_Window>; /** - * Gets a base64 encoded PNG snapshot of the window. + * Gets a base64 encoded PNG snapshot of the window or just part a of it. + * @param { Area } [area] The area of the window to be captured. + * Omitting it will capture the whole visible window. * @return {Promise.} * @tutorial Window.getSnapshot */ - getSnapshot(): Promise; + getSnapshot(area?: Area): Promise; /** * Gets the current state ("minimized", "maximized", or "restored") of the window. * @return {Promise.} @@ -636,24 +665,24 @@ export declare class _Window extends EmitterBase { * Resizes the window by a specified amount. * @param { number } deltaWidth The change in the width of the window * @param { number } deltaHeight The change in the height of the window - * @param { string } anchor Specifies a corner to remain fixed during the resize. - * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right." + * @param { AnchorType } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right". * If undefined, the default is "top-left" * @return {Promise.} * @tutorial Window.resizeBy */ - resizeBy(deltaWidth: number, deltaHeight: number, anchor: string): Promise; + resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType): Promise; /** * Resizes the window to the specified dimensions. * @param { number } width The change in the width of the window * @param { number } height The change in the height of the window - * @param { string } anchor Specifies a corner to remain fixed during the resize. - * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right." + * @param { AnchorType } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right". * If undefined, the default is "top-left" * @return {Promise.} * @tutorial Window.resizeTo */ - resizeTo(width: number, height: number, anchor: string): Promise; + resizeTo(width: number, height: number, anchor: AnchorType): Promise; /** * Restores the window to its normal state (i.e., unminimized, unmaximized). * @return {Promise.} @@ -747,13 +776,3 @@ export declare class _Window extends EmitterBase { */ stopNavigation(): Promise; } -export interface _Window { - on(type: 'focused', listener: Function): Promise; - on(type: 'initialized', listener: Function): Promise; - on(type: 'bounds-changed', listener: (data: BoundsChangedReply) => void): Promise; - on(type: 'hidden', listener: Function): Promise; - on(type: 'removeListener', listener: (eventType: string | symbol) => void): Promise; - on(type: 'newListener', listener: (eventType: string | symbol) => void): Promise; - on(type: 'closed', listener: (eventType: CloseEventShape) => void): Promise; - on(type: 'fire-constructor-callback', listener: Function): Promise; -} diff --git a/types/openfin/_v2/api/window/windowOption.d.ts b/types/openfin/_v2/api/window/windowOption.d.ts new file mode 100644 index 0000000000..faab275187 --- /dev/null +++ b/types/openfin/_v2/api/window/windowOption.d.ts @@ -0,0 +1,46 @@ +import { DownloadPreloadOption } from '../system/download-preload'; +export interface WindowOption { + accelerator?: object; + alwaysOnTop?: boolean; + api?: object; + aspectRatio?: number; + autoShow?: boolean; + backgroundColor?: string; + contentNavigation?: object; + contextMenu?: boolean; + cornerRounding?: object; + customData?: string; + customRequestHeaders?: Array; + defaultCentered?: boolean; + defaultHeight?: number; + defaultLeft?: number; + defaultTop?: number; + defaultWidth?: number; + frame?: boolean; + hideOnClose?: boolean; + icon?: string; + maxHeight?: number; + maximizable?: boolean; + maxWidth?: number; + minHeight?: number; + minimizable?: boolean; + minWidth?: number; + name?: string; + opacity?: number; + preloadScripts?: Array; + resizable?: boolean; + resizeRegion?: object; + saveWindowState?: boolean; + shadow?: boolean; + showTaskbarIcon?: boolean; + smallWindow?: boolean; + state?: string; + taskbarIconGroup?: string; + url?: string; + uuid?: string; + waitForPageLoad?: boolean; +} +export interface CustomRequestHeaders { + urlPatterns: Array; + headers: Array; +} diff --git a/types/openfin/_v2/transport/transport.d.ts b/types/openfin/_v2/transport/transport.d.ts index fb7b967240..519562de95 100644 --- a/types/openfin/_v2/transport/transport.d.ts +++ b/types/openfin/_v2/transport/transport.d.ts @@ -3,6 +3,8 @@ import { Wire, WireConstructor, READY_STATE, ExistingConnectConfig, ConnectConfi import { Identity } from '../identity'; import { EventEmitter } from 'events'; import { Environment } from '../environment/environment'; +import { RuntimeEvent } from '../api/events/base'; +import { EventAggregator } from '../api/events/eventAggregator'; export declare type MessageHandler = (data: any) => boolean; declare class Transport extends EventEmitter { protected wireListeners: Map; protected uncorrelatedListener: Function; - protected messageHandlers: MessageHandler[]; me: Identity; protected wire: Wire; environment: Environment; topicRefMap: Map; sendRaw: Wire['send']; + eventAggregator: EventAggregator; + protected messageHandlers: MessageHandler[]; constructor(wireType: WireConstructor, environment: Environment); connectSync: (config: ConnectConfig) => any; connect(config: InternalConnectConfig): Promise; @@ -38,6 +41,20 @@ export declare class Message { payload: T; correlationId?: number; } +export declare class EventMessage implements Message { + action: 'process-desktop-event'; + payload: RuntimeEvent; +} +export declare class NotificationEventMessage implements Message { + action: 'process-notification-event'; + payload: NotificationEvent; +} +export interface NotificationEvent { + payload: { + notificationId: string; + }; + type: string | symbol; +} export declare class Payload { success: boolean; data: any; diff --git a/types/openfin/index.d.ts b/types/openfin/index.d.ts index fe34f0b630..78b1801b0b 100644 --- a/types/openfin/index.d.ts +++ b/types/openfin/index.d.ts @@ -1,12 +1,13 @@ -// Type definitions for OpenFin API 34.0 +// Type definitions for OpenFin API 37.0 // Project: https://openfin.co/ // Definitions by: Chris Barker // Ricardo de Pena // Roma +// Li Cui // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.9 -// based on v9.61.34.22 +// based on v9.61.37.14 // see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean /** @@ -24,15 +25,51 @@ * without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "documennt" objects. */ declare namespace fin { - var Application: import('./_v2/api/application/application').default - var Clipboard: import('./_v2/api/clipboard/clipboard').default + var Application: import('./_v2/api/application/application').default; + var Clipboard: import('./_v2/api/clipboard/clipboard').default; var ExternalApplication: import('./_v2/api/external-application/external-application').default - var Frame: import('./_v2/api/frame/frame').default - var GlobalHotkey: import('./_v2/api/global-hotkey/index').default - var InterApplicationBus: import('./_v2/api/interappbus/interappbus').default - var Notification: import('./_v2/api/notification/notification').default - var System: import('./_v2/api/system/system').default - var Window: import('./_v2/api/window/window').default + var Frame: import('./_v2/api/frame/frame').default; + var GlobalHotkey: import('./_v2/api/global-hotkey/index').default; + var InterApplicationBus: import('./_v2/api/interappbus/interappbus').default; + var Notification: import('./_v2/api/notification/notification').default; + var System: import('./_v2/api/system/system').default; + var Window: import('./_v2/api/window/window').default; + + // v2 shapes + type Identity = import('./_v2/identity').Identity; + type LaunchInfo = import('./_v2/api/application/application').ApplicationInfo; + type ShortCutConfig = import('./_v2/api/application/application').ShortCutConfig; + type TrayInfo = import('./_v2/api/application/application').TrayInfo; + type ApplicationOption = import('./_v2/api/application/applicationOption').ApplicationOption; + type ExternalApplicationInfo = import('./_v2/api/external-application/external-application').ExternalApplicationInfo; + type ApplicationInfo = import('./_v2/api/system/application').ApplicationInfo; + type ClearCacheOption = import('./_v2/api/system/clearCacheOption').ClearCacheOption; + type CookieInfo = import('./_v2/api/system/cookie').CookieInfo; + type CookieOption = import('./_v2/api/system/cookie').CookieOption; + type AppAssetInfo = import('./_v2/api/system/download-asset').AppAssetInfo; + type AppAssetRequest = import('./_v2/api/system/download-asset').AppAssetRequest; + type RuntimeDownloadOptions = import('./_v2/api/system/download-asset').RuntimeDownloadOptions; + type RuntimeDownloadProgress = import('./_v2/api/system/download-asset').RuntimeDownloadProgress; + type DownloadPreloadInfo = import('./_v2/api/system/download-preload').DownloadPreloadInfo; + type DownloadPreloadOption = import('./_v2/api/system/download-preload').DownloadPreloadOption; + type EntityInfo = import('./_v2/api/system/entity').EntityInfo; + type ExternalProcessRequestType = import('./_v2/api/system/external-process').ExternalProcessRequestType; + type ExternalProcessInfo = import('./_v2/api/system/external-process').ExternalProcessInfo; + type HostSpecs = import('./_v2/api/system/host-specs').HostSpecs; + type LogInfo = import('./_v2/api/system/log').LogInfo; + type MonitorInfo = import('./_v2/api/system/monitor').MonitorInfo; + type PointTopLeft = import('./_v2/api/system/point').PointTopLeft; + type ProcessInfo = import('./_v2/api/system/process').ProcessInfo; + type ProxyInfo = import('./_v2/api/system/proxy').ProxyInfo; + type RegistryInfo = import('./_v2/api/system/registry-info').RegistryInfo; + type RVMInfo = import('./_v2/api/system/rvm').RVMInfo; + type WindowDetail = import('./_v2/api/system/window').WindowDetail; + type WindowInfo = import('./_v2/api/system/window').WindowInfo; + type AnchorType = import('./_v2/api/window/anchor-type').AnchorType; + type Bounds = import('./_v2/api/window/bounds').default; + type Transition = import('./_v2/api/window/transition').Transition; + type TransitionOptions = import('./_v2/api/window/transition').TransitionOptions; + type WindowOption = import('./_v2/api/window/windowOption').WindowOption; const desktop: OpenFinDesktop; @@ -53,7 +90,7 @@ declare namespace fin { * An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events. */ new ( - options: ApplicationOptions, + options: ApplicationOption, callback?: (successObj: { httpResponseCode: number }) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication; /** @@ -124,7 +161,7 @@ declare namespace fin { /** * Retrieves information about the system tray. */ - getTrayIconInfo(callback?: (trayInfo: TrayIconInfo) => void, errorCallback?: (reason: string) => void): void; + getTrayIconInfo(callback?: (trayInfo: TrayInfo) => void, errorCallback?: (reason: string) => void): void; /** * Determines if the application is currently running. */ @@ -188,21 +225,6 @@ declare namespace fin { uuid: string; } - interface ShortCutConfig { - /** - * application has a shortcut on the desktop - */ - desktop?: boolean; - /** - * application has no shortcut in the start menu - */ - startMenu?: boolean; - /** - * application will be launched on system startup - */ - systemStartup?: boolean; - } - interface SuccessObj { httpResponseCode: number; } @@ -216,192 +238,6 @@ declare namespace fin { message: string; } - interface ApplicationOptions { - /** - * The name of the application. - */ - name?: string; - /** - * The url to the application. - */ - url?: string; - /** - * The UUID of the application, unique within the set of all other applications running in the OpenFin Runtime. name and uuid must match. - */ - uuid?: string; - /** - * Enable Flash at the application level. Default: false. - */ - plugins?: boolean; - /** - * The options of the main window of the application. - */ - mainWindowOptions?: WindowOptions; - } - - interface WindowOptions { - /** - * Enable keyboard shortcuts for devtools and zoom. Default: false for both. - */ - accelerator?: { - devtools?: boolean, - zoom?: boolean, - reload?: boolean, - reloadIgnoreCache?: boolean, - }; - /** - * A flag to always position the window at the top of the window stack. Default: false. - * Updatable - */ - alwaysOnTop?: boolean; - /** - * A flag to automatically show the Window when it is created. Default: false. - */ - autoShow?: boolean; - /** - * A flag to show the context menu when right-clicking on a window. Gives access to the Developer Console for the Window. Default: true - * Updatable - */ - contextMenu?: boolean; - /** - * This defines and applies rounded corners for a frameless window. Default for both width and height: 0. - * Updatable - */ - cornerRounding?: { - width?: number; - height?: number; - }; - /** - * A field that the user can attach serializable data to to be ferried around with the window options. Default: ''. - */ - customData?: any; - /** - * Specifies that the window will be positioned in the center of the primary monitor when loaded for the first time on a machine. - * When the window corresponding to that id is loaded again, the position from before the window was closed is used. - * This option overrides defaultLeft and defaultTop. Default: false. - */ - defaultCentered?: boolean; - /** - * The default height of the window. Specifies the height of the window when loaded for the first time on a machine. - * When the window corresponding to that id is loaded again, the height is taken to be the last height of the window before it was closed. Default: 500. - */ - defaultHeight?: number; - /** - * The default left position of the window. Specifies the position of the left of the window when loaded for the first time on a machine. - * When the window corresponding to that id is loaded again, the value of left is taken to be the last value before the window was closed. Default: 100. - */ - defaultWidth?: number; - /** - * The default top position of the window. Specifies the position of the top of the window when loaded for the first time on a machine. - * When the window corresponding to that id is loaded again, the value of top is taken to be the last value before the window was closed. Default: 100. - */ - defaultTop?: number; - /** - * The default width of the window. Specifies the width of the window when loaded for the first time on a machine. - * When the window corresponding to that id is loaded again, the width is taken to be the last width of the window before it was closed. Default: 800. - */ - defaultLeft?: number; - /** - * A flag to show the frame. Default: true. - * Updatable - */ - frame?: boolean; - /** - * A flag to allow a window to be hidden when the close button is clicked.Default: false. - * Updatable - */ - hideOnClose?: boolean; - /** - * A URL for the icon to be shown in the window title bar and the taskbar.Default: The parent application's applicationIcon. - * Updatable - */ - icon?: string; - /** - * The maximum height of a window.Will default to the OS defined value if set to - 1. Default: -1. - * Updatable - */ - maxHeight?: number; - /** - * A flag that lets the window be maximized.Default: true. - * Updatable - */ - maximizable?: boolean; - /** - * The maximum width of a window.Will default to the OS defined value if set to - 1. Default: -1. - * Updatable - */ - maxWidth?: number; - /** - * The minimum height of a window.Default: 0. - * Updatable - */ - minHeight?: number; - /** - * A flag that lets the window be minimized.Default: true. - */ - minimizable?: boolean; - /** - * The minimum width of a window.Default: 0. - */ - minWidth?: number; - /** - * The name for the window which must be unique within the context of the invoking Application. - */ - name?: string; - /** - * A flag that specifies how transparent the window will be.This value is clamped between 0.0 and 1.0.Default: 1.0. - * Updatable - */ - opacity?: number; - /** - * A flag to drop to allow the user to resize the window.Default: true. - * Updatable - */ - resizable?: boolean; - /** - * Defines a region in pixels that will respond to user mouse interaction for resizing a frameless window. - * Updatable - */ - resizeRegion?: { - /** - * The size in pixels (Default: 2), - */ - size?: number; - /** - * The size in pixels of an additional - * square resizable region located at the - * bottom right corner of a - * frameless window. (Default: 4) - */ - bottomRightCorner?: number; - }; - /** - * A flag to show the Window's icon in the taskbar. Default: true. - */ - showTaskbarIcon?: boolean; - /** - * A flag to cache the location of the window or not. Default: true. - */ - saveWindowState?: boolean; - /** - * Specify a taskbar group for the window. Default: app's uuid. - */ - taskbarIconGroup?: string; - /** - * A string that sets the window to be "minimized", "maximized", or "normal" on creation. Default: "normal". - */ - state?: string; - /** - * The URL of the window. Default: "about:blank". - */ - url?: string; - /** - * When set to false, the window will render before the "load" event is fired on the content's window. - * Caution, when false you will see an initial empty white window. Default: true. - */ - waitForPageLoad?: boolean; - } - /** * Clipboard * Clipboard API allows reading and writting to the clipboard in multiple formats. @@ -584,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 */ @@ -637,7 +473,7 @@ declare namespace fin { * Clears cached data containing window state/positions, * application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage. */ - clearCache(options: CacheOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + clearCache(options: ClearCacheOption, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Clears all cached data when OpenFin Runtime exits. */ @@ -679,11 +515,11 @@ declare namespace fin { /** * Retrieves an array of data (name, ids, bounds) for all application windows. */ - getAllWindows(callback?: (windowInfoList: WindowDetails[]) => void, errorCallback?: (reason: string) => void): void; + getAllWindows(callback?: (windowInfoList: WindowInfo[]) => void, errorCallback?: (reason: string) => void): void; /** * Returns information about the app asset. */ - getAppAssetInfo(options: AppAssetOptions, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void; + getAppAssetInfo(options: AppAssetRequest, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void; /** * Get additional info of cookies. */ @@ -715,7 +551,7 @@ declare namespace fin { /** * Retrieves system information. */ - getHostSpecs(callback?: (info: HostSpecInfo) => void, errorCallback?: (reason: string) => void): void; + getHostSpecs(callback?: (info: HostSpecs) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves the contents of the log with the specified filename. */ @@ -735,7 +571,7 @@ declare namespace fin { /** * Returns the mouse in virtual screen coordinates (left, top). */ - getMousePosition(callback?: (mousePosition: VirtualScreenCoordinates) => void, errorCallback?: (reason: string) => void): void; + getMousePosition(callback?: (mousePosition: PointTopLeft) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves an array of all of the runtime processes that are currently running. * Each element in the array is an object containing the uuid and the name of the application to which the process belongs. @@ -748,7 +584,7 @@ declare namespace fin { /** * Returns information about the running RVM in an object. */ - getRvmInfo(callback?: (rvmInfo: RvmInfo) => void, errorCallback?: (reason: string) => void): void; + getRvmInfo(callback?: (rvmInfo: RVMInfo) => void, errorCallback?: (reason: string) => void): void; /** * Returns the version of the runtime. The version contains the major, minor, build and revision numbers. */ @@ -756,7 +592,7 @@ declare namespace fin { /** * Runs an executable or batch file. */ - launchExternalProcess(options: ExternalProcessLaunchInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + launchExternalProcess(options: ExternalProcessRequestType, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; /** * Writes the passed message into both the log file and the console. */ @@ -829,340 +665,6 @@ declare namespace fin { updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void; } - interface CacheOptions { - cache?: boolean; - cookies?: boolean; - localStorage?: boolean; - appcache?: boolean; - userData?: boolean; - } - - interface AppAssetInfo { - src?: string; - alias?: string; - version?: string; - target?: string; - args?: string; - mandatory?: boolean; - } - - interface AppAssetOptions { - alias: string; - } - - interface ApplicationInfo { - /** - * true when the application is running. - */ - isRunning?: boolean; - /** - * uuid of the application. - */ - uuid?: string; - /** - * uuid of the application that launches this application. - */ - parentUuid?: string; - } - - interface Identity { - uuid: string; - name: string; - } - - interface EntityInfo { - name: string; - uuid: string; - parent: Identity; - entityType: string; - } - - interface DownloadPreloadOption { - url: string; - } - - interface DownloadPreloadInfo { - success: boolean; - url?: string; - error: string; - } - - interface CookieInfo { - name: string; - // expirationDate: Date; - domain: string; - path: string; - } - - interface CookieOption { - name: string; - } - - interface RegistryInfo { - data: any; - rootKey: string; - subkey: string; - type: string; - value: string; - } - - interface RuntimeDownloadOptions { - version: string; - } - - interface RuntimeDownloadProgress { - downloadedBytes: number; - totalBytes: number; - } - - interface WindowDetails { - uuid?: string; - mainWindow?: WindowInfo; - childWindows?: WindowInfo[]; - } - - interface WindowInfo { - /** - * name of the child window - */ - name?: string; - /** - * top-most coordinate of the child window - */ - top?: number; - /** - * right-most coordinate of the child window - */ - right?: number; - /** - * bottom-most coordinate of the child window - */ - bottom?: number; - /** - * left-most coordinate of the child window - */ - left?: number; - } - - interface HostSpecInfo { - /** - * "x86" for 32-bit or "x86_64" for 64-bit - */ - arch: string; - /** - * Same payload as Node's os.cpus() - */ - cpus: NodeCpuInfo[]; - gpu: { - /** - * Graphics card name - */ - name: string; - }; - /** - * Same payload as Node's os.totalmem() - */ - memory: number; - /** - * OS name and version/edition - */ - name: string; - } - - interface NodeCpuInfo { - model: string; - /** - * in MHz - */ - speed: number; - times: { - /** - * The number of milliseconds the CPU has spent in user mode. - */ - user: number; - /** - * The number of milliseconds the CPU has spent in nice mode. - */ - nice: number; - /** - * The number of milliseconds the CPU has spent in sys mode. - */ - sys: number; - /** - * The number of milliseconds the CPU has spent in idle mode. - */ - idle: number; - /** - * The number of milliseconds the CPU has spent in irq mode. - */ - irq: number; - }; - } - - interface LogInfo { - /** - * the filename of the log - */ - name?: string; - /** - * the size of the log in bytes - */ - size?: number; - /** - * the unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)" - */ - date?: string; - } - - interface ProcessInfo { - /** - * the percentage of total CPU usage - */ - cpuUsage?: number; - /** - * the application name - */ - name?: string; - /** - * the current nonpaged pool usage in bytes - */ - nonPagedPoolUsage?: number; - /** - * the number of page faults - */ - pageFaultCount?: number; - /** - * the current paged pool usage in bytes - */ - pagedPoolUsage?: number; - /** - * the total amount of memory in bytes that the memory manager has committed - */ - pagefileUsage?: number; - /** - * the peak nonpaged pool usage in bytes - */ - peakNonPagedPoolUsage?: number; - /** - * the peak paged pool usage in bytes - */ - peakPagedPoolUsage?: number; - /** - * the peak value in bytes of pagefileUsage during the lifetime of this process - */ - peakPagefileUsage?: number; - /** - * the peak working set size in bytes - */ - peakWorkingSetSize?: number; - /** - * the native process identifier - */ - processId?: number; - /** - * the application UUID - */ - uuid?: string; - /** - * the current working set size (both shared and private data) in bytes - */ - workingSetSize?: number; - } - - interface ProxyInfo { - /** - * the configured Proxy Address - */ - proxyAddress?: string; - /** - * the configured Proxy port - */ - proxyPort?: number; - /** - * Proxy Type - */ - type?: string; - } - - interface RvmInfo { - version?: string; - "start-time"?: string; - } - - interface ExternalProcessLaunchInfo { - path?: string; - /** - * Additionally note that the executable found in the zip file specified in appAssets - * will default to the one mentioned by appAssets.target - * If the the path below refers to a specific path it will override this default - */ - alias?: string; - /** - * When using alias; if no arguments are passed then the arguments (if any) - * are taken from the 'app.json' file, from the 'args' parameter - * of the 'appAssets' Object with the relevant 'alias'. - * If 'arguments' is passed as a parameter it takes precedence - * over any 'args' set in the 'app.json'. - */ - arguments?: string; - listener?(result: { - /** - * "Exited" Or "released" on a call to releaseExternalProcess - */ - topic?: string; - /** - * The mapped UUID which identifies the launched process - */ - uuid?: string; - /* - * Process exit code - */ - exitCode?: number; - }): void; - certificate?: CertificationInfo; - } - - interface CertificationInfo { - /** - * A hex string with or without spaces - */ - serial?: string; - /** - * An internally tokenized and comma delimited string allowing partial or full checks of the subject fields - */ - subject?: string; - /** - * A hex string with or without spaces - */ - publickey?: string; - /** - * A hex string with or without spaces - */ - thumbprint?: string; - /** - * A boolean indicating that the certificate is trusted and not revoked - */ - trusted?: boolean; - } - - interface ExternalProcessInfo { - pid?: number; - listener?(result: { - /** - * "Exited" Or "released" on a call to releaseExternalProcess - */ - topic?: string; - /** - * The mapped UUID which identifies the launched process - */ - uuid?: string; - /* - * Process exit code - */ - exitCode?: number; - }): void; - } - interface OpenFinWindowStatic { /** * Class: Window @@ -1179,7 +681,7 @@ declare namespace fin { * @param [callback.successObj] - httpResponseCode */ new ( - options: WindowOptions, + options: WindowOption, callback?: (successObj: { httpResponseCode: number }) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow; /** @@ -1242,7 +744,7 @@ declare namespace fin { /** * Performs the specified window transitions */ - animate(transitions: AnimationTransition, options: AnimationOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void; + animate(transitions: Transition, options: TransitionOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void; /** * Provides credentials to authentication requests */ @@ -1287,7 +789,7 @@ declare namespace fin { /** * Gets the current bounds (top, left, width, height) of the window. */ - getBounds(callback?: (bounds: WindowBounds) => void, errorCallback?: (reason: string) => void): void; + getBounds(callback?: (bounds: Bounds) => void, errorCallback?: (reason: string) => void): void; /** * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned. * Please note that calling window is included in the result array. @@ -1296,15 +798,15 @@ declare namespace fin { /** * Gets the current settings of the window. */ - getOptions(callback?: (options: WindowOptions) => void, errorCallback?: (reason: string) => void): void; + getOptions(callback?: (options: WindowOption) => void, errorCallback?: (reason: string) => void): void; /** * Gets a base64 encoded PNG snapshot of the window. */ 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. */ @@ -1363,11 +865,11 @@ declare namespace fin { /** * Resizes the window by a specified amount. */ - resizeBy(deltaWidth: number, deltaHeight: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + resizeBy(deltaWidth: number, deltaHeight: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Resizes the window by a specified amount. */ - resizeTo(width: number, height: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + resizeTo(width: number, height: number, anchor: AnchorType, callback?: () => void, errorCallback?: (reason: string) => void): void; /** * Restores the window to its normal state (i.e., unminimized, unmaximized). */ @@ -1400,7 +902,7 @@ declare namespace fin { /** * Updates the window using the passed options */ - updateOptions(options: WindowOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + updateOptions(options: WindowOption, callback?: () => void, errorCallback?: (reason: string) => void): void; } interface OpenFinFrameStatic { @@ -1469,51 +971,6 @@ declare namespace fin { type: "monitor-info-changed"; } - interface MonitorInfo { - nonPrimaryMonitors: MonitorInfoDetail[]; - primaryMonitor: MonitorInfoDetail; - reason: string; - taskbar: { - edge: "left" | "right" | "top" | "bottom", - rect: MontiorCoordinates - }; - topic: "system"; - type: "monitor-info-changed"; - virtualScreen: MontiorCoordinates; - } - - interface TrayIconInfo { - x: number; - y: number; - bounds: { - x: number; - y: number; - width: number; - height: number; - }; - monitorInfo: MonitorInfo; - } - - interface MonitorInfoDetail { - availableRect: MontiorCoordinates; - deviceId: string; - displayDeviceActive: boolean; - monitorRect: MontiorCoordinates; - name: string; - } - - interface MontiorCoordinates { - bottom: number; - left: number; - right: number; - top: number; - } - - interface VirtualScreenCoordinates { - left: number; - top: number; - } - interface SystemBaseEvent { topic: string; type: OpenFinSystemEventType; @@ -1713,96 +1170,6 @@ declare namespace fin { uuid: string; } - interface AnimationTransition { - opacity?: { - /** - * This value is clamped from 0.0 to 1.0 - */ - opacity?: number; - /** - * The total time in milliseconds this transition should take. - */ - duration?: number; - /** - * Treat 'opacity' as absolute or as a delta. Defaults to false. - */ - relative?: boolean; - }; - position?: { - /** - * Defaults to the window's current left position in virtual screen coordinates. - */ - left?: number; - /** - * Defaults to the window's current top position in virtual screen coordinates. - */ - top?: number; - /** - * The total time in milliseconds this transition should take. - */ - duration?: number; - /** - * Treat 'left' and 'top' as absolute or as deltas. Defaults to false. - */ - relative?: boolean; - }; - size?: { - /** - * Optional if height is present. Defaults to the window's current width. - */ - width?: number; - /** - * Optional if width is present. Defaults to the window's current height. - */ - height?: number; - /** - * The total time in milliseconds this transition should take. - */ - duration?: number; - /** - * Treat 'width' and 'height' as absolute or as deltas. Defaults to false. - */ - relative?: boolean; - }; - } - - interface AnimationOptions { - /** - * This option interrupts the current animation. When false it pushes this animation onto the end of the animation queue. - */ - interrupt?: boolean; - /** - * Transition effect. Defaults to 'ease-in-out'. - */ - tween?: OpenFinTweenType; - } - - interface WindowBounds { - /** - * the height of the window. - */ - height?: number; - /** - * left-most coordinate of the window. - */ - left?: number; - /** - * top-most coordinate of the window. - */ - top?: number; - /** - * the width of the window. - */ - width?: number; - } - - interface ExternalApplicationInfo { - parent: { - uuid: string; - name: string; - }; - } - interface SessionChangedEvent { /** * the action that triggered this event: @@ -1816,34 +1183,6 @@ declare namespace fin { type: "session-changed"; } - interface LaunchInfo { - launchMode: "fin-protocol" - | "fins-protocol" - | "shortcut" - | "command-line" - | "adapter" - | "other" - | string; - } - - type OpenFinTweenType = "linear" - | "ease-in" - | "ease-out" - | "ease-in-out" - | "ease-in-quad" - | "ease-out-quad" - | "ease-in-out-quad" - | "ease-in-cubic" - | "ease-out-cubic" - | "ease-in-out-cubic" - | "ease-out-bounce" - | "ease-in-back" - | "ease-out-back" - | "ease-in-out-back" - | "ease-in-elastic" - | "ease-out-elastic" - | "ease-in-out-elastic"; - type OpenFinApplicationEventType = "closed" | "connected" | "crashed" @@ -1899,9 +1238,4 @@ declare namespace fin { | "restored" | "show-requested" | "shown"; - - type OpenFinAnchor = "top-left" - | "top-right" - | "bottom-left" - | "bottom-right"; } diff --git a/types/openfin/openfin-tests.ts b/types/openfin/openfin-tests.ts index 6059f54de7..e4430ff9c2 100644 --- a/types/openfin/openfin-tests.ts +++ b/types/openfin/openfin-tests.ts @@ -78,8 +78,8 @@ function test_application() { }); // getTrayIconInfo application.getTrayIconInfo(info => { - console.log(info.x, info.y, info.bounds.x, info.bounds.y, info.bounds.height, info.bounds.width, - info.monitorInfo.type, info.monitorInfo.reason); + console.log(info.x, info.y, info.bounds.left, info.bounds.top, info.bounds.height, info.bounds.width, + info.monitorInfo.reason); }); // isRunning application.isRunning(running => { @@ -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: () => { }, @@ -235,8 +235,7 @@ function test_system() { cache: true, cookies: true, localStorage: true, - appcache: true, - userData: true + appcache: true }); // deleteCacheOnExit fin.desktop.System.deleteCacheOnExit(() => { diff --git a/types/openfin/tsconfig.json b/types/openfin/tsconfig.json index 2a2c9d108b..a7f3e48849 100644 --- a/types/openfin/tsconfig.json +++ b/types/openfin/tsconfig.json @@ -21,6 +21,7 @@ "index.d.ts", "openfin-tests.ts", "_v2/api/application/application.d.ts", + "_v2/api/application/applicationOption.d.ts", "_v2/api/base.d.ts", "_v2/api/clipboard/clipboard.d.ts", "_v2/api/clipboard/write-request.d.ts", @@ -53,10 +54,12 @@ "_v2/api/system/rvm.d.ts", "_v2/api/system/system.d.ts", "_v2/api/system/window.d.ts", + "_v2/api/window/anchor-type.d.ts", "_v2/api/window/bounds-changed.d.ts", "_v2/api/window/bounds.d.ts", "_v2/api/window/transition.d.ts", "_v2/api/window/window.d.ts", + "_v2/api/window/windowOption.d.ts", "_v2/environment/environment.d.ts", "_v2/environment/node-env.d.ts", "_v2/environment/openfin-env.d.ts", diff --git a/types/openfin/v34/_v2/api/application/application.d.ts b/types/openfin/v34/_v2/api/application/application.d.ts new file mode 100644 index 0000000000..616501834d --- /dev/null +++ b/types/openfin/v34/_v2/api/application/application.d.ts @@ -0,0 +1,223 @@ +import { EmitterBase, Base, Reply, RuntimeEvent } from '../base'; +import { Identity } from '../../identity'; +import { _Window } from '../window/window'; +import { Point } from '../system/point'; +import { MonitorInfo } from '../system/monitor'; +import Transport from '../../transport/transport'; +import Bounds from '../window/bounds'; +export interface TrayIconClickReply extends Point, Reply<'application', 'tray-icon-clicked'> { + button: number; + monitorInfo: MonitorInfo; +} +export interface ApplicationInfo { + initialOptions: object; + launchMode: string; + manifest: object; + manifestUrl: string; + parentUuid?: string; + runtime: object; +} +export declare class NavigationRejectedReply extends Reply<'window-navigation-rejected', void> { + sourceName: string; + url: string; +} +export interface ConfigInterface { + desktop?: boolean; + startMenu?: boolean; + systemStartup?: boolean; +} +export interface TrayInfo { + bounds: Bounds; + monitorInfo: MonitorInfo; + x: number; + y: number; +} +export default class ApplicationModule extends Base { + /** + * Returns an Application object that represents an existing application. + * @param { Identity } indentity + * @return {Promise.} + * @tutorial Application.wrap + */ + wrap(identity: Identity): Promise; + /** + * Creates a new Application. + * @param {*} appOptions + * @return {Promise.} + * @tutorial Application.create + */ + create(appOptions: any): Promise; + /** + * Returns an Application object that represents the current application + * @return {Promise.} + * @tutorial Application.getCurrent + */ + getCurrent(): Promise; + /** + * Retrieves application's manifest and returns a wrapped application. + * @param {string} manifestUrl - The URL of app's manifest. + * @return {Promise.} + * @tutorial Application.createFromManifest + */ + createFromManifest(manifestUrl: string): Promise; +} +/** + * @classdesc An object representing an application. Allows the developer to create, + * execute, show/close an application as well as listen to application events. + * @class + */ +export declare class Application extends EmitterBase { + identity: Identity; + _manifestUrl?: string; + private window; + constructor(wire: Transport, identity: Identity); + protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; + private windowListFromIdentityList; + /** + * Determines if the application is currently running. + * @return {Promise.} + * @tutorial Application.isRunning + */ + isRunning(): Promise; + /** + * Closes the application and any child windows created by the application. + * @param { boolean } [force = false] Close will be prevented from closing when force is false and + * ‘close-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Application.close + */ + close(force?: boolean): Promise; + /** + * Retrieves an array of wrapped fin.Windows for each of the application’s child windows. + * @return {Promise.Array.<_Window>} + * @tutorial Application.getChildWindows + */ + getChildWindows(): Promise>; + /** + * Retrieves an array of active window groups for all of the application's windows. Each group is + * represented as an array of wrapped fin.Windows. + * @return {Promise.Array.Array.<_Window>} + * @tutorial Application.getGroups + */ + getGroups(): Promise>>; + /** + * Retrieves the JSON manifest that was used to create the application. Invokes the error callback + * if the application was not created from a manifest. + * @return {Promise.} + * @tutorial Application.getManifest + */ + getManifest(): Promise; + /** + * Retrieves UUID of the application that launches this application. Invokes the error callback + * if the application was created from a manifest. + * @return {Promise.} + * @tutorial Application.getParentUuid + */ + getParentUuid(): Promise; + /** + * Retrieves current application's shortcut configuration. + * @return {Promise.} + * @tutorial Application.getShortcuts + */ + getShortcuts(): Promise; + /** + * Returns an instance of the main Window of the application + * @return {Promise.<_Window>} + * @tutorial Application.getWindow + */ + getWindow(): Promise<_Window>; + /** + * Manually registers a user with the licensing service. The only data sent by this call is userName and appName. + * @param { string } userName - username to be passed to the RVM. + * @param { string } appName - app name to be passed to the RVM. + * @return {Promise.} + * @tutorial Application.registerUser + */ + registerUser(userName: string, appName: string): Promise; + /** + * Removes the application’s icon from the tray. + * @return {Promise.} + * @tutorial Application.removeTrayIcon + */ + removeTrayIcon(): Promise; + /** + * Restarts the application. + * @return {Promise.} + * @tutorial Application.restart + */ + restart(): Promise; + /** + * Runs the application. When the application is created, run must be called. + * @return {Promise.} + * @tutorial Application.run + */ + run(): Promise; + /** + * Instructs the RVM to schedule one restart of the application. + * @return {Promise.} + * @tutorial Application.scheduleRestart + */ + scheduleRestart(): Promise; + /** + * Adds a customizable icon in the system tray and notifies the application when clicked. + * @param { string } iconUrl Image URL to be used as the icon + * @return {Promise.} + * @tutorial Application.setTrayIcon + */ + setTrayIcon(iconUrl: string): Promise; + /** + * Sets new application's shortcut configuration. + * @param { Object } config New application's shortcut configuration. + * @param {Boolean} [config.desktop] - Enable/disable desktop shortcut. + * @param {Boolean} [config.startMenu] - Enable/disable start menu shortcut. + * @param {Boolean} [config.systemStartup] - Enable/disable system startup shortcut. + * @return {Promise.} + * @tutorial Application.setShortcuts + */ + setShortcuts(config: ConfigInterface): Promise; + /** + * @summary Retrieves information about the system tray. + * @desc The only information currently returned is the position and dimensions. + * @return {Promise.} + * @tutorial Application.getTrayIconInfo + */ + getTrayIconInfo(): Promise; + /** + * Closes the application by terminating its process. + * @return {Promise.} + * @tutorial Application.terminate + */ + terminate(): Promise; + /** + * Waits for a hanging application. This method can be called in response to an application + * "not-responding" to allow the application to continue and to generate another "not-responding" + * message after a certain period of time. + * @return {Promise.} + * @ignore + */ + wait(): Promise; + /** + * Retrieves information about the application. + * @return {Promise.} + * @tutorial Application.getInfo + */ + getInfo(): Promise; +} +export interface Application { + on(type: 'closed', listener: (data: Reply<'application', 'closed'>) => void): Promise; + on(type: 'initialized', listener: (data: Reply<'application', 'initialized'>) => void): Promise; + on(type: 'connected', listener: (data: Reply<'application', 'connected'>) => void): Promise; + on(type: 'crashed', listener: (data: Reply<'application', 'crashed'>) => void): Promise; + on(type: 'error', listener: (data: Reply<'application', 'error'>) => void): Promise; + on(type: 'not-responding', listener: (data: Reply<'application', 'not-responding'>) => void): Promise; + on(type: 'out-of-memory', listener: (data: Reply<'application', 'out-of-memory'>) => void): Promise; + on(type: 'responding', listener: (data: Reply<'application', 'responding'>) => void): Promise; + on(type: 'started', listener: (data: Reply<'application', 'started'>) => void): Promise; + on(type: 'run-requested', listener: (data: Reply<'application', 'run-requested'>) => void): Promise; + on(type: 'window-navigation-rejected', listener: (data: NavigationRejectedReply) => void): Promise; + on(type: 'window-created', listener: (data: Reply<'application', 'window-created'>) => void): Promise; + on(type: 'window-closed', listener: (data: Reply<'application', 'window-closed'>) => void): Promise; + on(type: 'tray-icon-clicked', listener: (data: TrayIconClickReply) => void): Promise; + on(type: 'removeListener', listener: (eventType: string) => void): Promise; + on(type: 'newListener', listener: (eventType: string) => void): Promise; +} diff --git a/types/openfin/v34/_v2/api/base.d.ts b/types/openfin/v34/_v2/api/base.d.ts new file mode 100644 index 0000000000..1f17e1f24f --- /dev/null +++ b/types/openfin/v34/_v2/api/base.d.ts @@ -0,0 +1,43 @@ +/// +import Transport, { Message } from '../transport/transport'; +import { Identity } from '../identity'; +import { EventEmitter } from 'events'; +export interface RuntimeEvent extends Identity { + topic: string; + type: string | symbol; +} +export declare class Base { + wire: Transport; + constructor(wire: Transport); + private _topic; + protected topic: string; + readonly me: Identity; + protected isNodeEnvironment: () => boolean; + protected isOpenFinEnvironment: () => boolean; + protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; +} +export declare class EmitterBase extends Base { + protected identity: Identity; + protected emitter: EventEmitter; + listeners: (event: string | symbol) => Function[]; + listenerCount: (type: string | symbol) => number; + constructor(wire: Transport); + emit: (eventName: string | symbol, ...args: any[]) => void; + protected onmessage: (message: Message) => boolean; + protected registerEventListener: (listener: RuntimeEvent) => Promise>; + protected deregisterEventListener: (listener: RuntimeEvent) => Promise>; + on(eventType: string, listener: (...args: any[]) => void): Promise; + addListener: (eventType: string, listener: (...args: any[]) => void) => Promise; + once(eventType: string, listener: (...args: any[]) => void): Promise; + prependListener(eventType: string, listener: (...args: any[]) => void): Promise; + prependOnceListener(eventType: string, listener: (...args: any[]) => void): Promise; + removeListener(eventType: string, listener: (...args: any[]) => void): Promise; + protected deregisterAllListeners: (eventType: string | symbol) => Promise>; + removeAllListeners(eventType?: string): Promise; +} +export declare class Reply implements Identity { + topic: TOPIC; + type: TYPE; + uuid: string; + name?: string; +} diff --git a/types/openfin/v34/_v2/api/clipboard/clipboard.d.ts b/types/openfin/v34/_v2/api/clipboard/clipboard.d.ts new file mode 100644 index 0000000000..11b466dea0 --- /dev/null +++ b/types/openfin/v34/_v2/api/clipboard/clipboard.d.ts @@ -0,0 +1,70 @@ +import { Base } from '../base'; +import { WriteRequestType, WriteAnyRequestType } from './write-request'; +/** + * WriteRequestType interface + * @typedef { Object } WriteRequestType + * @property { string } name The name of the running application + * @property { string } uuid The uuid of the running application + */ +/** + * The Clipboard API allows reading and writing to the clipboard in multiple formats. + * @namespace +*/ +export default class Clipboard extends Base { + /** + * Writes data into the clipboard as plain text + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typeof + * @return {Promise.} + * @tutorial Clipboard.writeText + */ + writeText(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as plain text + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readText + */ + readText(type?: string): Promise; + /** + * Writes data into the clipboard as Html + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.writeHtml + */ + writeHtml(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as Html + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readHtml + */ + readHtml(type?: string): Promise; + /** + * Writes data into the clipboard as Rtf + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.writeRtf + */ + writeRtf(writeObj: WriteRequestType): Promise; + /** + * Read the content of the clipboard as Rtf + * @param { string } type Clipboard Type + * @return {Promise.} + * @tutorial Clipboard.readRtf + */ + readRtf(type?: string): Promise; + /** + * Writes data into the clipboard + * @param { WriteRequestType } writeObj This object is described in the WriteRequestType typedef + * @return {Promise.} + * @tutorial Clipboard.write + */ + write(writeObj: WriteAnyRequestType): Promise; + /** + * Reads available formats for the clipboard type + * @param { string } type Clipboard Type + * @return {Promise.Array.} + * @tutorial Clipboard.getAvailableFormats + */ + getAvailableFormats(type?: string): Promise>; +} diff --git a/types/openfin/v34/_v2/api/clipboard/write-request.d.ts b/types/openfin/v34/_v2/api/clipboard/write-request.d.ts new file mode 100644 index 0000000000..a2fc5c333e --- /dev/null +++ b/types/openfin/v34/_v2/api/clipboard/write-request.d.ts @@ -0,0 +1,12 @@ +export interface WriteRequestType { + data: string; + type?: string; +} +export interface WriteAnyRequestType { + data: { + text?: string; + html?: string; + rtf?: string; + }; + type?: string; +} diff --git a/types/openfin/v34/_v2/api/external-application/external-application.d.ts b/types/openfin/v34/_v2/api/external-application/external-application.d.ts new file mode 100644 index 0000000000..2d1f46e0f3 --- /dev/null +++ b/types/openfin/v34/_v2/api/external-application/external-application.d.ts @@ -0,0 +1,36 @@ +import { Base, EmitterBase, Reply } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +export interface ExternalApplicationInfo { + parent: Identity; +} +export default class ExternalApplicationModule extends Base { + /** + * Returns an External Application object that represents an existing external application. + * @param {string} uuid The UUID of the external application to be wrapped + * @return {Promise.} + */ + wrap(uuid: string): Promise; +} +/** + * @classdesc An ExternalApplication object representing an application. Allows + * the developer to create, execute, show and close an external application as + * well as listen to application events. + * @class + */ +export declare class ExternalApplication extends EmitterBase { + identity: Identity; + constructor(wire: Transport, identity: Identity); + /** + * Retrieves information about the external application. + * @return {Promise.} + * @tutorial ExternalApplication.getInfo + */ + getInfo(): Promise; +} +export interface ExternalApplication { + on(type: 'connected', listener: (data: Reply<'externalapplication', 'connected'>) => void): Promise; + on(type: 'disconnected', listener: (data: Reply<'externalapplication', 'disconnected'>) => void): Promise; + on(type: 'removeListener', listener: (eventType: string) => void): Promise; + on(type: 'newListener', listener: (eventType: string) => void): Promise; +} diff --git a/types/openfin/v34/_v2/api/fin.d.ts b/types/openfin/v34/_v2/api/fin.d.ts new file mode 100644 index 0000000000..1bec2ffb4f --- /dev/null +++ b/types/openfin/v34/_v2/api/fin.d.ts @@ -0,0 +1,27 @@ +/// +import Transport from '../transport/transport'; +import { EventEmitter } from 'events'; +import System from './system/system'; +import _WindowModule from './window/window'; +import Application from './application/application'; +import InterApplicationBus from './interappbus/interappbus'; +import _NotificationModule from './notification/notification'; +import Clipbpard from './clipboard/clipboard'; +import ExternalApplication from './external-application/external-application'; +import _FrameModule from './frame/frame'; +import GlobalHotkey from './global-hotkey'; +import { Identity } from '../identity'; +export default class Fin extends EventEmitter { + private wire; + System: System; + Window: _WindowModule; + Application: Application; + InterApplicationBus: InterApplicationBus; + Notification: _NotificationModule; + Clipboard: Clipbpard; + ExternalApplication: ExternalApplication; + Frame: _FrameModule; + GlobalHotkey: GlobalHotkey; + readonly me: Identity; + constructor(wire: Transport); +} diff --git a/types/openfin/v34/_v2/api/frame/frame.d.ts b/types/openfin/v34/_v2/api/frame/frame.d.ts new file mode 100644 index 0000000000..4a5ab971de --- /dev/null +++ b/types/openfin/v34/_v2/api/frame/frame.d.ts @@ -0,0 +1,51 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +export declare type EntityType = 'window' | 'iframe' | 'external connection' | 'unknown'; +export interface FrameInfo { + uuid: string; + name: string; + entityType: EntityType; + parent: Identity; +} +export default class _FrameModule extends Base { + /** + * Gets a reference to the specified frame. The frame does not have to exist + * @param {string} uuid - uuid of the frame you want to wrap + * @param {string} name - name of the frame you want to wrap + * @return {Promise.<_Frame>} + */ + wrap(uuid: string, name: string): Promise<_Frame>; + /** + * Get a reference to the current frame + * @return {Promise.<_Frame>} + */ + getCurrent(): Promise<_Frame>; +} +/** + * @classdesc Represents a way to interact with `iframes`. Facilitates discovery of current context + * (iframe or main window) as well as the ability to listen for frame-specific events. + * @class + * @alias Frame + */ +export declare class _Frame extends EmitterBase { + identity: Identity; + constructor(wire: Transport, identity: Identity); + /** + * Returns a frame info object for the represented frame + * @return {Promise.} + * @tutorial Frame.getInfo + */ + getInfo(): Promise; + /** + * Returns a frame info object representing the window that the referenced iframe is + * currently embedded in + * @return {Promise.} + * @tutorial Frame.getParentWindow + */ + getParentWindow(): Promise; +} +export interface _Frame { + on(type: 'connected', listener: (eventType: string) => void): Promise; + on(type: 'disconnected', listener: (eventType: string) => void): Promise; +} diff --git a/types/openfin/v34/_v2/api/global-hotkey/index.d.ts b/types/openfin/v34/_v2/api/global-hotkey/index.d.ts new file mode 100644 index 0000000000..148ddff7e9 --- /dev/null +++ b/types/openfin/v34/_v2/api/global-hotkey/index.d.ts @@ -0,0 +1,33 @@ +import { EmitterBase } from '../base'; +import Transport from '../../transport/transport'; +/** + * The GlobalHotkey module can register/unregister a global hotkeys. + * @namespace + */ +export default class GlobalHotkey extends EmitterBase { + constructor(wire: Transport); + /** + * Registers a global hotkey with the operating system. + * @return {Promise.} + * @tutorial GlobalHotkey.register + */ + register(hotkey: string, listener: (...args: any[]) => void): Promise; + /** + * Unregisters a global hotkey with the operating system. + * @return {Promise.} + * @tutorial GlobalHotkey.unregister + */ + unregister(hotkey: string): Promise; + /** + * Unregisters all global hotkeys for the current application. + * @return {Promise.} + * @tutorial GlobalHotkey.unregisterAll + */ + unregisterAll(): Promise; + /** + * Checks if a given hotkey has been registered + * @return {Promise.} + * @tutorial GlobalHotkey.isRegistered + */ + isRegistered(hotkey: string): Promise; +} diff --git a/types/openfin/v34/_v2/api/interappbus/channel/channel.d.ts b/types/openfin/v34/_v2/api/interappbus/channel/channel.d.ts new file mode 100644 index 0000000000..1c9a502e12 --- /dev/null +++ b/types/openfin/v34/_v2/api/interappbus/channel/channel.d.ts @@ -0,0 +1,31 @@ +import { Identity } from '../../../identity'; +import Transport, { Message } from '../../../transport/transport'; +export interface ProviderIdentity extends Identity { + channelId: string; + isExternal?: boolean; + channelName: string; +} +export declare type Action = (() => any) | ((payload: any) => any) | ((payload: any, id: ProviderIdentity) => any); +export declare type Middleware = (() => any) | ((action: string) => any) | ((action: string, payload: any) => any) | ((action: string, payload: any, id: ProviderIdentity) => any); +export interface ChannelMessagePayload extends Identity { + action: string; + payload: any; +} +export declare class ChannelBase { + protected subscriptions: any; + defaultAction: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any; + private preAction; + private postAction; + private errorMiddleware; + private defaultSet; + protected send: (to: Identity, action: string, payload: any) => Promise>; + protected providerIdentity: ProviderIdentity; + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + processAction(action: string, payload: any, senderIdentity: ProviderIdentity): Promise; + beforeAction(func: Action): void; + onError(func: (e: any, action: string, id: Identity) => any): void; + afterAction(func: Action): void; + remove(action: string): void; + setDefaultAction(func: (action?: string, payload?: any, senderIdentity?: ProviderIdentity) => any): void; + register(topic: string, listener: Action): boolean; +} diff --git a/types/openfin/v34/_v2/api/interappbus/channel/client.d.ts b/types/openfin/v34/_v2/api/interappbus/channel/client.d.ts new file mode 100644 index 0000000000..d1c128a349 --- /dev/null +++ b/types/openfin/v34/_v2/api/interappbus/channel/client.d.ts @@ -0,0 +1,6 @@ +import { ChannelBase, ProviderIdentity } from './channel'; +import Transport from '../../../transport/transport'; +export declare class ChannelClient extends ChannelBase { + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + dispatch(action: string, payload?: any): Promise; +} diff --git a/types/openfin/v34/_v2/api/interappbus/channel/index.d.ts b/types/openfin/v34/_v2/api/interappbus/channel/index.d.ts new file mode 100644 index 0000000000..1297d2c5ea --- /dev/null +++ b/types/openfin/v34/_v2/api/interappbus/channel/index.d.ts @@ -0,0 +1,33 @@ +import { ChannelClient } from './client'; +import { Identity } from '../../../identity'; +import { ChannelProvider } from './provider'; +import { EmitterBase } from '../../base'; +import Transport, { Message, Payload } from '../../../transport/transport'; +import { ProviderIdentity } from './channel'; +export interface Options { + wait?: boolean; + uuid: string; + name?: string; + payload?: any; +} +export interface ChannelPayload { + payload: Payload; +} +export interface ChannelMessage { + senderIdentity: Identity; + ackToSender: any; + providerIdentity: Identity; + connectAction: boolean; +} +export declare class Channel extends EmitterBase { + private channelMap; + constructor(wire: Transport); + getAllChannels(): Promise; + onChannelConnect(listener: Function): Promise; + onChannelDisconnect(listener: Function): Promise; + connect(options: Options): Promise; + create(channelName?: string): Promise; + onmessage: (msg: Message) => boolean; + private processChannelMessage; + private processChannelConnection; +} diff --git a/types/openfin/v34/_v2/api/interappbus/channel/provider.d.ts b/types/openfin/v34/_v2/api/interappbus/channel/provider.d.ts new file mode 100644 index 0000000000..a869928ac2 --- /dev/null +++ b/types/openfin/v34/_v2/api/interappbus/channel/provider.d.ts @@ -0,0 +1,13 @@ +import { ChannelBase, ProviderIdentity } from './channel'; +import Transport from '../../../transport/transport'; +export declare type ConnectionListener = (adapterIdentity: ProviderIdentity, connectionMessage?: any) => any; +export declare class ChannelProvider extends ChannelBase { + private connectListener; + private disconnectListener; + connections: ProviderIdentity[]; + constructor(providerIdentity: ProviderIdentity, send: Transport['sendAction']); + dispatch(to: ProviderIdentity, action: string, payload: any): Promise; + processConnection(senderId: ProviderIdentity, payload: any): Promise; + publish(action: string, payload: any): Promise[]; + onConnection(listener: ConnectionListener): void; +} diff --git a/types/openfin/v34/_v2/api/interappbus/interappbus.d.ts b/types/openfin/v34/_v2/api/interappbus/interappbus.d.ts new file mode 100644 index 0000000000..48aaf7430c --- /dev/null +++ b/types/openfin/v34/_v2/api/interappbus/interappbus.d.ts @@ -0,0 +1,80 @@ +/// +import { Base } from '../base'; +import { Identity } from '../../identity'; +import Transport, { Message } from '../../transport/transport'; +import { EventEmitter } from 'events'; +import { Channel } from './channel/index'; +/** + * A messaging bus that allows for pub/sub messaging between different applications. + * @namespace +*/ +export default class InterApplicationBus extends Base { + Channel: Channel; + events: { + subscriberAdded: string; + subscriberRemoved: string; + }; + private refCounter; + protected emitter: EventEmitter; + on: any; + removeAllListeners: any; + constructor(wire: Transport); + /** + * Publishes a message to all applications running on OpenFin Runtime that + * are subscribed to the specified topic. + * @param { string } topic The topic on which the message is sent + * @param { any } message The message to be published. Can be either a primitive + * data type (string, number, or boolean) or composite data type (object, array) + * that is composed of other primitive or composite data types + * @return {Promise.} + * @tutorial InterApplicationBus.publish + */ + publish(topic: string, message: any): Promise; + /** + * Sends a message to a specific application on a specific topic. + * @param { object } destination The uuid of the application to which the message is sent + * @param { string } topic The topic on which the message is sent + * @param { any } message The message to be sent. Can be either a primitive data + * type (string, number, or boolean) or composite data type (object, array) that + * is composed of other primitive or composite data types + * @return {Promise.} + * @tutorial InterApplicationBus.send + */ + send(destination: Identity, topic: string, message: any): Promise; + /** + * Subscribes to messages from the specified application on the specified topic. + * If the subscription is for a uuid, [name], topic combination that has already + * been published to upon subscription you will receive the last 20 missed messages + * in the order they were published. + * @param { Identity } source This object is described in the Identity in the typedef + * @param { string } topic The topic on which the message is sent + * @param { function } listener A function that is called when a message has + * been received. It is passed the message, uuid and name of the sending application. + * The message can be either a primitive data type (string, number, or boolean) or + * composite data type (object, array) that is composed of other primitive or composite + * data types + * @return {Promise.} + * @tutorial InterApplicationBus.subcribe + */ + subscribe(source: Identity, topic: string, listener: any): Promise; + /** + * Unsubscribes to messages from the specified application on the specified topic. + * @param { Identity } source This object is described in the Identity in the typedef + * @param { string } topic The topic on which the message is sent + * @param { function } listener A callback previously registered with subscribe() + * @return {Promise.} + * @tutorial InterApplicationBus.unsubscribe + */ + unsubscribe(source: Identity, topic: string, listener: any): Promise; + private processMessage; + private emitSubscriverEvent; + protected createSubscriptionKey(uuid: string, name: string, topic: string): string; + protected onmessage(message: Message): boolean; +} +export declare class InterAppPayload { + sourceUuid: string; + sourceWindowName: string; + topic: string; + destinationUuid?: string; + message?: any; +} diff --git a/types/openfin/v34/_v2/api/notification/notification.d.ts b/types/openfin/v34/_v2/api/notification/notification.d.ts new file mode 100644 index 0000000000..8deec180ba --- /dev/null +++ b/types/openfin/v34/_v2/api/notification/notification.d.ts @@ -0,0 +1,71 @@ +import { Base, EmitterBase } from '../base'; +import { Identity } from '../../identity'; +import Transport from '../../transport/transport'; +export declare class NotificationOptions { + url: string; + message: string; + timeout: string | number; + notificationId: number; + uuidOfProxiedApp: string; + ignoreMouseOver: boolean; + constructor(options: any, identity: Identity, notificationId: number); +} +export interface NotificationCallback { + message?: any; +} +/** + * @classdesc A Notification object represents a window on OpenFin Runtime which + * is shown briefly to the user on the bottom-right corner of the primary monitor. + * A notification is typically used to alert the user of some important event which + * requires his or her attention. Notifications are a child or your application that + * are controlled by the runtime. + * @class + * @alias Notification + */ +export declare class _Notification extends EmitterBase { + private listenerList; + private unhookAllListeners; + private buildLocalPayload; + protected options: NotificationOptions; + protected generalListener: (msg: any) => void; + protected notificationId: number; + protected onmessage: (message: any) => boolean; + constructor(wire: Transport, options: NotificationOptions); + url: string; + timeout: number | string; + message: any; + /** + * Invoked when the notification is shown + * @return {Promise.} + * @tutorial Notification.show + */ + show(): Promise; + /** + * Sends a message to the notification. + * @param { any } message The message to be sent to the notification. + * Can be either a primitive data type (string, number, or boolean) + * or composite data type (object, array) that is composed of other + * primitive or composite data types + * @return {Promise.} + * @tutorial Notification.sendMessage + */ + sendMessage(message: any): Promise; + /** + * Closes the notification + * @return {Promise.} + * @tutorial Notification.close + */ + close(): Promise; +} +export default class _NotificationModule extends Base { + private nextNoteId; + private genNoteId; + events: { + show: string; + close: string; + error: string; + click: string; + message: string; + }; + create(options: any): _Notification; +} diff --git a/types/openfin/v34/_v2/api/system/application.d.ts b/types/openfin/v34/_v2/api/system/application.d.ts new file mode 100644 index 0000000000..9d7ea09b67 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/application.d.ts @@ -0,0 +1,4 @@ +export interface ApplicationInfo { + isRunning: boolean; + uuid: string; +} diff --git a/types/openfin/v34/_v2/api/system/clearCacheOption.d.ts b/types/openfin/v34/_v2/api/system/clearCacheOption.d.ts new file mode 100644 index 0000000000..6bae8116b7 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/clearCacheOption.d.ts @@ -0,0 +1,6 @@ +export interface ClearCacheOption { + appcache?: boolean; + cache?: boolean; + cookies?: boolean; + localStorage?: boolean; +} diff --git a/types/openfin/v34/_v2/api/system/cookie.d.ts b/types/openfin/v34/_v2/api/system/cookie.d.ts new file mode 100644 index 0000000000..1d229232c6 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/cookie.d.ts @@ -0,0 +1,8 @@ +export interface CookieInfo { + name: string; + domain: string; + path: string; +} +export interface CookieOption { + name: string; +} diff --git a/types/openfin/v34/_v2/api/system/crashReporterOption.d.ts b/types/openfin/v34/_v2/api/system/crashReporterOption.d.ts new file mode 100644 index 0000000000..7d512fdd7b --- /dev/null +++ b/types/openfin/v34/_v2/api/system/crashReporterOption.d.ts @@ -0,0 +1,4 @@ +export interface CrashReporterOption { + diagnosticMode: boolean; + isRunning?: boolean; +} diff --git a/types/openfin/v34/_v2/api/system/download-asset.d.ts b/types/openfin/v34/_v2/api/system/download-asset.d.ts new file mode 100644 index 0000000000..be513f5f0e --- /dev/null +++ b/types/openfin/v34/_v2/api/system/download-asset.d.ts @@ -0,0 +1,18 @@ +export interface AppAssetInfo { + src: string; + alias: string; + version: string; + target?: string; + args?: string; + mandatory?: boolean; +} +export interface RuntimeDownloadOptions { + version: string; +} +export interface AppAssetRequest { + alias: string; +} +export interface RuntimeDownloadProgress { + downloadedBytes: number; + totalBytes: number; +} diff --git a/types/openfin/v34/_v2/api/system/download-preload.d.ts b/types/openfin/v34/_v2/api/system/download-preload.d.ts new file mode 100644 index 0000000000..a7e635bcb8 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/download-preload.d.ts @@ -0,0 +1,8 @@ +export interface DownloadPreloadOption { + url: string; +} +export interface DownloadPreloadInfo { + success: boolean; + url?: string; + error: string; +} diff --git a/types/openfin/v34/_v2/api/system/entity.d.ts b/types/openfin/v34/_v2/api/system/entity.d.ts new file mode 100644 index 0000000000..50011a64f3 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/entity.d.ts @@ -0,0 +1,11 @@ +import { Identity } from '../../identity'; +export interface Entity { + type: string; + uuid: string; +} +export interface EntityInfo { + name: string; + uuid: string; + parent: Identity; + entityType: string; +} diff --git a/types/openfin/v34/_v2/api/system/external-process.d.ts b/types/openfin/v34/_v2/api/system/external-process.d.ts new file mode 100644 index 0000000000..8a68f1eae3 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/external-process.d.ts @@ -0,0 +1,22 @@ +export interface ExternalProcessRequestType { + path: string; + arguments: string; + listener: LaunchExternalProcessListener; +} +export interface ExitCode { + topic: string; + uuid: string; + exitCode: number; +} +export interface LaunchExternalProcessListener { + (code: ExitCode): void; +} +export interface TerminateExternalRequestType { + uuid: string; + timeout: number; + killTree: boolean; +} +export interface ExternalConnection { + token: string; + uuid: string; +} diff --git a/types/openfin/v34/_v2/api/system/host-specs.d.ts b/types/openfin/v34/_v2/api/system/host-specs.d.ts new file mode 100644 index 0000000000..2c5a134aea --- /dev/null +++ b/types/openfin/v34/_v2/api/system/host-specs.d.ts @@ -0,0 +1,22 @@ +export interface Time { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; +} +export interface CpuInfo { + model: string; + speed: number; + times: Time; +} +export interface GpuInfo { + name: string; +} +export interface HostSpecs { + cpu: CpuInfo[]; + memory: number; + arch: string; + name: string; + gpu: GpuInfo; +} diff --git a/types/openfin/v34/_v2/api/system/log.d.ts b/types/openfin/v34/_v2/api/system/log.d.ts new file mode 100644 index 0000000000..9b03b28c57 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/log.d.ts @@ -0,0 +1,11 @@ +export interface GetLogRequestType { + name: string; + endFile?: string; + sizeLimit?: number; +} +export interface LogInfo { + name: string; + size: number; + date: string; +} +export declare type LogLevel = 'verbose' | 'info' | 'warning' | 'error' | 'fatal'; diff --git a/types/openfin/v34/_v2/api/system/monitor.d.ts b/types/openfin/v34/_v2/api/system/monitor.d.ts new file mode 100644 index 0000000000..ea4aed799c --- /dev/null +++ b/types/openfin/v34/_v2/api/system/monitor.d.ts @@ -0,0 +1,39 @@ +import { Point } from './point'; +export interface MonitorInfo { + deviceScaleFactor: number; + dpi: Point; + nonPrimaryMonitors: Array; + primaryMonitor: MonitorDetails; + reason: string; + taskBar: TaskBar; + virtualScreen: DipRect; +} +export interface MonitorDetails { + available: DipScaleRects; + availableRect: Rect; + deviceId: string; + displayDeviceActive: boolean; + deviceScaleFactor: number; + monitorRect: Rect; + name: number; + dpi: Point; + monitor: DipScaleRects; +} +export interface Rect { + bottom: number; + left: number; + right: number; + top: number; +} +export interface DipRect extends Rect { + dipRect: Rect; + scaledRect: Rect; +} +export interface DipScaleRects { + dipRect: Rect; + scaledRect: Rect; +} +export interface TaskBar extends DipScaleRects { + edge: string; + rect: Rect; +} diff --git a/types/openfin/v34/_v2/api/system/point.d.ts b/types/openfin/v34/_v2/api/system/point.d.ts new file mode 100644 index 0000000000..b9830ce514 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/point.d.ts @@ -0,0 +1,8 @@ +export interface Point { + x: number; + y: number; +} +export interface PointTopLeft { + top: number; + left: number; +} diff --git a/types/openfin/v34/_v2/api/system/process.d.ts b/types/openfin/v34/_v2/api/system/process.d.ts new file mode 100644 index 0000000000..8a513ceecd --- /dev/null +++ b/types/openfin/v34/_v2/api/system/process.d.ts @@ -0,0 +1,15 @@ +export interface ProcessInfo { + cpuUsage: number; + name: string; + nonPagedPoolUsage: number; + pageFaultCount: number; + pagedPoolUsage: number; + pagefileUsage: number; + peakNonPagedPoolUsage: number; + peakPagedPoolUsage: number; + peakPagefileUsage: number; + peakWorkingSetSize: number; + processId: number; + uuid: string; + workingSetSize: number; +} diff --git a/types/openfin/v34/_v2/api/system/proxy.d.ts b/types/openfin/v34/_v2/api/system/proxy.d.ts new file mode 100644 index 0000000000..597afa6548 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/proxy.d.ts @@ -0,0 +1,14 @@ +export interface ProxyInfo { + config: ProxyConfig; + system: { + autoConfigUrl: string; + bypass: ''; + enabled: boolean; + proxy: string; + }; +} +export interface ProxyConfig { + proxyAddress: string; + proxyPort: number; + type: string; +} diff --git a/types/openfin/v34/_v2/api/system/registry-info.d.ts b/types/openfin/v34/_v2/api/system/registry-info.d.ts new file mode 100644 index 0000000000..a48ed34959 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/registry-info.d.ts @@ -0,0 +1,7 @@ +export interface RegistryInfo { + data: any; + rootKey: string; + subkey: string; + type: string; + value: string; +} diff --git a/types/openfin/v34/_v2/api/system/runtime-info.d.ts b/types/openfin/v34/_v2/api/system/runtime-info.d.ts new file mode 100644 index 0000000000..1508f87ef3 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/runtime-info.d.ts @@ -0,0 +1,7 @@ +export interface RuntimeInfo { + architecture: string; + manifestUrl: string; + port: number; + securityRealm?: string; + version: string; +} diff --git a/types/openfin/v34/_v2/api/system/rvm.d.ts b/types/openfin/v34/_v2/api/system/rvm.d.ts new file mode 100644 index 0000000000..42fc0b94db --- /dev/null +++ b/types/openfin/v34/_v2/api/system/rvm.d.ts @@ -0,0 +1,5 @@ +export interface RVMInfo { + action: string; + 'start-time': string; + version: string; +} diff --git a/types/openfin/v34/_v2/api/system/system.d.ts b/types/openfin/v34/_v2/api/system/system.d.ts new file mode 100644 index 0000000000..8c0bc7d3b6 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/system.d.ts @@ -0,0 +1,475 @@ +import { EmitterBase } from '../base'; +import { ApplicationInfo } from './application'; +import { WindowInfo } from './window'; +import { Identity } from '../../identity'; +import { MonitorInfo } from './monitor'; +import { PointTopLeft } from './point'; +import { GetLogRequestType, LogInfo, LogLevel } from './log'; +import { ProxyInfo, ProxyConfig } from './proxy'; +import { ProcessInfo } from './process'; +import { AppAssetInfo, AppAssetRequest, RuntimeDownloadOptions, RuntimeDownloadProgress } from './download-asset'; +import { RVMInfo } from './rvm'; +import { RuntimeInfo } from './runtime-info'; +import { Entity, EntityInfo } from './entity'; +import { HostSpecs } from './host-specs'; +import { ExternalProcessRequestType, TerminateExternalRequestType, ExternalConnection } from './external-process'; +import Transport from '../../transport/transport'; +import { CookieInfo, CookieOption } from './cookie'; +import { RegistryInfo } from './registry-info'; +import { DownloadPreloadOption, DownloadPreloadInfo } from './download-preload'; +import { ClearCacheOption } from './clearCacheOption'; +import { CrashReporterOption } from './crashReporterOption'; +/** + * AppAssetInfo interface + * @typedef { Object } AppAssetInfo + * @property { string } src The URL to a zip file containing the package files (executables, dlls, etc…) + * @property { string } alias The name of the asset + * @property { string } version The version of the package + * @property { string } target Specify default executable to launch. This option can be overridden in launchExternalProcess + * @property { args } args The default command line arguments for the aforementioned target. + * @property { boolean } mandatory When set to true, the app will fail to load if the asset cannot be downloaded. + * When set to false, the app will continue to load if the asset cannot be downloaded. (Default: true) + */ +/** + * AppAssetRequest interface + * @typedef { Object } AppAssetRequest + * @property { string } alias The name of the asset + */ +/** + * CookieInfo interface + * @typedef { Object } CookieInfo + * @property { string } name The name of the cookie + * @property { string } domain The domain of the cookie + * @property { string } path The path of the cookie + */ +/** + * CookieOption interface + * @typedef { Object } CookieOption + * @property { string } name The name of the cookie + */ +/** + * ExternalConnection interface + * @typedef { Object } ExternalConnection + * @property { string } token The token to broker an external connection + * @property { string } uuid The uuid of the external connection + */ +/** +* ExternalProcessRequestType interface +* @typedef { Object } ExternalProcessRequestType +* @property { string } path The file path to where the running application resides +* @property { string } arguments The argument passed to the running application +* @property { Object } listener This is described in the {LaunchExternalProcessListner} type definition +*/ +/** + * Entity interface + * @typedef { Object } Entity + * @property { string } type The type of the entity + * @property { string } uuid The uuid of the entity + */ +/** + * EntityInfo interface + * @typedef { Object } EntityInfo + * @property { string } name The name of the entity + * @property { string } uuid The uuid of the entity + * @property { Identity } parent The parent of the entity + * @property { string } entityType The type of the entity + */ +/** +* GetLogRequestType interface +* @typedef { Object } GetLogRequestType +* @property { string } name The name of the running application +* @property { number } endFile The file length of the log file +* @property { number } sizeLimit The set size limit of the log file +*/ +/** + * Identity interface + * @typedef { Object } Identity + * @property { string } name The name of the application + * @property { string } uuid The uuid of the application + */ +/** + * @typedef { verbose | info | warning | error | fatal } LogLevel + * @summary Log verbosity levels. + * @desc Describes the minimum level (inclusive) above which logs will be written + * + * @property { string } verbose all logs written + * @property { string } info info and above + * @property { string } warning warning and above + * @property { string } error error and above + * @property { string } fatal fatal only, indicates a crash is imminent + */ +/** + * ProxyConfig interface + * @typedef { Object } ProxyConfig + * @property { numder } proxyPort The port number of the running application + * @property { string } proxyAddress The address of the running application + * @property { string } type + */ +/** + * RegistryInfo interface + * @typedef { Object } RegistryInfo + * @property { any } data The registry data + * @property { string } rootKey The registry root key + * @property { string } subkey The registry key + * @property { string } type The registry type + * @property { string } value The registry value name + */ +/** + * RuntimeDownloadOptions interface + * @typedef { Object } RuntimeDownloadOptions + * @desc These are the options object required by the downloadRuntime function. + * @property { string } version The given version to download + */ +/** + * TerminateExternalRequestType interface + * @typedef { Object } TerminateExternalRequestType + * @property { string } uuid The uuid of the running application + * @property { number } timeout Time out period before the running application terminates + * @property { boolean } killtree Value to terminate the running application + */ +/** + * DownloadPreloadOption interface + * @typedef { Object } DownloadPreloadOption + * @desc These are the options object required by the downloadPreloadScripts function + * @property { string } url url to the preload script + */ +/** + * DownloadPreloadInfo interface + * @typedef { Object } DownloadPreloadInfo + * @desc downloadPreloadScripts function return value + * @property { string } url url to the preload script + * @property { string } error error during preload script acquisition + * @property { boolean } succeess download operation success + */ +/** + * @typedef { Object } ClearCacheOption + * @summary Clear cache options. + * @desc These are the options required by the clearCache function. + * + * @property {boolean} appcache html5 application cache + * @property {boolean} cache browser data cache for html files and images + * @property {boolean} cookies browser cookies + * @property {boolean} localStorage browser data that can be used across sessions + */ +/** +* CrashReporterOption interface +* @typedef { Object } CrashReporterOption +* @property { boolean } diagnosticMode In diagnostic mode the crash reporter will send diagnostic logs to +* the OpenFin reporting service on runtime shutdown +* @property { boolean } isRunning check if it's running +*/ +/** + * An object representing the core of OpenFin Runtime. Allows the developer + * to perform system-level actions, such as accessing logs, viewing processes, + * clearing the cache and exiting the runtime. + * @namespace + */ +export default class System extends EmitterBase { + constructor(wire: Transport); + /** + * Returns the version of the runtime. The version contains the major, minor, + * build and revision numbers. + * @return {Promise.} + * @tutorial System.getVersion + */ + getVersion(): Promise; + /** + * Clears cached data containing application resource + * files (images, HTML, JavaScript files), cookies, and items stored in the + * Local Storage. + * @param { ClearCacheOption } options - See tutorial for more details. + * @return {Promise.} + * @tutorial System.clearCache + */ + clearCache(options: ClearCacheOption): Promise; + /** + * Clears all cached data when OpenFin Runtime exits. + * @return {Promise.} + * @tutorial System.deleteCacheOnExit + */ + deleteCacheOnExit(): Promise; + /** + * Exits the Runtime. + * @return {Promise.} + * @tutorial System.exit + */ + exit(): Promise; + /** + * Writes any unwritten cookies data to disk. + * @return {Promise.} + * @tutorial System.flushCookieStore + */ + flushCookieStore(): Promise; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + * @return {Promise.Array.} + * @tutorial System.getAllWindows + */ + getAllWindows(): Promise>; + /** + * Retrieves an array of data for all applications. + * @return {Promise.Array.} + * @tutorial System.getAllApplications + */ + getAllApplications(): Promise>; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + * @return {Promise.} + * @tutorial System.getCommandLineArguments + */ + getCommandLineArguments(): Promise; + /** + * Get the current state of the crash reporter. + * @return {Promise.} + * @tutorial System.getCrashReporterState + */ + getCrashReporterState(): Promise; + /** + * Returns a unique identifier (UUID) for the machine (SHA256 hash of the system's MAC address). + * This call will return the same value on subsequent calls on the same machine(host). + * The values will be different on different machines, and should be considered globally unique. + * @return {Promise.} + * @tutorial System.getDeviceId + */ + getDeviceId(): Promise; + /** + * Start the crash reporter for the browser process if not already running. + * You can optionally specify `diagnosticMode` to have the logs sent to + * OpenFin on runtime close + * + * @param { CrashReporterOption } options - configure crash reporter + * @return {Promise.} + * @tutorial System.startCrashReporter + */ + startCrashReporter(options: CrashReporterOption): Promise; + /** + * Returns a hex encoded hash of the mac address and the currently logged in user name + * @return {Promise.} + * @tutorial System.getDeviceUserId + */ + getDeviceUserId(): Promise; + /** + * Retrieves a frame info object for the uuid and name passed in + * @param { string } uuid - The UUID of the target. + * @param { string } name - The name of the target. + * @return {Promise.} + * @tutorial System.getEntityInfo + */ + getEntityInfo(uuid: string, name: string): Promise; + /** + * Gets the value of a given environment variable on the computer on which the runtime is installed + * @return {Promise.} + * @tutorial System.getEnvironmentVariable + */ + getEnvironmentVariable(envName: string): Promise; + /** + * Get current focused window. + * @return {Promise.} + * @tutorial System.getFocusedWindow + */ + getFocusedWindow(): Promise; + /** + * Retrieves the contents of the log with the specified filename. + * @param { GetLogRequestType } options A object that id defined by the GetLogRequestType interface + * @return {Promise.} + * @tutorial System.getLog + */ + getLog(options: GetLogRequestType): Promise; + /** + * Returns the minimum (inclusive) logging level that is currently being written to the log. + * @return {Promise.} + * @tutorial System.getMinLogLevel + */ + getMinLogLevel(): Promise; + /** + * Retrieves an array containing information for each log file. + * @return {Promise.Array} + * @tutorial System.getLogList + */ + getLogList(): Promise>; + /** + * Retrieves an object that contains data about the monitor setup of the + * computer that the runtime is running on. + * @return {Promise.} + * @tutorial System.getMonitorInfo + */ + getMonitorInfo(): Promise; + /** + * Returns the mouse in virtual screen coordinates (left, top). + * @return {Promise.} + * @tutorial System.getMousePosition + */ + getMousePosition(): Promise; + /** + * Retrieves an array of all of the runtime processes that are currently + * running. Each element in the array is an object containing the uuid + * and the name of the application to which the process belongs. + * @return {Promise.Array.} + * @tutorial System.getProcessList + */ + getProcessList(): Promise>; + /** + * Retrieves the Proxy settings. + * @return {Promise.} + * @tutorial System.getProxySettings + */ + getProxySettings(): Promise; + /** + * Returns information about the running Runtime in an object. + * @return {Promise.} + * @tutorial System.getRuntimeInfo + */ + getRuntimeInfo(): Promise; + /** + * Returns information about the running RVM in an object. + * @return {Promise.} + * @tutorial System.getRvmInfo + */ + getRvmInfo(): Promise; + /** + * Retrieves system information. + * @return {Promise.} + * @tutorial System.getHostSpecs + */ + getHostSpecs(): Promise; + /** + * Runs an executable or batch file. + * @param { ExternalProcessRequestType } options A object that is defined in the ExternalProcessRequestType interface + * @return {Promise.} + * @tutorial System.launchExternalProcess + */ + launchExternalProcess(options: ExternalProcessRequestType): Promise; + /** + * Monitors a running process. + * @param { number } pid See tutorial for more details + * @return {Promise.} + * @tutorial System.monitorExternalProcess + */ + monitorExternalProcess(pid: number): Promise; + /** + * Writes the passed message into both the log file and the console. + * @param { string } level The log level for the entry. Can be either "info", "warning" or "error" + * @param { string } message The log message text + * @return {Promise.} + * @tutorial System.log + */ + log(level: string, message: string): Promise; + /** + * Opens the passed URL in the default web browser. + * @param { string } url The URL to open + * @return {Promise.} + * @tutorial System.openUrlWithBrowser + */ + openUrlWithBrowser(url: string): Promise; + /** + * Removes the process entry for the passed UUID obtained from a prior call + * of fin.System.launchExternalProcess(). + * @param { string } uuid The UUID for a process obtained from a prior call to fin.desktop.System.launchExternalProcess() + * @return {Promise.} + * @tutorial System.releaseExternalProcess + */ + releaseExternalProcess(uuid: string): Promise; + /** + * Shows the Chromium Developer Tools for the specified window + * @param { Identity } identity This is a object that is defined by the Identity interface + * @return {Promise.} + * @tutorial System.showDeveloperTools + */ + showDeveloperTools(identity: Identity): Promise; + /** + * Attempt to close an external process. The process will be terminated if it + * has not closed after the elapsed timeout in milliseconds. + * @param { TerminateExternalRequestType } options A object defined in the TerminateExternalRequestType interface + * @return {Promise.} + * @tutorial System.terminateExternalProcess + */ + terminateExternalProcess(options: TerminateExternalRequestType): Promise; + /** + * Update the OpenFin Runtime Proxy settings. + * @param { ProxyConfig } options A config object defined in the ProxyConfig interface + * @return {Promise.} + * @tutorial System.updateProxySettings + */ + updateProxySettings(options: ProxyConfig): Promise; + /** + * Downloads the given application asset + * @param { AppAssetInfo } appAsset App asset object + * @return {Promise.} + * @tutorial System.downloadAsset + */ + downloadAsset(appAsset: AppAssetInfo, progressListener: (progress: RuntimeDownloadProgress) => void): Promise; + /** + * Downloads a version of the runtime. + * @param { RuntimeDownloadOptions } options - Download options. + * @param {Function} [progressListener] - called as the runtime is downloaded with progress information. + * @return {Promise.} + * @tutorial System.downloadRuntime + */ + downloadRuntime(options: RuntimeDownloadOptions, progressListener: (progress: RuntimeDownloadProgress) => void): Promise; + /** + * Download preload scripts from given URLs + * @param {DownloadPreloadOption[]} scripts - URLs of preload scripts. See tutorial for more details. + * @return {Promise.Array} + * @tutorial System.downloadPreloadScripts + */ + downloadPreloadScripts(scripts: Array): Promise>; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + * @return {Promise.Array.} + * @tutorial System.getAllExternalApplications + */ + getAllExternalApplications(): Promise>; + /** + * Retrieves app asset information. + * @param { AppAssetRequest } options + * @return {Promise.} + * @tutorial System.getAppAssetInfo + */ + getAppAssetInfo(options: AppAssetRequest): Promise; + /** + * Get additional info of cookies. + * @param { CookieOption } options - See tutorial for more details. + * @return {Promise.Array.} + * @tutorial System.getCookies + */ + getCookies(options: CookieOption): Promise>; + /** + * Set the minimum log level above which logs will be written to the OpenFin log + * @param { LogLevel } The minimum level (inclusive) above which all calls to log will be written + * @return {Promise.} + * @tutorial System.setMinLogLevel + */ + setMinLogLevel(level: LogLevel): Promise; + /** + * Retrieves the UUID of the computer on which the runtime is installed + * @param { string } uuid The uuid of the running application + * @return {Promise.} + * @tutorial System.resolveUuid + */ + resolveUuid(uuid: string): Promise; + /** + * Retrieves an array of data for all external applications + * @param { Identity } requestingIdentity This object is described in the Identity typedef + * @param { any } data Any data type to pass to the method + * @return {Promise.} + * @ignore + */ + executeOnRemote(requestingIdentity: Identity, data: any): Promise; + /** + * Reads the specifed value from the registry. + * @param { string } rootKey - The registry root key. + * @param { string } subkey - The registry key. + * @param { string } value - The registry value name. + * @return {Promise.} + * @tutorial System.readRegistryValue + */ + readRegistryValue(rootKey: string, subkey: string, value: string): Promise; + /** + * This function call will register a unique id and produce a token. + * The token can be used to broker an external connection. + * @param { string } uuid - A UUID for the remote connection. + * @return {Promise.} + * @tutorial System.registerExternalConnection + */ + registerExternalConnection(uuid: string): Promise; +} diff --git a/types/openfin/v34/_v2/api/system/window.d.ts b/types/openfin/v34/_v2/api/system/window.d.ts new file mode 100644 index 0000000000..886084fad6 --- /dev/null +++ b/types/openfin/v34/_v2/api/system/window.d.ts @@ -0,0 +1,14 @@ +export interface WindowInfo { + uuid: string; + mainWindow: WindowDetail; + childWindows: Array; +} +export interface WindowDetail { + name: string; + top: number; + right: number; + bottom: number; + height: number; + width: number; + left: number; +} diff --git a/types/openfin/v34/_v2/api/window/bounds-changed.d.ts b/types/openfin/v34/_v2/api/window/bounds-changed.d.ts new file mode 100644 index 0000000000..f7801da3fc --- /dev/null +++ b/types/openfin/v34/_v2/api/window/bounds-changed.d.ts @@ -0,0 +1,14 @@ +import { Reply } from '../base'; +export default class BoundsChangedReply extends Reply<'window', 'bounds-changed'> { + changeType: BoundsChangeType; + deferred: boolean; + height: number; + width: number; + top: number; + left: number; +} +export declare const enum BoundsChangeType { + POSITION = 0, + SIZE = 1, + POSITION_AND_SIZE = 2 +} diff --git a/types/openfin/v34/_v2/api/window/bounds.d.ts b/types/openfin/v34/_v2/api/window/bounds.d.ts new file mode 100644 index 0000000000..40822c4aa3 --- /dev/null +++ b/types/openfin/v34/_v2/api/window/bounds.d.ts @@ -0,0 +1,9 @@ +interface Bounds { + height: number; + width: number; + top: number; + left: number; + right?: number; + bottom?: number; +} +export default Bounds; diff --git a/types/openfin/v34/_v2/api/window/transition.d.ts b/types/openfin/v34/_v2/api/window/transition.d.ts new file mode 100644 index 0000000000..c16440c80d --- /dev/null +++ b/types/openfin/v34/_v2/api/window/transition.d.ts @@ -0,0 +1,24 @@ +export interface TransitionBase { + duration: number; + relative?: boolean; +} +export interface Opacity extends TransitionBase { + opacity: number; +} +export interface Position extends TransitionBase { + left: number; + top: number; +} +export interface Size extends TransitionBase { + width: number; + height: number; +} +export interface TransitionOptions { + interrupt: boolean; + tween?: string; +} +export interface Transition { + opacity?: Opacity; + position?: Position; + size?: Size; +} diff --git a/types/openfin/v34/_v2/api/window/window.d.ts b/types/openfin/v34/_v2/api/window/window.d.ts new file mode 100644 index 0000000000..8d597a6446 --- /dev/null +++ b/types/openfin/v34/_v2/api/window/window.d.ts @@ -0,0 +1,759 @@ +import { Base, EmitterBase, RuntimeEvent } from '../base'; +import { Identity } from '../../identity'; +import Bounds from './bounds'; +import BoundsChangedReply from './bounds-changed'; +import { Transition, TransitionOptions } from './transition'; +import { Application } from '../application/application'; +import Transport from '../../transport/transport'; +export default class _WindowModule extends Base { + private instance; + /** + * Returns a Window object that represents an existing window. + * @param { Identity } indentity + * @return {Promise.<_Window>} + * @tutorial Window.wrap + */ + wrap(identity: Identity): Promise<_Window>; + /** + * Creates a new Window. + * @param { * } options - Window creation options + * @return {Promise.<_Window>} + * @tutorial Window.create + */ + create(options: any): Promise<_Window>; + /** + * Returns a Window object that represents the current window + * @return {Promise.} + * @tutorial window.getCurrent + */ + getCurrent(): Promise<_Window>; +} +export interface CloseEventShape { + name: string; + uuid: string; + type: string; + topic: string; +} +export interface WindowInfo { + canNavigateBack: boolean; + canNavigateForward: boolean; + preloadScripts: Array; + title: string; + url: string; +} +export interface FrameInfo { + name: string; + uuid: string; + entityType: string; + parent?: Identity; +} +/** + * @typedef {object} Transition + * @property {Opacity} opacity - The Opacity transition + * @property {Position} position - The Position transition + * @property {Size} size - The Size transition +*/ +/** + * @typedef {object} TransitionOptions + * @property {boolean} interrupt - This option interrupts the current animation. When false it pushes +this animation onto the end of the animation queue. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + */ +/** + * @typedef {object} Size + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} width - Optional if height is present. Defaults to the window's current width. + * @property {number} height - Optional if width is present. Defaults to the window's current height. + */ +/** + * @typedef {object} Position + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} left - Defaults to the window's current left position in virtual screen coordinates. + * @property {number} top - Defaults to the window's current top position in virtual screen coordinates. + */ +/** + * @typedef {object} Opacity + * @property {number} duration - The total time in milliseconds this transition should take. + * @property {boolean} relative - Treat 'opacity' as absolute or as a delta. Defaults to false. + * @property {number} opacity - This value is clamped from 0.0 to 1.0. +*/ +/** + * Bounds is a interface that has the properties of height, + * width, left, top which are all numbers + * @typedef { Object } Bounds + * @property { number } height Get the application height bound + * @property { number } width Get the application width bound + * @property { number } top Get the application top bound + * @property { number } left Get the application left bound + * @property { number } right Get the application right bound + * @property { number } bottom Get the application bottom bound + */ +/** + * @classdesc A basic window that wraps a native HTML window. Provides more fine-grained + * control over the window state such as the ability to minimize, maximize, restore, etc. + * By default a window does not show upon instantiation; instead the window's show() method + * must be invoked manually. The new window appears in the same process as the parent window. + * @class + * @alias Window +*/ +export declare class _Window extends EmitterBase { + identity: Identity; + /** + * Raised when a window within this application requires credentials from the user. + * + * @event Window#auth-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {object} authInfo + * @property {string} authInfo.host - Host server. + * @property {boolean} authInfo.isProxy - Indicates if the request involves a proxy. + * @property {number} authInfo.port - Port number. + * @property {string} authInfo.realm - Authentication request realm. + * @property {string} authInfo.scheme - Authentication scheme. + */ + /** + * Raised when a window loses focus. + * + * @event Window#blurred + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised after changes in a window's size and/or position. + * + * @event Window#bounds-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when a window has been prevented from closing. A window will be prevented from closing by default, + either through the API or by a user when ‘close-requested’ has been subscribed to and the Window.close(force) flag is false. + * + * @event Window#close-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has closed. + * + * @event Window#closed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has crashed. + * + * @event Window#crashed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when the frame is disabled after all prevent user changes in window's size and/or position have completed. + * + * @event Window#disabled-frame-bounds-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when the frame is disabled during prevented user changes to a window's size and/or position. + * + * @event Window#disabled-frame-bounds-changing + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} changeType - Describes what kind of change occurred. + 0 means a change in position. + 1 means a change in size. + 2 means a change in position and size. + * @property {string} deferred - Indicated whether pending changes have been applied. + * @property {number} height - New height of the window. + * @property {number} left - New left most coordinate of the window. + * @property {number} top - New top most coordinate of the window. + * @property {number} width - New width of the window. + */ + /** + * Raised when the window has been embedded. + * + * @event Window#embedded + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when an external process has exited. + * + * @event Window#external-process-exited + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} processUuid - The process handle UUID. + * @property {number} exitCode - The process exit code + */ + /** + * Raised when an external process has started. + * + * @event Window#external-process-started + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} processUuid - The process handle UUID. + */ + /** + * Raised when a window's frame becomes disabled. + * + * @event Window#frame-disabled + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window's frame becomes enabled. + * + * @event Window#frame-enabled + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window joins/leaves a group and/or when the group a window is a member of changes. + * + * @event Window#group-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} source - Which group array the window that the event listener was registered on is included in: + 'source' The window is included in sourceGroup. + 'target' The window is included in targetGroup. + 'nothing' The window is not included in sourceGroup nor targetGroup. + * @property {string} reason - The reason this event was triggered. + 'leave' A window has left the group due to a leave or merge with group. + 'join' A window has joined the group. + 'merge' Two groups have been merged together. + 'disband' There are no other windows in the group. + * @property {string} name - Name of the window. + * @property {legacyWindowIdentity[]} sourceGroup - All the windows in the group the sourceWindow originated from. + * @property {string} sourceWindowAppUuid - UUID of the application the sourceWindow belongs to the + source window is the window in which (merge/join/leave)group(s) was called. + * @property {string} sourceWindowName - Name of the sourcewindow. + The source window is the window in which (merge/join/leave)group(s) was called. + * @property {legacyWindowIdentity[]} targetGroup - All the windows in the group the targetWindow orginated from. + * @property {string} targetWindowAppUuid - UUID of the application the targetWindow belongs to. + The target window is the window that was passed into (merge/join)group(s). + * @property {string} targetWindowName - Name of the targetWindow. + The target window is the window that was passed into (merge/join)group(s). + */ + /** + * Raised when a window has been hidden. + * + * @event Window#hidden + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} reason - Action prompted the close The reasons are: + "hide" + "hide-on-close" + */ + /** + * Raised when a window is initialized. + * + * @event Window#initialized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window is maximized. + * + * @event Window#maximized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window is minimized. + * + * @event Window#minimized + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when window navigation is rejected as per ContentNavigation whitelist/blacklist rules. + * + * @event Window#navigation-rejected + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} sourceName - source of navigation window name. + * @property {string} url - Blocked content url. + */ + /** + * Raised when a window is out of memory. + * + * @event Window#out-of-memory + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised after the execution of all of a window's preload scripts. Contains + information about all window's preload scripts' final states. + * + * @event Window#preload-scripts-state-changed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states + */ + /** + * Raised during the execution of a window's preload script. Contains information + about a single window's preload script's state, for which the event has been raised. + * + * @event Window#preload-scripts-state-changing + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {preloadScriptState[]} preloadState - An array of all final preload scripts' states + */ + /** + * Raised when an HTTP load was cancelled or failed. + * + * @event Window#resource-load-failed + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {number} errorCode - The Chromium error code. + * @property {string} errorDescription - The Chromium error description. + * @property {string} validatedURL - The url attempted. + * @property {boolean} isMainFrame - Was the attempt made from the main frame. + */ + /** + * Raised when an HTTP resource request has received response details. + * + * @event Window#resource-response-received + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {boolean} status - Status of the request. + * @property {string} newUrl - The URL of the responded resource. + * @property {string} originalUrl - The requested URL. + * @property {number} httpResponseCode - The HTTP Response code. + * @property {string} requestMethod - The HTTP request method. + * @property {string} referrer - The HTTP referrer. + * @property {object} headers - The HTTP headers. + * @property {string} resourceType - Resource type: + "mainFrame", "subFrame", + "styleSheet", "script", "image", + "object", "xhr", or "other" + */ + /** + * Raised when a window has reloaded. + * + * @event Window#reloaded + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + * @property {string} url - Url has has been reloaded. + */ + /** + * Raised when a window is displayed after having been minimized or + when a window leaves the maximize state without minimizing. + * + * @event Window#restored + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window has been prevented from showing. + A window will be prevented from showing by default, either through the API or by a user when + ‘show-requested’ has been subscribed to on the window or 'window-show-requested' + on the parent application and the Window.show(force) flag is false. + * + * @event Window#show-requested + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * Raised when a window been shown. + * + * @event Window#shown + * @type {object} + * @property {string} name - Name of the window. + * @property {string} uuid - UUID of the application that the window belongs to. + */ + /** + * @typedef {object} legacyWindowIdentity + * @summary Object summary + * @desc Object description + * @property {string} appUuid - The UUID of the application this window entry belongs to. + * @property {string} windowName - The name of this window entry. + */ + /** + * @typedef {object} preloadScriptState + * @summary Object summary + * @desc Object description + * @property {string} url - The url of the preload script. + * @property {string} state - The preload script state: + "load-failed", "failed", "succeeded" + */ + private nativeWindow; + constructor(wire: Transport, identity: Identity); + createWindow(options: any): Promise<_Window>; + protected runtimeEventComparator: (listener: RuntimeEvent) => boolean; + private windowListFromNameList; + /** + * Retrieves an array of frame info objects representing the main frame and any + * iframes that are currently on the page. + * @return {Promise.>} + * @tutorial Window.getAllFrames + */ + getAllFrames(): Promise>; + /** + * Gets the current bounds (top, left, width, height) of the window. + * @return {Promise.} + * @tutorial Window.getBounds + */ + getBounds(): Promise; + /** + * Returns the native JavaScript "window" object for the window. + * @return {Promise.} + * @tutorial Window.getNativeWindow + */ + getNativeWindow(): Promise; + /** + * Gives focus to the window. + * @return {Promise.} + * @emits _Window#focused + * @tutorial Window.focus + */ + focus(): Promise; + /** + * Removes focus from the window. + * @return {Promise.} + * @tutorial Window.blur + */ + blur(): Promise; + /** + * Brings the window to the front of the window stack. + * @return {Promise.} + * @tutorial Window.bringToFront + */ + bringToFront(): Promise; + /** + * Performs the specified window transitions. + * @param {Transition} transitions - Describes the animations to perform. See the tutorial. + * @param {TransitionOptions} options - Options for the animation. See the tutorial. + * @return {Promise.} + * @tutorial Window.animate + */ + animate(transitions: Transition, options: TransitionOptions): Promise; + /** + * Hides the window. + * @return {Promise.} + * @tutorial Window.hide + */ + hide(): Promise; + /** + * closes the window application + * @param { boolean } [force = false] Close will be prevented from closing when force is false and + * ‘close-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Window.close + */ + close(force?: boolean): Promise; + /** + * Returns then running applications uuid + * @return {Promise.} + * @tutorial Window.getNativeId + */ + getNativeId(): Promise; + /** + * Prevents a user from changing a window's size/position when using the window's frame. + * @return {Promise.} + * @tutorial Window.disableFrame + */ + disableFrame(): Promise; + /** + * Re-enables user changes to a window's size/position when using the window's frame. + * @return {Promise.} + * @tutorial Window.enableFrame + */ + enableFrame(): Promise; + /** + * Executes Javascript on the window, restricted to windows you own or windows owned by + * applications you have created. + * @param { string } code JavaScript code to be executed on the window. + * @return {Promise.} + * @tutorial Window.executeJavaScript + */ + executeJavaScript(code: string): Promise; + /** + * Flashes the window’s frame and taskbar icon until stopFlashing is called. + * @return {Promise.} + * @tutorial Window.flash + */ + flash(): Promise; + /** + * Stops the taskbar icon from flashing. + * @return {Promise.} + * @tutorial Window.stopFlashing + */ + stopFlashing(): Promise; + /** + * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this + * window. If a window is not in a group an empty array is returned. Please note that + * calling window is included in the result array. + * @return {Promise.>} + * @tutorial Window.getGroup + */ + getGroup(): Promise>; + /** + * Gets an information object for the window. + * @return {Promise.} + * @tutorial Window.getInfo + */ + getInfo(): Promise; + /** + * Gets the current settings of the window. + * @return {Promise.} + * @tutorial Window.getOptions + */ + getOptions(): Promise; + /** + * Gets the parent application. + * @return {Promise.} + * @tutorial Window.getParentApplication + */ + getParentApplication(): Promise; + /** + * Gets the parent window. + * @return {Promise.<_Window>} + * @tutorial Window.getParentWindow + */ + getParentWindow(): Promise<_Window>; + /** + * Gets a base64 encoded PNG snapshot of the window. + * @return {Promise.} + * @tutorial Window.getSnapshot + */ + getSnapshot(): Promise; + /** + * Gets the current state ("minimized", "maximized", or "restored") of the window. + * @return {Promise.} + * @tutorial Window.getState + */ + getState(): Promise; + /** + * Determines if the window is currently showing. + * @return {Promise.} + * @tutorial Window.isShowing + */ + isShowing(): Promise; + /** + * Joins the same window group as the specified window. + * @param { class } target The window whose group is to be joined + * @return {Promise.} + * @tutorial Window.joinGroup + */ + joinGroup(target: _Window): Promise; + /** + * Reloads the window current page + * @return {Promise.} + * @tutorial Window.reload + */ + reload(ignoreCache?: boolean): Promise; + /** + * Leaves the current window group so that the window can be move independently of those in the group. + * @return {Promise.} + * @tutorial Window.leaveGroup + */ + leaveGroup(): Promise; + /** + * Maximizes the window + * @return {Promise.} + * @tutorial Window.maximize + */ + maximize(): Promise; + /** + * Merges the instance's window group with the same window group as the specified window + * @param { class } target The window whose group is to be merged with + * @return {Promise.} + * @tutorial Window.mergeGroups + */ + mergeGroups(target: _Window): Promise; + /** + * Minimizes the window. + * @return {Promise.} + * @tutorial Window.minimize + */ + minimize(): Promise; + /** + * Moves the window by a specified amount. + * @param { number } deltaLeft The change in the left position of the window + * @param { number } deltaTop The change in the top position of the window + * @return {Promise.} + * @tutorial Window.moveBy + */ + moveBy(deltaLeft: number, deltaTop: number): Promise; + /** + * Moves the window to a specified location. + * @param { number } left The left position of the window + * @param { number } top The top position of the window + * @return {Promise.} + * @tutorial Window.moveTo + */ + moveTo(left: number, top: number): Promise; + /** + * Resizes the window by a specified amount. + * @param { number } deltaWidth The change in the width of the window + * @param { number } deltaHeight The change in the height of the window + * @param { string } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right." + * If undefined, the default is "top-left" + * @return {Promise.} + * @tutorial Window.resizeBy + */ + resizeBy(deltaWidth: number, deltaHeight: number, anchor: string): Promise; + /** + * Resizes the window to the specified dimensions. + * @param { number } width The change in the width of the window + * @param { number } height The change in the height of the window + * @param { string } anchor Specifies a corner to remain fixed during the resize. + * Can take the values: "top-left", "top-right", "bottom-left", or "bottom-right." + * If undefined, the default is "top-left" + * @return {Promise.} + * @tutorial Window.resizeTo + */ + resizeTo(width: number, height: number, anchor: string): Promise; + /** + * Restores the window to its normal state (i.e., unminimized, unmaximized). + * @return {Promise.} + * @tutorial Window.restore + */ + restore(): Promise; + /** + * Will bring the window to the front of the entire stack and give it focus. + * @return {Promise.} + * @tutorial Window.setAsForeground + */ + setAsForeground(): Promise; + /** + * Sets the window's size and position. + * @property { Bounds } bounds This is a * @type {string} name - name of the window.object that holds the propertys of + * @return {Promise.} + * @tutorial Window.setBounds + */ + setBounds(bounds: Bounds): Promise; + /** + * Shows the window if it is hidden. + * @param { boolean } [force = false] Show will be prevented from showing when force is false and + * ‘show-requested’ has been subscribed to for application’s main window. + * @return {Promise.} + * @tutorial Window.show + */ + show(force?: boolean): Promise; + /** + * Shows the window if it is hidden at the specified location. + * If the toggle parameter is set to true, the window will + * alternate between showing and hiding. + * @param { number } left The left position of the window + * @param { number } top The right position of the window + * @param { boolean } force Show will be prevented from closing when force is false and + * ‘show-requested’ has been subscribed to for application’s main window + * @return {Promise.} + * @tutorial Window.showAt + */ + showAt(left: number, top: number, force?: boolean): Promise; + /** + * Shows the Chromium Developer Tools + * @return {Promise.} + * @tutorial Window.showDeveloperTools + */ + showDeveloperTools(): Promise; + /** + * Updates the window using the passed options + * @param {*} options Changes a window's options that were defined upon creation. See tutorial + * @return {Promise.} + * @tutorial Window.updateOptions + */ + updateOptions(options: any): Promise; + /** + * Provides credentials to authentication requests + * @param { string } userName userName to provide to the authentication challange + * @param { string } password password to provide to the authentication challange + * @return {Promise.} + * @tutorial Window.authenticate + */ + authenticate(userName: string, password: string): Promise; + /** + * Returns the zoom level of the window. + * @return {Promise.} + * @tutorial Window.getZoomLevel + */ + getZoomLevel(): Promise; + /** + * Sets the zoom level of the window. + * @param { number } level The zoom level + * @return {Promise.} + * @tutorial Window.setZoomLevel + */ + setZoomLevel(level: number): Promise; + /** + * Navigates the window to a specified URL. + * @param {string} url - The URL to navigate the window to. + * @return {Promise.} + * @tutorial Window.navigate + */ + navigate(url: string): Promise; + /** + * Navigates the window back one page. + * @return {Promise.} + * @tutorial Window.navigateBack + */ + navigateBack(): Promise; + /** + * Stops any current navigation the window is performing. + * @return {Promise.} + * @tutorial Window.stopNavigation + */ + stopNavigation(): Promise; +} +export interface _Window { + on(type: 'focused', listener: Function): Promise; + on(type: 'initialized', listener: Function): Promise; + on(type: 'bounds-changed', listener: (data: BoundsChangedReply) => void): Promise; + on(type: 'hidden', listener: Function): Promise; + on(type: 'removeListener', listener: (eventType: string | symbol) => void): Promise; + on(type: 'newListener', listener: (eventType: string | symbol) => void): Promise; + on(type: 'closed', listener: (eventType: CloseEventShape) => void): Promise; + on(type: 'fire-constructor-callback', listener: Function): Promise; +} diff --git a/types/openfin/v34/_v2/environment/environment.d.ts b/types/openfin/v34/_v2/environment/environment.d.ts new file mode 100644 index 0000000000..0b0f1571f2 --- /dev/null +++ b/types/openfin/v34/_v2/environment/environment.d.ts @@ -0,0 +1,10 @@ +import { NewConnectConfig } from '../transport/wire'; +export interface Environment { + writeToken(path: string, token: string): Promise; + retrievePort(config: NewConnectConfig): Promise; + getNextMessageId(): any; + getRandomId(): string; + createChildWindow(options: any): Promise; + isWindowExists(uuid: string, name: string): boolean; +} +export declare const notImplementedEnvErrorMsg = "Not implemented in this environment"; diff --git a/types/openfin/v34/_v2/environment/node-env.d.ts b/types/openfin/v34/_v2/environment/node-env.d.ts new file mode 100644 index 0000000000..03e0faeede --- /dev/null +++ b/types/openfin/v34/_v2/environment/node-env.d.ts @@ -0,0 +1,11 @@ +import { Environment } from './environment'; +import { NewConnectConfig } from '../transport/wire'; +export default class NodeEnvironment implements Environment { + private messageCounter; + writeToken: (path: string, token: string) => Promise; + retrievePort: (config: NewConnectConfig) => Promise; + getNextMessageId: () => any; + createChildWindow: (options: any) => Promise; + getRandomId: () => string; + isWindowExists: (uuid: string, name: string) => boolean; +} diff --git a/types/openfin/v34/_v2/environment/openfin-env.d.ts b/types/openfin/v34/_v2/environment/openfin-env.d.ts new file mode 100644 index 0000000000..456e2f8caf --- /dev/null +++ b/types/openfin/v34/_v2/environment/openfin-env.d.ts @@ -0,0 +1,11 @@ +import { Environment } from './environment'; +import { NewConnectConfig } from '../transport/wire'; +export default class OpenFinEnvironment implements Environment { + writeToken: (path: string, token: string) => Promise; + retrievePort: (config: NewConnectConfig) => Promise; + getNextMessageId: () => any; + createChildWindow: (options: any) => Promise; + getRandomId: () => string; + private resolveUrl; + isWindowExists: (uuid: string, name: string) => boolean; +} diff --git a/types/openfin/v34/_v2/environment/openfin-renderer-api.d.ts b/types/openfin/v34/_v2/environment/openfin-renderer-api.d.ts new file mode 100644 index 0000000000..82822c3111 --- /dev/null +++ b/types/openfin/v34/_v2/environment/openfin-renderer-api.d.ts @@ -0,0 +1,6 @@ +export declare const ipc: any; +export declare const routingId: any; +export declare const CORE_MESSAGE_CHANNEL: any; +export declare const outboundTopic = "of-window-message"; +export declare const inboundTopic: string; +export declare const currentWindowIdentity: any; diff --git a/types/openfin/v34/_v2/identity.d.ts b/types/openfin/v34/_v2/identity.d.ts new file mode 100644 index 0000000000..f10f030248 --- /dev/null +++ b/types/openfin/v34/_v2/identity.d.ts @@ -0,0 +1,4 @@ +export interface Identity { + uuid: string; + name?: string; +} diff --git a/types/openfin/v34/_v2/launcher/launcher.d.ts b/types/openfin/v34/_v2/launcher/launcher.d.ts new file mode 100644 index 0000000000..d0ffc16989 --- /dev/null +++ b/types/openfin/v34/_v2/launcher/launcher.d.ts @@ -0,0 +1,15 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export default class Launcher { + private os; + OpenFin_Installer: string; + Installer_Work_Dir: string; + Security_Realm_Config_Key: string; + nixConfig?: any; + constructor(); + launch(config: ConfigWithRuntime, manifestLocation: string, namedPipeName: string): Promise; + static IS_SUPPORTED(): boolean; + private macLaunch; + private winLaunch; +} diff --git a/types/openfin/v34/_v2/launcher/nix-launch.d.ts b/types/openfin/v34/_v2/launcher/nix-launch.d.ts new file mode 100644 index 0000000000..02b0da4fbb --- /dev/null +++ b/types/openfin/v34/_v2/launcher/nix-launch.d.ts @@ -0,0 +1,14 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export declare function getUrl(version: string, urlPath: string): string; +export declare function download(version: string, folder: string, osConfig: OsConfig): Promise; +export declare function getRuntimePath(version: string): Promise; +export declare function install(versionOrChannel: string, osConfig: OsConfig): Promise; +export interface OsConfig { + manifestLocation: string; + namedPipeName: string; + urlPath: string; + executablePath: string; +} +export default function launch(config: ConfigWithRuntime, osConfig: OsConfig): Promise; diff --git a/types/openfin/v34/_v2/launcher/util.d.ts b/types/openfin/v34/_v2/launcher/util.d.ts new file mode 100644 index 0000000000..808ad015ea --- /dev/null +++ b/types/openfin/v34/_v2/launcher/util.d.ts @@ -0,0 +1,8 @@ +export declare function exists(path: string): Promise; +export declare function get(url: string): Promise; +export declare function unzip(file: string, dest: string): Promise; +export declare function rmDir(dirPath: string, removeSelf?: boolean): Promise; +export declare function downloadFile(url: string, writeLocation: string): Promise<{}>; +export declare function resolveRuntimeVersion(versionOrChannel: string): Promise; +export declare function first(arr: T[], func: (x: T, i: number, r: T[]) => boolean): T | null; +export declare function resolveDir(base: string, paths: string[]): Promise; diff --git a/types/openfin/v34/_v2/launcher/win-launch.d.ts b/types/openfin/v34/_v2/launcher/win-launch.d.ts new file mode 100644 index 0000000000..b08fac3f8a --- /dev/null +++ b/types/openfin/v34/_v2/launcher/win-launch.d.ts @@ -0,0 +1,4 @@ +/// +import { ChildProcess } from 'child_process'; +import { ConfigWithRuntime } from '../transport/wire'; +export default function launch(config: ConfigWithRuntime, manifestLocation: string, namedPipeName: string, Installer_Work_Dir: string): Promise; diff --git a/types/openfin/v34/_v2/main.d.ts b/types/openfin/v34/_v2/main.d.ts new file mode 100644 index 0000000000..2f4a3d8730 --- /dev/null +++ b/types/openfin/v34/_v2/main.d.ts @@ -0,0 +1,11 @@ +import Fin from './api/fin'; +import { Application } from './api/application/application'; +import { _Window as Window } from './api/window/window'; +import { _Frame as Frame } from './api/frame/frame'; +import { _Notification as Notification } from './api/notification/notification'; +import System from './api/system/system'; +import { ConnectConfig } from './transport/wire'; +export declare function connect(config: ConnectConfig): Promise; +export declare function launch(config: ConnectConfig): Promise; +export { Identity } from './identity'; +export { Fin, Application, Window, System, Frame, Notification }; diff --git a/types/openfin/v34/_v2/of-main.d.ts b/types/openfin/v34/_v2/of-main.d.ts new file mode 100644 index 0000000000..cb0ff5c3b5 --- /dev/null +++ b/types/openfin/v34/_v2/of-main.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/types/openfin/v34/_v2/transport/elipc.d.ts b/types/openfin/v34/_v2/transport/elipc.d.ts new file mode 100644 index 0000000000..94c398cba5 --- /dev/null +++ b/types/openfin/v34/_v2/transport/elipc.d.ts @@ -0,0 +1,13 @@ +/// +import { EventEmitter } from 'events'; +import { Wire, READY_STATE } from './wire'; +export default class ElIPCTransport extends EventEmitter implements Wire { + protected wire: any; + onmessage: (data: any) => void; + constructor(onmessage: (data: any) => void); + connectSync: () => any; + connect: (address: string) => Promise; + send(data: any, flags?: any): Promise; + shutdown(): Promise; + static READY_STATE: typeof READY_STATE; +} diff --git a/types/openfin/v34/_v2/transport/port-discovery.d.ts b/types/openfin/v34/_v2/transport/port-discovery.d.ts new file mode 100644 index 0000000000..d8ea25934d --- /dev/null +++ b/types/openfin/v34/_v2/transport/port-discovery.d.ts @@ -0,0 +1,17 @@ +import { PortDiscoveryConfig } from './wire'; +import { Environment } from '../environment/environment'; +export declare class PortDiscovery { + private savedConfig; + private namedPipeName; + private manifestLocation; + private namedPipeServer; + private pipeConnection; + private timeoutTimer; + private environment; + constructor(config: PortDiscoveryConfig, environment: Environment); + retrievePort(): Promise; + private createDiscoveryNamedPipe; + private listenDiscoveryMessage; + private createManifest; + private cleanup; +} diff --git a/types/openfin/v34/_v2/transport/transport-errors.d.ts b/types/openfin/v34/_v2/transport/transport-errors.d.ts new file mode 100644 index 0000000000..90f9d10f55 --- /dev/null +++ b/types/openfin/v34/_v2/transport/transport-errors.d.ts @@ -0,0 +1,17 @@ +export declare class DisconnectedError extends Error { + constructor(readyState: number); + readyState: number; +} +export declare class UnexpectedActionError extends Error { +} +export declare class DuplicateCorrelationError extends Error { +} +export declare class NoAckError extends Error { +} +export declare class NotImplementedError extends Error { +} +export declare class NotSupportedError extends Error { +} +export declare class RuntimeError extends Error { + constructor(data: any); +} diff --git a/types/openfin/v34/_v2/transport/transport.d.ts b/types/openfin/v34/_v2/transport/transport.d.ts new file mode 100644 index 0000000000..fb7b967240 --- /dev/null +++ b/types/openfin/v34/_v2/transport/transport.d.ts @@ -0,0 +1,48 @@ +/// +import { Wire, WireConstructor, READY_STATE, ExistingConnectConfig, ConnectConfig, InternalConnectConfig } from './wire'; +import { Identity } from '../identity'; +import { EventEmitter } from 'events'; +import { Environment } from '../environment/environment'; +export declare type MessageHandler = (data: any) => boolean; +declare class Transport extends EventEmitter { + protected wireListeners: Map; + protected uncorrelatedListener: Function; + protected messageHandlers: MessageHandler[]; + me: Identity; + protected wire: Wire; + environment: Environment; + topicRefMap: Map; + sendRaw: Wire['send']; + constructor(wireType: WireConstructor, environment: Environment); + connectSync: (config: ConnectConfig) => any; + connect(config: InternalConnectConfig): Promise; + connectByPort(config: ExistingConnectConfig): Promise; + READY_STATE: typeof READY_STATE; + ferryAction(data: any): Promise>; + registerMessageHandler(handler: MessageHandler): void; + protected addWireListener(id: number, resolve: Function, reject: Function, uncorrelated: boolean): void; + protected onmessage(data: Message): void; + protected handleMessage(data: Message): boolean; +} +export default Transport; +interface Transport { + sendAction(action: 'request-external-authorization', payload: {}, uncorrelated: true): Promise>; + sendAction(action: string, payload: {}, uncorrelated: boolean): Promise>; + topicRefMap: Map; +} +export declare class Message { + action: string; + payload: T; + correlationId?: number; +} +export declare class Payload { + success: boolean; + data: any; +} +export declare class AuthorizationPayload { + token: string; + file: string; +} diff --git a/types/openfin/v34/_v2/transport/websocket.d.ts b/types/openfin/v34/_v2/transport/websocket.d.ts new file mode 100644 index 0000000000..5617afa8e3 --- /dev/null +++ b/types/openfin/v34/_v2/transport/websocket.d.ts @@ -0,0 +1,14 @@ +/// +import { EventEmitter } from 'events'; +import * as WebSocket from 'ws'; +import { Wire, READY_STATE } from './wire'; +export default class WebSocketTransport extends EventEmitter implements Wire { + protected wire: WebSocket; + onmessage: (data: any) => void; + constructor(onmessage: (data: any) => void); + connect: (address: string) => Promise; + connectSync: () => any; + send(data: any, flags?: any): Promise; + shutdown(): Promise; + static READY_STATE: typeof READY_STATE; +} diff --git a/types/openfin/v34/_v2/transport/wire.d.ts b/types/openfin/v34/_v2/transport/wire.d.ts new file mode 100644 index 0000000000..227c6d4d72 --- /dev/null +++ b/types/openfin/v34/_v2/transport/wire.d.ts @@ -0,0 +1,71 @@ +/// +import { EventEmitter } from 'events'; +export interface Wire extends EventEmitter { + connect(address: string): Promise; + connectSync(): any; + send(data: any): Promise; + shutdown(): Promise; +} +export interface WireConstructor { + new (onmessage: (data: any) => void): Wire; +} +export interface RuntimeConfig { + version: string; + fallbackVersion?: string; + securityRealm?: string; + verboseLogging?: boolean; + arguments?: string; + rvmDir?: string; +} +export interface BaseConfig { + uuid?: string; + address?: string; + name?: string; + nonPersistent?: boolean; + runtimeClient?: boolean; + licenseKey?: string; + client?: any; + manifestUrl?: string; + startupApp?: any; + lrsUrl?: string; + assetsUrl?: string; + devToolsPort?: number; + installerUI?: boolean; + runtime?: RuntimeConfig; + appAssets?: [{ + src: string; + alias: string; + target: string; + version: string; + args: string; + }]; + customItems?: [any]; + timeout?: number; +} +export interface ConfigWithUuid extends BaseConfig { + uuid: string; +} +export interface ExistingConnectConfig extends ConfigWithUuid { + address: string; +} +export interface ConfigWithRuntime extends BaseConfig { + runtime: RuntimeConfig; +} +export interface ExternalConfig extends BaseConfig { + manifestUrl: string; +} +export declare type NewConnectConfig = ConfigWithUuid & ConfigWithRuntime; +export declare type PortDiscoveryConfig = (ExternalConfig & ConfigWithRuntime) | NewConnectConfig; +export declare type ConnectConfig = ExistingConnectConfig | NewConnectConfig | ExternalConfig; +export declare type InternalConnectConfig = ExistingConnectConfig | NewConnectConfig; +export declare function isExternalConfig(config: ConnectConfig): config is ExternalConfig; +export declare function isExistingConnectConfig(config: any): config is ExistingConnectConfig; +export declare function isNewConnectConfig(config: any): config is NewConnectConfig; +export declare function isPortDiscoveryConfig(config: any): config is PortDiscoveryConfig; +export declare function isInternalConnectConfig(config: any): config is InternalConnectConfig; +export declare enum READY_STATE { + CONNECTING = 0, + OPEN = 1, + CLOSING = 2, + CLOSED = 3 +} diff --git a/types/openfin/v34/_v2/util/normalize-config.d.ts b/types/openfin/v34/_v2/util/normalize-config.d.ts new file mode 100644 index 0000000000..ed322d30ec --- /dev/null +++ b/types/openfin/v34/_v2/util/normalize-config.d.ts @@ -0,0 +1,3 @@ +import { ConnectConfig, InternalConnectConfig, ExternalConfig } from '../transport/wire'; +export declare function normalizeConfig(config: ConnectConfig): Promise; +export declare function validateConfig(config: ConnectConfig): Promise; diff --git a/types/openfin/v34/_v2/util/promises.d.ts b/types/openfin/v34/_v2/util/promises.d.ts new file mode 100644 index 0000000000..8e7bf9efe9 --- /dev/null +++ b/types/openfin/v34/_v2/util/promises.d.ts @@ -0,0 +1,5 @@ +export declare function promisify(func: Function): (...args: any[]) => Promise; +export declare function promiseMap(arr: T[], asyncF: (x: T, i: number, r: T[]) => Promise): Promise; +export declare type asyncF = (...args: any[]) => Promise; +export declare function serial(arr: asyncF[]): Promise; +export declare function promiseMapSerial(arr: any[], func: asyncF): Promise; diff --git a/types/openfin/v34/_v2/util/ref-counter.d.ts b/types/openfin/v34/_v2/util/ref-counter.d.ts new file mode 100644 index 0000000000..8184e09079 --- /dev/null +++ b/types/openfin/v34/_v2/util/ref-counter.d.ts @@ -0,0 +1,7 @@ +export default class RefCoutner { + topicRefMap: Map; + incRefCount(key: string): number; + decRefCount(key: string): number; + actOnFirst(key: string, firstAction: () => any, nonFirstAction?: () => void): any; + actOnLast(key: string, lastAction: () => any, nonLastAction?: () => void): any; +} diff --git a/types/openfin/v34/index.d.ts b/types/openfin/v34/index.d.ts new file mode 100644 index 0000000000..fe34f0b630 --- /dev/null +++ b/types/openfin/v34/index.d.ts @@ -0,0 +1,1907 @@ +// Type definitions for OpenFin API 34.0 +// Project: https://openfin.co/ +// Definitions by: Chris Barker +// Ricardo de Pena +// Roma +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +// based on v9.61.34.22 +// see https://openfin.co/support/technical-faq/#what-do-the-numbers-in-the-runtime-version-mean + +/** + * JavaScript API + * The JavaScript API allows you to create an HTML/JavaScript application that has access to the native windowing environment, + * can communicate with other applications and has access to sandboxed system-level features. + * + * API Ready + * When using the OpenFin API, it is important to ensure that it has been fully loaded before making any API calls. To verify + * that the API is in fact ready, be sure to make any API calls either from within the fin.desktop.main() method or explicitly + * after it has returned. This avoids the situation of trying to access methods that are not yet fully injected. + * + * Overview + * When running within the OpenFin Runtime your web applications have access to the "fin" namespace and all the modules within the API + * without the need to include additional source files. You can treat the "fin" namespace as you would the "window", "navigator" or "documennt" objects. + */ +declare namespace fin { + var Application: import('./_v2/api/application/application').default + var Clipboard: import('./_v2/api/clipboard/clipboard').default + var ExternalApplication: import('./_v2/api/external-application/external-application').default + var Frame: import('./_v2/api/frame/frame').default + var GlobalHotkey: import('./_v2/api/global-hotkey/index').default + var InterApplicationBus: import('./_v2/api/interappbus/interappbus').default + var Notification: import('./_v2/api/notification/notification').default + var System: import('./_v2/api/system/system').default + var Window: import('./_v2/api/window/window').default + + const desktop: OpenFinDesktop; + + interface OpenFinDesktop { + main(f: () => any): void; + Application: OpenFinApplicationStatic; + ExternalApp: OpenFinExternalApplicationStatic; + InterApplicationBus: OpenFinInterApplicationBus; + Notification: OpenFinNotificationStatic; + System: OpenFinSystem; + Window: OpenFinWindowStatic; + Frame: OpenFinFrameStatic; + } + + interface OpenFinApplicationStatic { + /** + * Creates a new Application. + * An object representing an application. Allows the developer to create, execute, show/close an application as well as listen to application events. + */ + new ( + options: ApplicationOptions, + callback?: (successObj: { httpResponseCode: number }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinApplication; + /** + * Launches the given Application manifest. + */ + createFromManifest(manifestUrl: string, callback?: (app: OpenFinApplication) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Returns an Application object that represents an existing application. + */ + getCurrent(): OpenFinApplication; + /** + * Returns an Application object that represents an existing application. + */ + wrap(uuid: string): OpenFinApplication; + } + + /** + * Application + * An object representing an application.Allows the developer to create, execute, show / close an application as well as listen to application events. + */ + interface OpenFinApplication { + /** + * Returns an instance of the main Window of the application + */ + getWindow(): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinApplicationEventType, + listener: (event: ApplicationBaseEvent + | TrayIconClickedEvent + | WindowEvent + | WindowAlertRequestedEvent + | WindowAuthRequested + | WindowNavigationRejectedEvent + | WindowEndLoadEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Closes the application and any child windows created by the application. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of wrapped fin.desktop.Windows for each of the application's child windows. + */ + getChildWindows(callback?: (children: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of active window groups for all of the application's windows. Each group is represented as an array of wrapped fin.desktop.Windows. + */ + getGroups(callback?: (groups: OpenFinWindow[][]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the JSON manifest that was used to create the application. Invokes the error callback if the application was not created from a manifest. + */ + getManifest(callback?: (manifest: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves UUID of the application that launches this application. Invokes the error callback if the application was created from a manifest. + */ + getParentUuid(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves current configuration of application's shortcuts. + */ + getShortcuts(callback?: (config: ShortCutConfig) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves information about the application. + */ + getInfo(callback?: (info: LaunchInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves information about the system tray. + */ + getTrayIconInfo(callback?: (trayInfo: TrayIconInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the application is currently running. + */ + isRunning(callback?: (running: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Registers a username and an app name for licensing purposes. + */ + registerUser(userName: string, appName: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinApplicationEventType, + previouslyRegisteredListener: (event: ApplicationBaseEvent + | TrayIconClickedEvent + | WindowEvent + | WindowAlertRequestedEvent + | WindowAuthRequested + | WindowNavigationRejectedEvent + | WindowEndLoadEvent) => any, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Removes the application's icon from the tray. + */ + removeTrayIcon(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restarts the application. + */ + restart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Runs the application. When the application is created, run must be called. + */ + run(callback?: (successObj: SuccessObj) => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * Tells the rvm to relaunch the main application once upon a complete shutdown + */ + scheduleRestart(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets new shortcut configuration for current application. + * Application has to be launched with a manifest and has to have shortcut configuration (icon url, name, etc.) in its manifest to + * be able to change shortcut states. + */ + setShortcuts(config: ShortCutConfig, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Adds a customizable icon in the system tray and notifies the application when clicked. + */ + setTrayIcon(iconUrl: string, listener: (clickInfo: TrayIconClickedEvent) => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the application by terminating its process. + */ + terminate(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Waits for a hanging application. This method can be called in response to an application "not-responding" to allow the application + * to continue and to generate another "not-responding" message after a certain period of time. + */ + wait(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * The Application's uuid + */ + uuid: string; + } + + interface ShortCutConfig { + /** + * application has a shortcut on the desktop + */ + desktop?: boolean; + /** + * application has no shortcut in the start menu + */ + startMenu?: boolean; + /** + * application will be launched on system startup + */ + systemStartup?: boolean; + } + + interface SuccessObj { + httpResponseCode: number; + } + + interface NetworkErrorInfo extends ErrorInfo { + networkErrorCode: number; + } + + interface ErrorInfo { + stack: string; + message: string; + } + + interface ApplicationOptions { + /** + * The name of the application. + */ + name?: string; + /** + * The url to the application. + */ + url?: string; + /** + * The UUID of the application, unique within the set of all other applications running in the OpenFin Runtime. name and uuid must match. + */ + uuid?: string; + /** + * Enable Flash at the application level. Default: false. + */ + plugins?: boolean; + /** + * The options of the main window of the application. + */ + mainWindowOptions?: WindowOptions; + } + + interface WindowOptions { + /** + * Enable keyboard shortcuts for devtools and zoom. Default: false for both. + */ + accelerator?: { + devtools?: boolean, + zoom?: boolean, + reload?: boolean, + reloadIgnoreCache?: boolean, + }; + /** + * A flag to always position the window at the top of the window stack. Default: false. + * Updatable + */ + alwaysOnTop?: boolean; + /** + * A flag to automatically show the Window when it is created. Default: false. + */ + autoShow?: boolean; + /** + * A flag to show the context menu when right-clicking on a window. Gives access to the Developer Console for the Window. Default: true + * Updatable + */ + contextMenu?: boolean; + /** + * This defines and applies rounded corners for a frameless window. Default for both width and height: 0. + * Updatable + */ + cornerRounding?: { + width?: number; + height?: number; + }; + /** + * A field that the user can attach serializable data to to be ferried around with the window options. Default: ''. + */ + customData?: any; + /** + * Specifies that the window will be positioned in the center of the primary monitor when loaded for the first time on a machine. + * When the window corresponding to that id is loaded again, the position from before the window was closed is used. + * This option overrides defaultLeft and defaultTop. Default: false. + */ + defaultCentered?: boolean; + /** + * The default height of the window. Specifies the height of the window when loaded for the first time on a machine. + * When the window corresponding to that id is loaded again, the height is taken to be the last height of the window before it was closed. Default: 500. + */ + defaultHeight?: number; + /** + * The default left position of the window. Specifies the position of the left of the window when loaded for the first time on a machine. + * When the window corresponding to that id is loaded again, the value of left is taken to be the last value before the window was closed. Default: 100. + */ + defaultWidth?: number; + /** + * The default top position of the window. Specifies the position of the top of the window when loaded for the first time on a machine. + * When the window corresponding to that id is loaded again, the value of top is taken to be the last value before the window was closed. Default: 100. + */ + defaultTop?: number; + /** + * The default width of the window. Specifies the width of the window when loaded for the first time on a machine. + * When the window corresponding to that id is loaded again, the width is taken to be the last width of the window before it was closed. Default: 800. + */ + defaultLeft?: number; + /** + * A flag to show the frame. Default: true. + * Updatable + */ + frame?: boolean; + /** + * A flag to allow a window to be hidden when the close button is clicked.Default: false. + * Updatable + */ + hideOnClose?: boolean; + /** + * A URL for the icon to be shown in the window title bar and the taskbar.Default: The parent application's applicationIcon. + * Updatable + */ + icon?: string; + /** + * The maximum height of a window.Will default to the OS defined value if set to - 1. Default: -1. + * Updatable + */ + maxHeight?: number; + /** + * A flag that lets the window be maximized.Default: true. + * Updatable + */ + maximizable?: boolean; + /** + * The maximum width of a window.Will default to the OS defined value if set to - 1. Default: -1. + * Updatable + */ + maxWidth?: number; + /** + * The minimum height of a window.Default: 0. + * Updatable + */ + minHeight?: number; + /** + * A flag that lets the window be minimized.Default: true. + */ + minimizable?: boolean; + /** + * The minimum width of a window.Default: 0. + */ + minWidth?: number; + /** + * The name for the window which must be unique within the context of the invoking Application. + */ + name?: string; + /** + * A flag that specifies how transparent the window will be.This value is clamped between 0.0 and 1.0.Default: 1.0. + * Updatable + */ + opacity?: number; + /** + * A flag to drop to allow the user to resize the window.Default: true. + * Updatable + */ + resizable?: boolean; + /** + * Defines a region in pixels that will respond to user mouse interaction for resizing a frameless window. + * Updatable + */ + resizeRegion?: { + /** + * The size in pixels (Default: 2), + */ + size?: number; + /** + * The size in pixels of an additional + * square resizable region located at the + * bottom right corner of a + * frameless window. (Default: 4) + */ + bottomRightCorner?: number; + }; + /** + * A flag to show the Window's icon in the taskbar. Default: true. + */ + showTaskbarIcon?: boolean; + /** + * A flag to cache the location of the window or not. Default: true. + */ + saveWindowState?: boolean; + /** + * Specify a taskbar group for the window. Default: app's uuid. + */ + taskbarIconGroup?: string; + /** + * A string that sets the window to be "minimized", "maximized", or "normal" on creation. Default: "normal". + */ + state?: string; + /** + * The URL of the window. Default: "about:blank". + */ + url?: string; + /** + * When set to false, the window will render before the "load" event is fired on the content's window. + * Caution, when false you will see an initial empty white window. Default: true. + */ + waitForPageLoad?: boolean; + } + + /** + * Clipboard + * Clipboard API allows reading and writting to the clipboard in multiple formats. + */ + interface OpenFinClipboard { + /** + * Reads available formats for the clipboard type + */ + availableFormats(type: string | null, callback?: (formats: string[]) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Reads available formats for the clipboard type + */ + readHtml(type: string | null, callback?: (html: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as Rtf + */ + readRtf(type: string | null, callback?: (rtf: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Read the content of the clipboard as plain text + */ + readText(type: string | null, callback?: (text: string) => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard + */ + write(data: any, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Html + */ + writeHtml(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as Rtf + */ + writeRtf(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Writes data into the clipboard as plain text + */ + writeText(data: string, type: string | null, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + interface OpenFinExternalApplicationStatic { + /** + * Returns an External Application object that represents an existing external application. + */ + wrap(uuid: string): OpenFinExternalApplication; + } + /** + * ExternalApplication + * An object representing an application. Allows the developer to create, execute, show and close an application, as well as listen to application events. + */ + interface OpenFinExternalApplication { + /** + * Retrieves information about the application. + */ + getInfo(callback?: (info: ExternalApplicationInfo) => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinExternalApplicationEventType, + listener: () => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinExternalApplicationEventType, + listener: () => void, + callback?: () => void, + errorCallback?: (reason: string, error: ErrorInfo) => void): void; + } + + /** + * InterApplicationBus + * A messaging bus that allows for pub/sub messaging between different applications. + */ + interface OpenFinInterApplicationBus { + /** + * Adds a listener that gets called when applications subscribe to the current application's messages. + */ + addSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Adds a listener that gets called when applications unsubscribe to the current application's messages. + */ + addUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered subscribe listener. + */ + removeSubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Removes a previously registered unsubscribe listener. + */ + removeUnsubscribeListener(listener: (uuid: string, topic: string, name: string) => void): void; + /** + * Publishes a message to all applications running on OpenFin Runtime that are subscribed to the specified topic. + */ + publish(topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sends a message to a specific application on a specific topic. + */ + send(destinationUuid: string, name: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + send(destinationUuid: string, topic: string, message: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Subscribes to messages from the specified application on the specified topic. If the subscription is for a uuid, [name], + * topic combination that has already been published to upon subscription you will receive the last 20 missed messages in the order they were published. + */ + subscribe( + senderUuid: string, + name: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + subscribe( + senderUuid: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Unsubscribes to messages from the specified application on the specified topic. + */ + unsubscribe( + senderUuid: string, + name: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + unsubscribe( + senderUuid: string, + topic: string, + listener: (message: any, uuid: string, name: string) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + } + + interface OpenFinNotificationStatic { + /** + * ctor + */ + new (options: NotificationOptions, callback?: () => void, errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinNotification; + /** + * Gets an instance of the current notification. For use within a notification window to close the window or send a message back to its parent application. + */ + getCurrent(): OpenFinNotification; + } + + /** + * Notification + * Notification represents a window on OpenFin Runtime which is shown briefly to the user on the bottom-right corner of the primary monitor. + * A notification is typically used to alert the user of some important event which requires his or her attention. + * Notifications are a child or your application that are controlled by the runtime. + */ + interface OpenFinNotification { + /** + * Closes the notification. + */ + close(callback?: () => void): void; + /** + * Sends a message to the notification. + */ + sendMessage(message: any, callback?: () => void): void; + /** + * Sends a message from the notification to the application that created the notification. The message is handled by the notification's onMessage callback. + */ + sendMessageToApplication(message: any, callback?: () => void): void; + } + + interface NotificationOptions { + /** + * A boolean that will force dismissal even if the mouse is hovering over the notification + */ + ignoreMouseOver?: boolean; + /** + * A message of any primitive or composite-primitive type to be passed to the notification upon creation. + */ + message?: any; + /** + * The timeout for displaying a notification.Can be in milliseconds or "never". + */ + duration?: number | "never"; + /** + * The url of the notification + */ + url?: string; + /** + * A function that is called when a notification is clicked. + */ + onClick?(callback: () => void): void; + /** + * Invoked when the notification is closed via .close() method on the created notification instance + * or the by the notification itself via fin.desktop.Notification.getCurrent().close(). + * NOTE: this is not invoked when the notification is dismissed via a swipe. For the swipe dismissal callback see onDismiss + */ + onClose?(callback: () => void): void; + /** + * Invoked when a the notification is dismissed by swiping it off the screen to the right. NOTE: this is no fired on a programmatic close. + */ + onDismiss?(callback: () => void): void; + /** + * A function that is called when an error occurs.The reason for the error is passed as an argument. + */ + onError?(errorCallback: (reason: string, errorObj: NetworkErrorInfo) => void): void; + /** + * The onMessage function will respond to messages sent from notification.sendMessageToApplication. + * The function is passed the message, which can be of any primitive or composite-primitive type. + */ + onMessage?(callback: (message: any) => void): void; + /** + * A function that is called when a notification is shown. + */ + onShow?(callback: (successObj: SuccessObj) => void): void; + } + + /** + * System + * An object representing the core of OpenFin Runtime. + * Allows the developer to perform system-level actions, such as accessing logs, viewing processes, clearing the cache and exiting the runtime. + */ + interface OpenFinSystem { + Clipboard: OpenFinClipboard; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinSystemEventType, + listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Clears cached data containing window state/positions, + * application resource files (images, HTML, JavaScript files), cookies, and items stored in the Local Storage. + */ + clearCache(options: CacheOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Clears all cached data when OpenFin Runtime exits. + */ + deleteCacheOnExit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Downloads the given application asset + */ + downloadAsset( + assetObj: AppAssetInfo, + progressListener?: (progress: { downloadedBytes: number, totalBytes: number }) => void, + callback?: (successObj: { path: string }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): void; + + /** + * Download preload scripts from given URLs + */ + downloadPreloadScripts(scripts: DownloadPreloadOption[], callback?: (downloadInfo: DownloadPreloadInfo[]) => void, + errorCallback?: (reason: string) => void): void; + /** + * Downloads the given OpenFin Runtime. + */ + downloadRuntime(options: RuntimeDownloadOptions, onProgress?: (progress: RuntimeDownloadProgress) => void, onComplete?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Exits the Runtime. + */ + exit(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Writes any unwritten cookies data to disk. + */ + flushCookieStore(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all applications. + */ + getAllApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data for all external applications. + */ + getAllExternalApplications(callback?: (applicationInfoList: ApplicationInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of data (name, ids, bounds) for all application windows. + */ + getAllWindows(callback?: (windowInfoList: WindowDetails[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the app asset. + */ + getAppAssetInfo(options: AppAssetOptions, callback?: (appAssetInfo: AppAssetInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Get additional info of cookies. + */ + getCookies(option: CookieOption, callback?: (info: CookieInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the command line argument string that started OpenFin Runtime. + */ + getCommandLineArguments(callback?: (args: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the configuration object that started the OpenFin Runtime. + */ + getDeviceId(callback?: (uuid: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns a hex encoded hash of the mac address and the currently logged in user name + */ + getDeviceUserId(callback?: (id: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns an Entity info object relating to the entity specified by the uuid and name passed in. The possible types are 'window', 'iframe', 'external connection' or 'unknown'. + */ + getEntityInfo(uuid: string, name: string, callback?: (info: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the value of a given environment variable on the computer on which the runtime is installed. + */ + getEnvironmentVariable(envVar: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves currently focused window identity. + */ + getFocusedWindow(callback?: (focusedWindowIdentity: Identity) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves system information. + */ + getHostSpecs(callback?: (info: HostSpecInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the contents of the log with the specified filename. + */ + getLog(logFileName: string, callback?: (variable: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing information for each log file. + */ + getLogList(callback?: (logInfoList: LogInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the minimum (inclusive) logging level that is currently being written to the logs. + */ + getMinLogLevel(callback?: (logLevel: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an object that contains data about the about the monitor setup of the computer that the runtime is running on. + */ + getMonitorInfo(callback?: (monitorInfo: MonitorInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the mouse in virtual screen coordinates (left, top). + */ + getMousePosition(callback?: (mousePosition: VirtualScreenCoordinates) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array of all of the runtime processes that are currently running. + * Each element in the array is an object containing the uuid and the name of the application to which the process belongs. + */ + getProcessList(callback?: (processInfoList: ProcessInfo[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves the Proxy settings. + */ + getProxySettings(callback?: (proxy: ProxyInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns information about the running RVM in an object. + */ + getRvmInfo(callback?: (rvmInfo: RvmInfo) => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the version of the runtime. The version contains the major, minor, build and revision numbers. + */ + getVersion(callback?: (version: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Runs an executable or batch file. + */ + launchExternalProcess(options: ExternalProcessLaunchInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Writes the passed message into both the log file and the console. + */ + log(level: "debug" | "info" | "warn" | "error", message: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Monitors a running process. + */ + monitorExternalProcess(options: ExternalProcessInfo, callback?: (payload: { uuid: string }) => void, errorCallback?: (reason: string) => void): void; + /** + * Opens the passed URL in the default web browser. + */ + openUrlWithBrowser(url: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Opens the passed URL in the default web browser. + */ + readRegistryValue(rootKey: string, subkey: string, value: string, callback?: (info: RegistryInfo) => void, + errorCallback?: (reason: string) => void): void; + /** + * This function call will register a unique id and produce a token. The token can be used to broker an external connection. + */ + registerExternalConnection( + uuid: string, + callback?: (detail: { + /** + * this will be unique each time + */ + token: string; + /** + * "remote-connection-uuid" + */ + uuid: string; + }) => void, + errorCallback?: (reason: string) => void): void; + /** + * Removes the process entry for the passed UUID obtained from a prior call of fin.desktop.System.launchExternalProcess(). + */ + releaseExternalProcess(processUuid: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinSystemEventType, + listener: (event: SystemBaseEvent | DesktopIconClickedEvent | IdleStateChangedEvent | MonitorInfoChangedEvent | SessionChangedEvent) => void, + callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Set the minimum log level above which logs will be written to the OpenFin log + */ + setMinLogLevel(logLevel: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the Chrome Developer Tools for the specified window. + */ + showDeveloperTools(uuid: string, name: string, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Attempt to close an external process. The process will be terminated if it has not closed after the elapsed timeout in milliseconds. + */ + terminateExternalProcess( + processUuid: string, + timeout: number, + killTree: boolean, + callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, + errorCallback?: (reason: string) => void): void; + terminateExternalProcess( + processUuid: string, + timeout: number, + callback?: (info: { result: "clean" | "terminated" | "failed" }) => void, + errorCallback?: (reason: string) => void): void; + /** + * Update the OpenFin Runtime Proxy settings. + */ + updateProxySettings(type: string, address: string, port: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface CacheOptions { + cache?: boolean; + cookies?: boolean; + localStorage?: boolean; + appcache?: boolean; + userData?: boolean; + } + + interface AppAssetInfo { + src?: string; + alias?: string; + version?: string; + target?: string; + args?: string; + mandatory?: boolean; + } + + interface AppAssetOptions { + alias: string; + } + + interface ApplicationInfo { + /** + * true when the application is running. + */ + isRunning?: boolean; + /** + * uuid of the application. + */ + uuid?: string; + /** + * uuid of the application that launches this application. + */ + parentUuid?: string; + } + + interface Identity { + uuid: string; + name: string; + } + + interface EntityInfo { + name: string; + uuid: string; + parent: Identity; + entityType: string; + } + + interface DownloadPreloadOption { + url: string; + } + + interface DownloadPreloadInfo { + success: boolean; + url?: string; + error: string; + } + + interface CookieInfo { + name: string; + // expirationDate: Date; + domain: string; + path: string; + } + + interface CookieOption { + name: string; + } + + interface RegistryInfo { + data: any; + rootKey: string; + subkey: string; + type: string; + value: string; + } + + interface RuntimeDownloadOptions { + version: string; + } + + interface RuntimeDownloadProgress { + downloadedBytes: number; + totalBytes: number; + } + + interface WindowDetails { + uuid?: string; + mainWindow?: WindowInfo; + childWindows?: WindowInfo[]; + } + + interface WindowInfo { + /** + * name of the child window + */ + name?: string; + /** + * top-most coordinate of the child window + */ + top?: number; + /** + * right-most coordinate of the child window + */ + right?: number; + /** + * bottom-most coordinate of the child window + */ + bottom?: number; + /** + * left-most coordinate of the child window + */ + left?: number; + } + + interface HostSpecInfo { + /** + * "x86" for 32-bit or "x86_64" for 64-bit + */ + arch: string; + /** + * Same payload as Node's os.cpus() + */ + cpus: NodeCpuInfo[]; + gpu: { + /** + * Graphics card name + */ + name: string; + }; + /** + * Same payload as Node's os.totalmem() + */ + memory: number; + /** + * OS name and version/edition + */ + name: string; + } + + interface NodeCpuInfo { + model: string; + /** + * in MHz + */ + speed: number; + times: { + /** + * The number of milliseconds the CPU has spent in user mode. + */ + user: number; + /** + * The number of milliseconds the CPU has spent in nice mode. + */ + nice: number; + /** + * The number of milliseconds the CPU has spent in sys mode. + */ + sys: number; + /** + * The number of milliseconds the CPU has spent in idle mode. + */ + idle: number; + /** + * The number of milliseconds the CPU has spent in irq mode. + */ + irq: number; + }; + } + + interface LogInfo { + /** + * the filename of the log + */ + name?: string; + /** + * the size of the log in bytes + */ + size?: number; + /** + * the unix time at which the log was created "Thu Jan 08 2015 14:40:30 GMT-0500 (Eastern Standard Time)" + */ + date?: string; + } + + interface ProcessInfo { + /** + * the percentage of total CPU usage + */ + cpuUsage?: number; + /** + * the application name + */ + name?: string; + /** + * the current nonpaged pool usage in bytes + */ + nonPagedPoolUsage?: number; + /** + * the number of page faults + */ + pageFaultCount?: number; + /** + * the current paged pool usage in bytes + */ + pagedPoolUsage?: number; + /** + * the total amount of memory in bytes that the memory manager has committed + */ + pagefileUsage?: number; + /** + * the peak nonpaged pool usage in bytes + */ + peakNonPagedPoolUsage?: number; + /** + * the peak paged pool usage in bytes + */ + peakPagedPoolUsage?: number; + /** + * the peak value in bytes of pagefileUsage during the lifetime of this process + */ + peakPagefileUsage?: number; + /** + * the peak working set size in bytes + */ + peakWorkingSetSize?: number; + /** + * the native process identifier + */ + processId?: number; + /** + * the application UUID + */ + uuid?: string; + /** + * the current working set size (both shared and private data) in bytes + */ + workingSetSize?: number; + } + + interface ProxyInfo { + /** + * the configured Proxy Address + */ + proxyAddress?: string; + /** + * the configured Proxy port + */ + proxyPort?: number; + /** + * Proxy Type + */ + type?: string; + } + + interface RvmInfo { + version?: string; + "start-time"?: string; + } + + interface ExternalProcessLaunchInfo { + path?: string; + /** + * Additionally note that the executable found in the zip file specified in appAssets + * will default to the one mentioned by appAssets.target + * If the the path below refers to a specific path it will override this default + */ + alias?: string; + /** + * When using alias; if no arguments are passed then the arguments (if any) + * are taken from the 'app.json' file, from the 'args' parameter + * of the 'appAssets' Object with the relevant 'alias'. + * If 'arguments' is passed as a parameter it takes precedence + * over any 'args' set in the 'app.json'. + */ + arguments?: string; + listener?(result: { + /** + * "Exited" Or "released" on a call to releaseExternalProcess + */ + topic?: string; + /** + * The mapped UUID which identifies the launched process + */ + uuid?: string; + /* + * Process exit code + */ + exitCode?: number; + }): void; + certificate?: CertificationInfo; + } + + interface CertificationInfo { + /** + * A hex string with or without spaces + */ + serial?: string; + /** + * An internally tokenized and comma delimited string allowing partial or full checks of the subject fields + */ + subject?: string; + /** + * A hex string with or without spaces + */ + publickey?: string; + /** + * A hex string with or without spaces + */ + thumbprint?: string; + /** + * A boolean indicating that the certificate is trusted and not revoked + */ + trusted?: boolean; + } + + interface ExternalProcessInfo { + pid?: number; + listener?(result: { + /** + * "Exited" Or "released" on a call to releaseExternalProcess + */ + topic?: string; + /** + * The mapped UUID which identifies the launched process + */ + uuid?: string; + /* + * Process exit code + */ + exitCode?: number; + }): void; + } + + interface OpenFinWindowStatic { + /** + * Class: Window + * + * new Window(options, callbackopt, errorCallbackopt) + * + * Creates a new OpenFin Window + * + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, + * maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. + * The new window appears in the same process as the parent window. + * @param options - The options of the window + * @param [callback] - Called if the window creation was successful + * @param [callback.successObj] - httpResponseCode + */ + new ( + options: WindowOptions, + callback?: (successObj: { httpResponseCode: number }) => void, + errorCallback?: (reason: string, errorObj: NetworkErrorInfo) => void): OpenFinWindow; + /** + * Returns an instance of the current window. + * @returns Current window + */ + getCurrent(): OpenFinWindow; + /** + * Returns a Window object that wraps an existing window. + */ + wrap(appUuid: string, windowName: string): OpenFinWindow; + } + + /** + * Window + * A basic window that wraps a native HTML window. Provides more fine-grained control over the window state such as the ability to minimize, + * maximize, restore, etc. By default a window does not show upon instantiation; instead the window's show() method must be invoked manually. + * The new window appears in the same process as the parent window. + */ + interface OpenFinWindow { + /** + * uuid of the application that the window belongs to. + */ + uuid: string; + /** + * Name of window + */ + name: string; + /** + * Returns the native JavaScript "window" object for the window. This method can only be used by the parent application or the window itself, + * otherwise it will return undefined. The same Single-Origin-Policy (SOP) rules apply for child windows created by window.open(url) in that the + * contents of the window object are only accessible if the URL has the same origin as the invoking window. See example below. + * Also, will not work with fin.desktop.Window objects created with fin.desktop.Window.wrap(). + * @returns Native window + */ + getNativeWindow(): Window; + /** + * Gets the parent application. + * @returns Parent application + */ + getParentApplication(): OpenFinApplication; + /** + * Gets the parent window. + */ + getParentWindow(): OpenFinWindow; + /** + * Registers an event listener on the specified event. + */ + addEventListener( + type: OpenFinWindowEventType, + listener: (event: WindowBaseEvent + | WindowAuthRequestedEvent + | WindowBoundsEvent + | WindowExternalProcessStartedEvent + | WindowExternalProcessExited + | WindowGroupChangedEvent + | WindowHiddenEvent + | Window_NavigationRejectedEvent) => void, + callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Performs the specified window transitions + */ + animate(transitions: AnimationTransition, options: AnimationOptions, callback?: (event: any) => void, errorCallback?: (reason: string) => void): void; + /** + * Provides credentials to authentication requests + */ + authenticate(userName: string, password: string, callback?: () => void, errorCallback?: (reason: string, error: ErrorInfo) => void): void; + /** + * Removes focus from the window. + */ + blur(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Brings the window to the front of the OpenFin window stack. + */ + bringToFront(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Closes the window. + * @param Close will be prevented from closing when force is false and 'close-requested' has been subscribed to for application's main window. + */ + close(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Prevents a user from changing a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-disabled' is generated when an enabled frame becomes disabled. + */ + disableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Re-enables user changes to a window's size/position when using the window's frame. + * 'disabled-frame-bounds-changing' is generated at the start of and during a user move/size operation. + * 'disabled-frame-bounds-changed' is generated after a user move/size operation. + * The events provide the bounds that would have been applied if the frame was enabled. + * 'frame-enabled' is generated when a disabled frame has becomes enabled. + */ + enableFrame(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Flashes the window's frame and taskbar icon until the window is activated. + */ + flash(options?: any, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gives focus to the window. + */ + focus(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current bounds (top, left, width, height) of the window. + */ + getBounds(callback?: (bounds: WindowBounds) => void, errorCallback?: (reason: string) => void): void; + /** + * Retrieves an array containing wrapped fin.desktop.Windows that are grouped with this window. If a window is not in a group an empty array is returned. + * Please note that calling window is included in the result array. + */ + getGroup(callback?: (group: OpenFinWindow[]) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current settings of the window. + */ + getOptions(callback?: (options: WindowOptions) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets a base64 encoded PNG snapshot of the window. + */ + getSnapshot(callback?: (base64Snapshot: string) => void, errorCallback?: (reason: string) => void): void; + /** + * Gets the current state ("minimized", "maximized", or "restored") of the window. + */ + getState(callback?: (state: "minimized" | "maximized" | "restored") => void, errorCallback?: (reason: string) => void): void; + /** + * Returns the zoom level of the window. + */ + getZoomLevel(callback?: (level: number) => void, errorCallback?: (reason: string) => void): void; + /** + * Hides the window. + */ + hide(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Determines if the window is currently showing. + */ + isShowing(callback?: (showing: boolean) => void, errorCallback?: (reason: string) => void): void; + /** + * Joins the same window group as the specified window. + */ + joinGroup(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Leaves the current window group so that the window can be move independently of those in the group. + */ + leaveGroup(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Maximizes the window. + */ + maximize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Merges the instance's window group with the same window group as the specified window + */ + mergeGroups(target: OpenFinWindow, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Minimizes the window. + */ + minimize(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window by a specified amount. + */ + moveBy(deltaLeft: number, deltaTop: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Moves the window to a specified location. + */ + moveTo(left: number, top: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Removes a previously registered event listener from the specified event. + */ + removeEventListener( + type: OpenFinWindowEventType, + listener: (event: WindowBaseEvent + | WindowAuthRequestedEvent + | WindowBoundsEvent + | WindowExternalProcessStartedEvent + | WindowExternalProcessExited + | WindowGroupChangedEvent + | WindowHiddenEvent + | Window_NavigationRejectedEvent) => void, + callback?: () => void, + errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeBy(deltaWidth: number, deltaHeight: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Resizes the window by a specified amount. + */ + resizeTo(width: number, height: number, anchor: OpenFinAnchor, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Restores the window to its normal state (i.e., unminimized, unmaximized). + */ + restore(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Will bring the window to the front of the entire stack and give it focus. + */ + setAsForeground(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the window's size and position + */ + setBounds(left: number, top: number, width: number, height: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Sets the zoom level of the window. + */ + setZoomLevel(level: number, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden. + * @param Show will be prevented from closing when force is false and 'show-requested' has been subscribed to for application's main window. + */ + show(force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Shows the window if it is hidden at the specified location. If the toggle parameter is set to true, the window will alternate between showing and hiding. + */ + showAt(left: number, top: number, force?: boolean, callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Stops the taskbar icon from flashing. + */ + stopFlashing(callback?: () => void, errorCallback?: (reason: string) => void): void; + /** + * Updates the window using the passed options + */ + updateOptions(options: WindowOptions, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface OpenFinFrameStatic { + wrap(uuid: string, name: string): OpenFinFrame; + + getCurrent(): OpenFinFrame; + } + + interface OpenFinFrame { + name: string; + uuid: string; + + addEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + + getParentWindow(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + + getInfo(callback?: (entityInfo: EntityInfo) => void, errorCallback?: (reason: string) => void): void; + + removeEventListener(type: string, listener: () => void, callback?: () => void, errorCallback?: (reason: string) => void): void; + } + + interface ApplicationBaseEvent { + topic: string; + type: OpenFinApplicationEventType; + uuid: string; + } + + interface TrayIconClickedEvent extends ApplicationBaseEvent { + button: number; // 0 for left, 1 for middle, 2 for right + monitorInfo: MonitorInfo; + x: number; // the cursor x coordinate + y: number; // the cursor y coordinate + } + + interface WindowEvent extends ApplicationBaseEvent { + name: string; + } + + interface WindowAlertRequestedEvent extends WindowEvent { + message: string; + url: string; + } + + interface WindowAuthRequested extends WindowEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowNavigationRejectedEvent extends WindowEvent { + sourceName: string; + url: string; + } + + interface WindowEndLoadEvent extends WindowEvent { + documentName: string; + isMain: boolean; + } + + interface MonitorInfoChangedEvent extends MonitorInfo { + topic: "system"; + type: "monitor-info-changed"; + } + + interface MonitorInfo { + nonPrimaryMonitors: MonitorInfoDetail[]; + primaryMonitor: MonitorInfoDetail; + reason: string; + taskbar: { + edge: "left" | "right" | "top" | "bottom", + rect: MontiorCoordinates + }; + topic: "system"; + type: "monitor-info-changed"; + virtualScreen: MontiorCoordinates; + } + + interface TrayIconInfo { + x: number; + y: number; + bounds: { + x: number; + y: number; + width: number; + height: number; + }; + monitorInfo: MonitorInfo; + } + + interface MonitorInfoDetail { + availableRect: MontiorCoordinates; + deviceId: string; + displayDeviceActive: boolean; + monitorRect: MontiorCoordinates; + name: string; + } + + interface MontiorCoordinates { + bottom: number; + left: number; + right: number; + top: number; + } + + interface VirtualScreenCoordinates { + left: number; + top: number; + } + + interface SystemBaseEvent { + topic: string; + type: OpenFinSystemEventType; + uuid: string; + } + + interface DesktopIconClickedEvent { + mouse: { + /** + * the left virtual screen coordinate of the mouse + */ + left: number, + /** + * the top virtual screen coordinate of the mouse + */ + top: number + }; + /** + * the number of milliseconds that have elapsed since the system was started, + */ + tickCount: number; + topic: "system"; + type: "desktop-icon-clicked"; + } + + interface IdleStateChangedEvent { + /** + * How long in milliseconds since the user has been idle. + */ + elapsedTime: number; + /** + * true when the user is idle,false when the user has returned; + */ + isIdle: boolean; + topic: "system"; + type: "idle-state-changed"; + } + + interface WindowBaseEvent { + /** + * the name of the window + */ + name: string; + /** + * always window + */ + topic: "window"; + /** + * window event type + */ + type: OpenFinWindowEventType; + /** + * the UUID of the application the window belongs to + */ + uuid: string; + } + + interface WindowAuthRequestedEvent extends WindowBaseEvent { + authInfo: { + host: string; + isProxy: boolean; + port: number; + realm: string; + scheme: string; + }; + } + + interface WindowBoundsEvent extends WindowBaseEvent { + /** + * describes what kind of change occurred. + * 0 means a change in position. + * 1 means a change in size. + * 2 means a change in position and size. + */ + changeType: number; + /** + * true when pending changes have been applied to the window. + */ + deferred: boolean; + /** + * the new height of the window. + */ + height: number; + /** + * the left-most coordinate of the window. + */ + left: number; + /** + * the top-most coordinate of the window. + */ + top: number; + + type: "bounds-changed" | "bounds-changing" | "disabled-frame-bounds-changed" | "disabled-frame-bounds-changing"; + /** + * the new width of the window. + */ + width: number; + } + + interface WindowExternalProcessStartedEvent extends WindowBaseEvent { + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-started"; + } + + interface WindowExternalProcessExited extends WindowBaseEvent { + /** + * the process exit code + */ + exitCode: number; + /** + * the process handle uuid + */ + processUuid: string; + type: "external-process-exited"; + } + + interface WindowGroupChangedEvent extends WindowBaseEvent { + /** + * Which group array the window that the event listener was registered on is included in: + * 'source' The window is included in sourceGroup. + * 'target' The window is included in targetGroup. + * 'nothing' The window is not included in sourceGroup nor targetGroup. + */ + memberOf: "source" | "target" | "nothing"; + /** + * The reason this event was triggered. + * 'leave' A window has left the group due to a leave or merge with group. + * 'join' A window has joined the group. + * 'merge' Two groups have been merged together. + * 'disband' There are no other windows in the group. + */ + reason: "leave" | "join" | "merge" | "disband"; + /** + * All the windows in the group the sourceWindow originated from. + */ + sourceGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the sourceWindow belongs to The source window is the window in which (merge/join/leave)group(s) was called. + */ + sourceWindowAppUuid: string; + /** + * the name of the sourcewindow.The source window is the window in which(merge / join / leave) group(s) was called. + */ + sourceWindowName: string; + /** + * All the windows in the group the targetWindow orginated from + */ + targetGroup: WindowOfGroupInfo[]; + /** + * The UUID of the application the targetWindow belongs to. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowAppUuid: string; + /** + * The name of the targetWindow. The target window is the window that was passed into (merge/join) group(s). + */ + targetWindowName: string; + type: "group-changed"; + } + + interface WindowOfGroupInfo { + /** + * The UUID of the application this window entry belongs to. + */ + appUuid: string; + /** + * The name of this window entry. + */ + windowName: string; + } + + interface WindowHiddenEvent extends WindowBaseEvent { + /** + * What action prompted the close. + * The reasons are: "hide", "hide-on-close" + */ + reason: "hide" | "hide-on-close"; + type: "hidden"; + } + + interface Window_NavigationRejectedEvent { + name: string; + /** + * source of navigation window name + */ + sourceName: string; + topic: "navigation-rejected"; + /** + * Url that was not reached "http://blocked-content.url" + */ + url: string; + /** + * the UUID of the application the window belongs to. + */ + uuid: string; + } + + interface AnimationTransition { + opacity?: { + /** + * This value is clamped from 0.0 to 1.0 + */ + opacity?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'opacity' as absolute or as a delta. Defaults to false. + */ + relative?: boolean; + }; + position?: { + /** + * Defaults to the window's current left position in virtual screen coordinates. + */ + left?: number; + /** + * Defaults to the window's current top position in virtual screen coordinates. + */ + top?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'left' and 'top' as absolute or as deltas. Defaults to false. + */ + relative?: boolean; + }; + size?: { + /** + * Optional if height is present. Defaults to the window's current width. + */ + width?: number; + /** + * Optional if width is present. Defaults to the window's current height. + */ + height?: number; + /** + * The total time in milliseconds this transition should take. + */ + duration?: number; + /** + * Treat 'width' and 'height' as absolute or as deltas. Defaults to false. + */ + relative?: boolean; + }; + } + + interface AnimationOptions { + /** + * This option interrupts the current animation. When false it pushes this animation onto the end of the animation queue. + */ + interrupt?: boolean; + /** + * Transition effect. Defaults to 'ease-in-out'. + */ + tween?: OpenFinTweenType; + } + + interface WindowBounds { + /** + * the height of the window. + */ + height?: number; + /** + * left-most coordinate of the window. + */ + left?: number; + /** + * top-most coordinate of the window. + */ + top?: number; + /** + * the width of the window. + */ + width?: number; + } + + interface ExternalApplicationInfo { + parent: { + uuid: string; + name: string; + }; + } + + interface SessionChangedEvent { + /** + * the action that triggered this event: + */ + reason: "lock" + | "unlock" + | "remote-connect" + | "remote-disconnect" + | "unknown"; + topic: "system"; + type: "session-changed"; + } + + interface LaunchInfo { + launchMode: "fin-protocol" + | "fins-protocol" + | "shortcut" + | "command-line" + | "adapter" + | "other" + | string; + } + + type OpenFinTweenType = "linear" + | "ease-in" + | "ease-out" + | "ease-in-out" + | "ease-in-quad" + | "ease-out-quad" + | "ease-in-out-quad" + | "ease-in-cubic" + | "ease-out-cubic" + | "ease-in-out-cubic" + | "ease-out-bounce" + | "ease-in-back" + | "ease-out-back" + | "ease-in-out-back" + | "ease-in-elastic" + | "ease-out-elastic" + | "ease-in-out-elastic"; + + type OpenFinApplicationEventType = "closed" + | "connected" + | "crashed" + | "initialized" + | "manifest-changed" + | "not-responding" + | "out-of-memory" + | "responding" + | "run-requested" + | "started" + | "tray-icon-clicked" + | "window-alert-requested" + | "window-auth-requested" + | "window-closed" + | "window-created" + | "window-end-load" + | "window-navigation-rejected" + | "window-show-requested" + | "window-start-load"; + + type OpenFinExternalApplicationEventType = "connected" + | "disconnected"; + + type OpenFinSystemEventType = "application-closed" + | "application-crashed" + | "application-created" + | "application-started" + | "desktop-icon-clicked" + | "idle-state-changed" + | "monitor-info-changed" + | "session-changed"; + + type OpenFinWindowEventType = "auth-requested" + | "blurred" + | "bounds-changed" + | "bounds-changing" + | "close-requested" + | "closed" + | "disabled-frame-bounds-changed" + | "disabled-frame-bounds-changing" + | "embedded" + | "external-process-exited" + | "external-process-started" + | "focused" + | "frame-disabled" + | "frame-enabled" + | "group-changed" + | "hidden" + | "initialized" + | "maximized" + | "minimized" + | "navigation-rejected" + | "restored" + | "show-requested" + | "shown"; + + type OpenFinAnchor = "top-left" + | "top-right" + | "bottom-left" + | "bottom-right"; +} diff --git a/types/openfin/v34/openfin-tests.ts b/types/openfin/v34/openfin-tests.ts new file mode 100644 index 0000000000..6059f54de7 --- /dev/null +++ b/types/openfin/v34/openfin-tests.ts @@ -0,0 +1,800 @@ +function test_application() { + let application: fin.OpenFinApplication; + // constructor + application = new fin.desktop.Application({ + url: "application.html", + uuid: "74BED629-2D8E-4141-8582-73E364BDFA74", + name: "Application Name", + plugins: false, + mainWindowOptions: { + defaultHeight: 600, + defaultWidth: 800, + defaultTop: 300, + defaultLeft: 300, + autoShow: true + } + }, (successObj) => { + console.log("Application successfully created, HTTP response code:", successObj); + application.run(); + }, (error) => { + console.log("Error creating application:", error); + }); + // createFromManifest + fin.desktop.Application.createFromManifest("http://stuf.com/app.json", (app) => { + console.log(app.uuid); + }, err => console.log(err)); + // getCurrent + application = fin.desktop.Application.getCurrent(); + // wrap + application = fin.desktop.Application.wrap("454C7F31-A915-4EA2-83F2-CFA655453C52"); + // getWindow + application.getWindow(); + // addEventListener + application.addEventListener("closed", (event) => { + console.log("The application has closed"); + }, () => { + console.log("The registration was successful"); + }, reason => { + console.log("failure: " + reason); + }); + // close + application.close(); + // getChildWindows + application.getChildWindows(children => { + children.forEach(childWindow => { + console.log("Showing child: " + childWindow.name); + childWindow.show(); + }); + }); + // getGroups + application.getGroups(allGroups => { + console.log(`There are a total of ${allGroups.length} groups.`); + + let groupCounter = 1; + allGroups.forEach(windowGroup => { + console.log(`Group ${groupCounter} contains ${windowGroup.length} windows.`); + ++groupCounter; + }); + }); + // getManifest + application.getManifest(manifest => { + console.log("Application manifest:"); + console.log(manifest); + }); + // getParentUuid + application.getParentUuid(parentUuid => { + console.log("UUID of parent application:"); + console.log(parentUuid); + }); + // getShortcuts + application.getShortcuts(config => { + console.log("Desktop shortcut is enabled: ", config.desktop); + console.log("Start Menu shortcut is enabled: ", config.startMenu); + console.log("System Startup shortcut is enabled: ", config.systemStartup); + }); + // getInfo + application.getInfo(info => { + console.log(`Launch mode: ${info.launchMode}`); + }); + // getTrayIconInfo + application.getTrayIconInfo(info => { + console.log(info.x, info.y, info.bounds.x, info.bounds.y, info.bounds.height, info.bounds.width, + info.monitorInfo.type, info.monitorInfo.reason); + }); + // isRunning + application.isRunning(running => { + console.log("the application is", running ? "running" : "not running"); + }); + // registerCustomData + application.registerUser("a", "b", () => console.log("done"), err => console.log(err)); + // removeEventListener + application.removeEventListener("closed", (event: any) => { + console.log(event); + }, () => { + console.log("The unregistration was successful"); + }, err => { + console.log("failure:", err); + }); + // removeTrayIcon + application.removeTrayIcon(() => { + console.log("Removed the tray icon."); + }, err => { + console.log("failure:", err); + }); + // restart + application.restart(() => { + console.log("You will not read this."); + }, err => { + console.log("failure:", err); + }); + // schedule restart + application.scheduleRestart(() => { + console.log("You will not read this."); + }, err => { + console.log("failure:", err); + }); + // setShortcuts + application.setShortcuts({ + desktop: true, + startMenu: false, + systemStartup: true + }, () => { + console.log("Successfully set new shortcut states"); + }, error => { + console.log("Failed to set new shortcut states. Error: ", error); + }); + // setTrayIcon + application.setTrayIcon("https://developer.openf.in/download/openfin.png", clickInfo => { + console.log(`The mouse has clicked at (${clickInfo.x}, ${clickInfo.y})`); + }); + // terminate + application.terminate(); + // wait + application.addEventListener("not-responding", () => { + console.log("waiting for hung application"); + application.wait(); + }); + // uuid + const hasUuid = application.uuid; +} + +function test_external_application() { + let externalApp: fin.OpenFinExternalApplication; + // wrap + externalApp = fin.desktop.ExternalApp.wrap('my-uuid'); + // addEventListener + externalApp.addEventListener('connected', () => { + console.log('external app connected'); + }, () => { + console.log('The registration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + // removeEventListener + const previousCallback = () => { }; + externalApp.removeEventListener('connected', previousCallback, () => { + console.log('The unregistration was successful'); + }, (reason, err) => { + console.log(`Error Message: ${err.message} Error Stack: ${err.stack}`); + }); + + // getInfo + externalApp.getInfo(info => { + console.log(info.parent.uuid, info.parent.name); + }, err => console.log(err)); +} + +function test_inter_application_bus() { + // addSubscribeListener + fin.desktop.InterApplicationBus.addSubscribeListener((uuid, topic, name) => { + console.log(`The application ${uuid} has subscribed to ${topic}`); + }); + // addUnsubscribeListener + fin.desktop.InterApplicationBus.addUnsubscribeListener((uuid, topic, name) => { + console.log(`The application ${uuid} has unsubscribed to ${topic}`); + }); + // removeSubscribeListener + const aRegisteredListener = (uuid: string, topic: string, name: string) => { }; + fin.desktop.InterApplicationBus.removeSubscribeListener(aRegisteredListener); + // removeUnsubscribeListener + fin.desktop.InterApplicationBus.removeUnsubscribeListener(aRegisteredListener); + // publish + fin.desktop.InterApplicationBus.publish("a topic", { + field1: "value1", + field2: "value2" + }); + // send + fin.desktop.InterApplicationBus.send("an application's uuid", "a topic", { + field1: "value1", + field2: "value2" + }); + // subscribe + fin.desktop.InterApplicationBus.subscribe("*", "a topic", (message, uuid, name) => { + console.log(`The application ${uuid} sent this message: ${message}`); + }); + // unsubscribe + const aRegisteredMessageListener = (message: any, senderUuid: string) => { + console.log(message, senderUuid); + }; + fin.desktop.InterApplicationBus.unsubscribe("*", "a topic", aRegisteredMessageListener); +} + +function test_notification() { + let notification: fin.OpenFinNotification; + // getCurrent + notification = fin.desktop.Notification.getCurrent(); + // close + notification.close(); + // sendMessage + notification = new fin.desktop.Notification({ + duration: 10, + url: "http://localhost:5000/Account/Register", + message: "Hello", + onShow: () => { }, + // onClose: () => { }, + onDismiss: () => { }, + // onClick: () => { }, + onMessage: () => { }, + onError: () => { } + }); + // sendMessageToApplication + notification.sendMessageToApplication("some message"); +} + +function test_system() { + // addEventListener + fin.desktop.System.addEventListener('monitor-info-changed', event => { + console.log("The monitor information has changed to: ", event); + }, () => { + console.log("The registration was successful"); + }, err => { + console.log("failure: " + err); + }); + // clearCache + fin.desktop.System.clearCache({ + cache: true, + cookies: true, + localStorage: true, + appcache: true, + userData: true + }); + // deleteCacheOnExit + fin.desktop.System.deleteCacheOnExit(() => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // downloadAsset + const dirAppAsset = { + src: 'http://local:8000/dir.zip', + alias: 'dirApp', + version: '1.23.24', + target: 'dir.bat', + args: '' + }; + fin.desktop.System.downloadAsset(dirAppAsset, progress => { + const downloadedPercent = Math.floor((progress.downloadedBytes / progress.totalBytes) * 100); + console.log(`Downloaded ${downloadedPercent}%`); + }, p => { + console.log(`Downlod complete, can be found on ${p.path}`); + // lets launch our application asset. + // launchDirApp(); + }, (reason, err) => { + console.log(reason, err); + }); + // downloadRuntime + fin.desktop.System.downloadRuntime({ version: '9.61.31.56' }, progress => { + console.log(progress.downloadedBytes, progress.downloadedBytes); + }, () => console.log('download complete'), err => console.error(err)); + // downloadPreloadScript + const preloadScripts = [ + { url: 'http://whatever.com/script.js' } + ]; + fin.desktop.System.downloadPreloadScripts(preloadScripts, info => { + const downloadInfo = info[0]; + console.log(downloadInfo.success, downloadInfo.url, downloadInfo.error); + }, err => { + console.log(err); + }); + // exit + fin.desktop.System.exit(() => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // flushCookieStore + fin.desktop.System.flushCookieStore(() => { + console.log('successful'); + }, err => { + console.log('failure', err); + }); + // getAllApplications + fin.desktop.System.getAllApplications(applicationInfoList => { + applicationInfoList.forEach(applicationInfo => { + console.log("Showing information for application with uuid: " + + applicationInfo.uuid); + console.log("isRunning: ", applicationInfo.isRunning); + }); + }); + // getAllExternalApplications + fin.desktop.System.getAllExternalApplications(externalAppsInfoList => { + externalAppsInfoList.forEach(appInfo => { + console.log(`External app connected to the runtime with UUID ${appInfo.uuid}`); + }); + }); + // getAllWindows + fin.desktop.System.getAllWindows(windowInfoList => { + windowInfoList.forEach(windowInfo => { + console.log("Showing information for application with uuid: ", windowInfo.uuid); + console.log("Main window: ", windowInfo.mainWindow); + console.log("Child windows: ", windowInfo.childWindows); + }); + }); + // getAppAssetInfo + fin.desktop.System.getAppAssetInfo({ alias: 'myAppAsset' }, info => { + console.log(info.alias, info.args, info.mandatory, info.src, info.target, info.version); + }, err => console.log(err)); + // getCommandLineArguments + fin.desktop.System.getCommandLineArguments(args => { + console.log("The command line arguments are " + args); + }); + // getCookieInfo + fin.desktop.System.getCookies({ name: 'myCookie1'}, cookies => { + const cookie1 = cookies[0]; + console.log(cookie1.name, cookie1.domain, cookie1.path); + }, err => console.log(err)); + // getDeviceId + fin.desktop.System.getDeviceId(id => { + console.log("The id of the device is: " + id); + }); + // getDeviceUserId + fin.desktop.System.getDeviceUserId(id => console.log(id), err => console.error(err)); + // getEntityInfo + fin.desktop.System.getEntityInfo('uuid', 'name', info => { + console.log(info.entityType, info.name, info.uuid, info.parent.name, info.parent.uuid); + }, err => console.log(err)); + // getEnvironmentVariable + fin.desktop.System.getEnvironmentVariable("APPDATA", variable => { + console.log("this is the APPDATA value", variable); + }); + // getFocusedWindow + fin.desktop.System.getFocusedWindow(win => { + console.log(win.uuid, win.name); + }, err => console.log(err)); + // getHostSpecs + fin.desktop.System.getHostSpecs(info => { + console.log(info); + }, error => { + console.log('There was an error:', error); + }); + // getLog + fin.desktop.System.getLog('debug-2015-01-08-22-27-53.log', log => { + console.log(log); + }); + // getLogList + fin.desktop.System.getLogList(logList => { + logList.forEach(logInfo => { + console.log(`The filename of the log is ${logInfo.name}, the size is ${logInfo.size}, and the date of creation is ${logInfo.date}`); + }); + }); + // getMinLogLevel + fin.desktop.System.getMinLogLevel(level => console.log(level), err => console.log(err)); + // getMonitorInfo + fin.desktop.System.getMonitorInfo(monitorInfo => { + console.log("This object contains information about all monitors: ", monitorInfo); + }); + // getMousePosition + fin.desktop.System.getMousePosition(mousePosition => { + console.log(`The mouse is located at left: ${mousePosition.left}, top: ${mousePosition.top}`); + }); + // getProcessList + fin.desktop.System.getProcessList(list => { + list.forEach(process => { + console.log(`UUID: ${process.uuid}, Application Name: ${process.name}`); + }); + }); + // getProxySettings + fin.desktop.System.getProxySettings(proxy => { + console.log(proxy); + }); + // getRvmInfo + fin.desktop.System.getRvmInfo(rvmInfoObject => { + console.log("RVM version:", rvmInfoObject.version); + console.log("RVM has been running since:", rvmInfoObject["start-time"]); + }, err => { + console.log("Failed to get rvm info, error message:", err); + }); + // getVersion + fin.desktop.System.getVersion(version => { + console.log("The version is " + version); + }); + // launchExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // launch external process with an alias + fin.desktop.System.launchExternalProcess({ + // Additionally note that the executable found in the zip file specified in appAssets + // will default to the one mentioned by appAssets.target + // If the the path below refers to a specific path it will override this default + alias: "myApp", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + alias: "myApp", + arguments: "e f g", + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // + fin.desktop.System.launchExternalProcess({ + path: "C:\Users\ExampleUser\AppData\Local\OpenFin\OpenFinRVM.exe", + arguments: "--version", + certificate: { + trusted: true, + subject: 'O=OpenFin INC., L=New York, S=NY, C=US', + thumbprint: '3c a5 28 19 83 05 fe 69 88 e6 8f 4b 3a af c5 c5 1b 07 80 5b' + }, + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log('Success:', payload.uuid); + }, error => { + console.log('Error:', error); + }); + // log + fin.desktop.System.log("info", "An example log message", () => { + console.log("message successfully logged"); + }, err => { + console.log(err); + }); + // monitorExternalProcess + fin.desktop.System.monitorExternalProcess({ + pid: 2508, + listener(result) { + console.log('the exit code', result.exitCode); + } + }, payload => { + console.log("The process is now being monitored: ", payload.uuid); + }, error => { + console.log("Error:", error); + }); + // openUrlWithBrowser + fin.desktop.System.openUrlWithBrowser("https://developer.openf.in/", () => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // readRegistryValue + fin.desktop.System.readRegistryValue('HKEY_SOMETHING', 'HARDWARE\\SOMETHING', 'BootSomething', info => { + console.log(info.data, info.rootKey, info.subkey, info.type, info.value); + }, err => console.log(err)); + // registerExternalConnection + fin.desktop.System.registerExternalConnection("remote-connection-uuid", (...args: any[]) => { + console.log(args); + }); + // releaseExternalProcess + fin.desktop.System.launchExternalProcess({ + path: "notepad", + arguments: "", + listener(result) { + console.log("The exit code", result.exitCode); + } + }, result => { + console.log("Result UUID is " + result.uuid); + + // release it. + fin.desktop.System.releaseExternalProcess(result.uuid, () => { + console.log("Process has been unmapped!"); + }, reason => { + console.log("failure: " + reason); + }); + }); + // removeEventListener + fin.desktop.System.removeEventListener("monitor-info-changed", (event) => { + console.log(event); + }, () => { + console.log("successful"); + }, (err: any) => { + console.log("failure: " + err); + }); + // setMinLogLevel + fin.desktop.System.setMinLogLevel("log level", () => console.log('Success'), (err: any) => console.error(err)); + // showDeveloperTools + fin.desktop.System.showDeveloperTools("uuid", "name", () => { + console.log("successful"); + }, err => { + console.log("failure: " + err); + }); + // terminateExternalProcess + fin.desktop.System.launchExternalProcess({ + // notepad is in the system's PATH + path: "notepad", + arguments: "", + listener(result) { + console.log("The exit code", result.exitCode); + } + }, result => { + console.log("Result UUID is " + result.uuid); + + // Attempt to close the process. Terminate after 4 seconds if it + // has not done so. + fin.desktop.System.terminateExternalProcess(result.uuid, 4000, info => { + console.log("Termination result " + info.result); + }, reason => { + console.log("failure: " + reason); + }); + }); + // updateProxySettings + fin.desktop.System.updateProxySettings("type", "proxyAddress", 8080, () => { + console.log('success'); + }, err => { + console.log(err); + }); +} + +function test_system_clipboard() { + // availableFormats + fin.desktop.System.Clipboard.availableFormats(null, formats => { + formats.forEach(format => console.log(`The format ${format} is available to read`)); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readHtml + fin.desktop.System.Clipboard.readHtml(null, html => { + console.log(`This is the html from the clipboard: ${html}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readRtf + fin.desktop.System.Clipboard.readRtf(null, rtf => { + console.log(`This is the rtf from the clipboard: ${rtf}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // readText + fin.desktop.System.Clipboard.readText(null, text => { + console.log(`This is the text from the clipboard: ${text}`); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // write + fin.desktop.System.Clipboard.write({ + text: 'Hello Text!', + html: '

          Hello Html

          ', + rtf: 'Hello Rtf' + }, null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeHtml + fin.desktop.System.Clipboard.writeHtml('

          Hello World

          ', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeRtf + fin.desktop.System.Clipboard.writeRtf('Hello World!', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); + // writeText + fin.desktop.System.Clipboard.writeText('Hello World', null, () => { + console.log('Success!!'); + }, (reason, err) => { + console.log(`Error while reading the clipboard Message: ${err.message}, Stack: ${err.stack}`); + }); +} + +function test_window() { + let finWindow: fin.OpenFinWindow; + // constructor + finWindow = new fin.desktop.Window({ + name: "childWindow", + url: "child.html", + defaultWidth: 320, + defaultHeight: 320, + defaultTop: 10, + defaultLeft: 300, + frame: false, + resizable: false, + state: "normal" + }, () => { + const _win = finWindow.getNativeWindow(); + _win.addEventListener("DOMContentLoaded", () => { finWindow.show(); }); + }, error => { + console.log("Error creating window:", error); + }); + // getCurrent + finWindow = fin.desktop.Window.getCurrent(); + // getNativeWindow + let nativeWindow: Window; + nativeWindow = finWindow.getNativeWindow(); + // getParentApplication + let parentApp: fin.OpenFinApplication; + parentApp = finWindow.getParentApplication(); + // getParentWindow + let parentFinWindow: fin.OpenFinWindow; + parentFinWindow = finWindow.getParentWindow(); + // wrap + finWindow = fin.desktop.Window.wrap("uuid", "name"); + // addEventListener + finWindow.addEventListener("bounds-changed", event => { + console.log("The window has been moved or resized"); + }, () => { + console.log("The registration was successful"); + }, reason => { + console.log("failure:" + reason); + }); + // animate + finWindow.animate({ + opacity: { + opacity: 0.15, + duration: 1000 + }, + position: { + left: 10, + top: 10, + duration: 3000 + } + }, { + interrupt: false + }, evt => { + // Callback will only fire after both "opacity" and "position" have finished animating. + }); + // authenticate + finWindow.addEventListener('auth-requested', evt => { + finWindow.authenticate('userName', 'P@assw0rd', () => { }, (reason, err) => { + console.log("failure:", err); + }); + }); + // blur + finWindow.blur(); + // bringToFront + finWindow.bringToFront(); + // close + finWindow.close(); + // disableFrame + finWindow.disableFrame(); + // enableFrame + finWindow.enableFrame(); + // flash + finWindow.flash(); + // focus + finWindow.focus(); + // getBounds + finWindow.getBounds(bounds => { + console.log(`top: ${bounds.top} left: ${bounds.left} height: ${bounds.height} width: ${bounds.width}`); + }); + // getOptions + finWindow.getOptions(options => { + console.log(options); + }); + // getSnapshot + finWindow.getSnapshot(base64Snapshot => { + console.log("data:image/png;base64," + base64Snapshot); + }); + // getState + finWindow.getState(state => { + console.log("state: " + state); + }); + // getZoomLevel + finWindow.getZoomLevel(level => { + console.log("zoom level: " + level); + }, error => { + console.log('error:', error); + }); + // hide + finWindow.hide(); + // isShowing + finWindow.isShowing(showing => { + console.log("the window is " + (showing ? "showing" : "hidden")); + }); + // joinGroup + let secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, () => { + // When mainWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow); + }); + // leaveGroup + secondWindow = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "secondWindow", + autoShow: true + }, () => { + // When finWindow moves or is moved, secondWindow moves by the same amount + secondWindow.joinGroup(finWindow, () => { + // once we are in the group, lets leave it. + secondWindow.leaveGroup(); + }); + }); + // maximize + finWindow.maximize(); + // mergeGroups + { + const finWindowOne = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowOne", + autoShow: true + }); + const finWindowTwo = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowTwo", + autoShow: true + }); + const finWindowThree = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowThree", + autoShow: true + }); + const finWindowFour = new fin.desktop.Window({ + url: "http://www.openfin.co", + name: "finWindowFour", + autoShow: true + }); + // When finWindowOne moves or is moved, finWindowTwo moves by the same amount + finWindowOne.joinGroup(finWindowTwo); + // When finWindowThree moves or is moved, finWindowFour moves by the same amount + finWindowThree.joinGroup(finWindowFour); + // finWindowOne, finWindowTwo, finWindowThree, and finWindowFour now move together in the same group + finWindowOne.mergeGroups(finWindowThree); + } + // minimize + finWindow.minimize(); + // moveBy + finWindow.moveBy(10, 10); + // moveTo + finWindow.moveTo(100, 200); + // removeEventListener + finWindow.removeEventListener("bounds-changed", event => { + console.log(event); + }); + // resizeBy + finWindow.resizeBy(10, 10, "top-right"); + // resizeTo + finWindow.resizeTo(10, 10, "top-right"); + // restore + finWindow.restore(); + // setAsForeground + finWindow.setAsForeground(); + // setBounds + finWindow.setBounds(100, 200, 400, 400); + // setZoomLevel + finWindow.setZoomLevel(10); + // show + finWindow.show(); + // showAt + finWindow.showAt(10, 10, false); + // stopFlashing + finWindow.stopFlashing(); + // updateOptions + finWindow.updateOptions({ + frame: false, + maxWidth: 500 + }); +} + +function test_frame() { + // wrap + const frame = fin.desktop.Frame.wrap('uuid', 'name'); + // getCurrent + const currentFrame = fin.desktop.Frame.getCurrent(); + // addEventlistener + frame.addEventListener('event', () => console.log('on event'), () => console.log('success'), err => console.error(err)); + // removeEventListener + frame.removeEventListener('event', () => console.log('on event'), () => console.log('success'), err => console.error(err)); + // getInfo + frame.getInfo(info => { + console.log(info.uuid, info.name, info.entityType, info.parent.uuid, info.parent.name); + }, err => console.error(err)); + // getParentWindow + frame.getParentWindow(parent => { + console.log(parent.uuid, parent.name, parent.entityType, parent.parent.uuid, parent.parent.name); + }, err => console.error(err)); +} diff --git a/types/openfin/v34/tsconfig.json b/types/openfin/v34/tsconfig.json new file mode 100644 index 0000000000..c446671530 --- /dev/null +++ b/types/openfin/v34/tsconfig.json @@ -0,0 +1,86 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "types": [], + "paths": { + "openfin": [ + "openfin/v34" + ] + }, + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "openfin-tests.ts", + "_v2/api/application/application.d.ts", + "_v2/api/base.d.ts", + "_v2/api/clipboard/clipboard.d.ts", + "_v2/api/clipboard/write-request.d.ts", + "_v2/api/external-application/external-application.d.ts", + "_v2/api/fin.d.ts", + "_v2/api/frame/frame.d.ts", + "_v2/api/global-hotkey/index.d.ts", + "_v2/api/interappbus/channel/channel.d.ts", + "_v2/api/interappbus/channel/client.d.ts", + "_v2/api/interappbus/channel/index.d.ts", + "_v2/api/interappbus/channel/provider.d.ts", + "_v2/api/interappbus/interappbus.d.ts", + "_v2/api/notification/notification.d.ts", + "_v2/api/system/application.d.ts", + "_v2/api/system/clearCacheOption.d.ts", + "_v2/api/system/cookie.d.ts", + "_v2/api/system/crashReporterOption.d.ts", + "_v2/api/system/download-asset.d.ts", + "_v2/api/system/download-preload.d.ts", + "_v2/api/system/entity.d.ts", + "_v2/api/system/external-process.d.ts", + "_v2/api/system/host-specs.d.ts", + "_v2/api/system/log.d.ts", + "_v2/api/system/monitor.d.ts", + "_v2/api/system/point.d.ts", + "_v2/api/system/process.d.ts", + "_v2/api/system/proxy.d.ts", + "_v2/api/system/registry-info.d.ts", + "_v2/api/system/runtime-info.d.ts", + "_v2/api/system/rvm.d.ts", + "_v2/api/system/system.d.ts", + "_v2/api/system/window.d.ts", + "_v2/api/window/bounds-changed.d.ts", + "_v2/api/window/bounds.d.ts", + "_v2/api/window/transition.d.ts", + "_v2/api/window/window.d.ts", + "_v2/environment/environment.d.ts", + "_v2/environment/node-env.d.ts", + "_v2/environment/openfin-env.d.ts", + "_v2/environment/openfin-renderer-api.d.ts", + "_v2/identity.d.ts", + "_v2/launcher/launcher.d.ts", + "_v2/launcher/nix-launch.d.ts", + "_v2/launcher/util.d.ts", + "_v2/launcher/win-launch.d.ts", + "_v2/main.d.ts", + "_v2/of-main.d.ts", + "_v2/transport/elipc.d.ts", + "_v2/transport/port-discovery.d.ts", + "_v2/transport/transport-errors.d.ts", + "_v2/transport/transport.d.ts", + "_v2/transport/websocket.d.ts", + "_v2/transport/wire.d.ts", + "_v2/util/normalize-config.d.ts", + "_v2/util/promises.d.ts", + "_v2/util/ref-counter.d.ts" + ] +} diff --git a/types/openfin/v34/tslint.json b/types/openfin/v34/tslint.json new file mode 100644 index 0000000000..f95a4974aa --- /dev/null +++ b/types/openfin/v34/tslint.json @@ -0,0 +1,18 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + "max-line-length": false, + "no-redundant-jsdoc-2": false, + "jsdoc-format": false, + "no-var-keyword": false, + "whitespace": false, + "semicolon": false, + "strict-export-declare-modifiers": false, + "array-type": false, + "unified-signatures": false, + "void-return": false, + "ban-types": false, + "callable-types": false, + "no-const-enum": false + } +} diff --git a/types/openjscad/index.d.ts b/types/openjscad/index.d.ts index 56026967a2..4a4f84c5b4 100644 --- a/types/openjscad/index.d.ts +++ b/types/openjscad/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/joostn/OpenJsCad // Definitions by: Dan Marshall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 /// diff --git a/types/openjscad/tslint.json b/types/openjscad/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/openjscad/tslint.json +++ b/types/openjscad/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/openlayers/index.d.ts b/types/openlayers/index.d.ts index 3214bad15c..b0356122e4 100644 --- a/types/openlayers/index.d.ts +++ b/types/openlayers/index.d.ts @@ -12494,6 +12494,7 @@ export namespace olx { renderer?: (ol.RendererType | Array<(ol.RendererType | string)> | string); target?: (Element | string); view?: ol.View; + moveTolerance?: number; } /** diff --git a/types/openlayers/openlayers-tests.ts b/types/openlayers/openlayers-tests.ts index d631a9e9bb..9fb6f0bb3b 100644 --- a/types/openlayers/openlayers-tests.ts +++ b/types/openlayers/openlayers-tests.ts @@ -175,7 +175,7 @@ loadingStrategy = ol.loadingstrategy.tile(tilegrid); // ol.geom.Circle // booleanValue = circle.intersectsExtent(extent); -circle = circle.transform(projectionLike, projectionLike); +circle = circle.transform(projectionLike, projectionLike) as ol.geom.Circle; // // diff --git a/types/openpgp/index.d.ts b/types/openpgp/index.d.ts index b671f8484e..81b28c36a8 100644 --- a/types/openpgp/index.d.ts +++ b/types/openpgp/index.d.ts @@ -1,8 +1,9 @@ -// Type definitions for openpgp 4.0.0 +// Type definitions for openpgp 4.0.1 // Project: http://openpgpjs.org/ // Definitions by: Guillaume Lacasa // Errietta Kostala // Daniel Montesinos +// Carlos Villavicencio // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export as namespace openpgp; @@ -269,7 +270,17 @@ export namespace cleartext { verify(keys: Array): Array; } - function readArmored(armoredText: string): CleartextMessage; + /** creates new message object from binary data + @param bytes + */ + function fromBinary(bytes: string): CleartextMessage; + + /** creates new message object from text + @param text + */ + function fromText(text: string): CleartextMessage; + + function readArmored(armoredText: string): Promise; } export namespace config { @@ -514,7 +525,7 @@ export namespace key { @param armoredText text to be parsed */ - function readArmored(armoredText: string): KeyResult; + function readArmored(armoredText: string): Promise; } export namespace message { @@ -580,7 +591,7 @@ export namespace message { @param armoredText text to be parsed */ - function readArmored(armoredText: string): Message; + function readArmored(armoredText: string): Promise; /** * reads an OpenPGP message as byte array and returns a message object diff --git a/types/openpgp/openpgp-tests.ts b/types/openpgp/openpgp-tests.ts index bb34505055..e0495520e4 100644 --- a/types/openpgp/openpgp-tests.ts +++ b/types/openpgp/openpgp-tests.ts @@ -19,27 +19,51 @@ openpgp.generateKey(options).then(function (keypair) { var spubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----'; -var publicKey = openpgp.key.readArmored(spubkey); -openpgp.encrypt({ - message: openpgp.message.fromText('Hello, World!'), - publicKeys: publicKey.keys -}).then(function (pgpMessage) { +openpgp.key.readArmored(spubkey) + .then(function (publicKey) { + return { + message: openpgp.message.fromText('Hello, World!'), + publicKeys: publicKey.keys + }; + }) + .then(openpgp.encrypt) + .then(function (pgpMessage) { + // success + }) + .catch(function (error) { + // failure + }); + +var sprivkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----'; +var pgpMessageStr = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'; + +openpgp.message.readArmored(pgpMessageStr).then(function(pgpMessage) { + const options = { + message: pgpMessage + }; + return openpgp.decrypt(options); +}).then(function (plaintext) { // success }).catch(function (error) { // failure }); -var sprivkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----'; -var privateKey = openpgp.key.readArmored(sprivkey).keys[0]; -privateKey.decrypt('passphrase'); +const promises: [Promise, Promise] = [ + openpgp.key.readArmored(sprivkey), + openpgp.message.readArmored(pgpMessageStr) +]; -var pgpMessageStr = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'; -var pgpMessage = openpgp.message.readArmored(pgpMessageStr); - -openpgp.decrypt({ - privateKeys: privateKey, - message: pgpMessage +Promise.all(promises).then(function (values) { + const keyObject: openpgp.key.KeyResult = values[0]; + const pgpMessage: openpgp.message.Message = values[1]; + const privateKey = keyObject.keys[0]; + privateKey.decrypt('passphrase'); + const options = { + privateKeys: privateKey, + message: pgpMessage + }; + return openpgp.decrypt(options); }).then(function (plaintext) { // success }).catch(function (error) { 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/opossum/index.d.ts b/types/opossum/index.d.ts new file mode 100644 index 0000000000..e79a9c4bba --- /dev/null +++ b/types/opossum/index.d.ts @@ -0,0 +1,75 @@ +// Type definitions for opossum 1.9 +// Project: https://github.com/nodeshift/opossum +// Definitions by: Quinn Langille +// Willy Zhang +// Lance Ball +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import * as stream from "stream"; +import { EventEmitter } from "events"; + +export type Action = (...args: any[]) => any; + +export class CircuitBreaker extends EventEmitter { + clearCache(): void; + close(): void; + disable(): void; + enable(): void; + fallback(func?: (...args: any[]) => any): this; + fire(...args: any[]): Promise; + healthCheck(func: (...args: any[]) => Promise, interval?: number): Promise; + on(event: string | symbol, listener: (...args: any[]) => void): this; + open(): void; + promisify(action: Action): Promise; + stats(): stream.Transform; + + static readonly name: symbol; + static readonly group: symbol; + static readonly pendingClose: symbol; + static readonly closed: symbol; + static readonly opened: symbol; + static readonly halfOpen: symbol; + static readonly status: symbol; + static readonly hystrixStats: symbol; + static readonly enabled: symbol; + static readonly warmUp: symbol; + static readonly volumeThreshold: symbol; +} + +export enum Event { + cacheHit = 'cacheHit', + cacheMiss = 'cacheMiss', + close = 'close', + failure = 'failure', + fallback = 'fallback', + fire = 'fire', + halfOpen = 'halfOpen', + healthCheckFailed = 'health-check-failed', + open = 'open', + reject = 'reject', + semaphoreLocked = 'semaphore-locked', + success = 'success', + timeout = 'timeout' +} + +export interface CircuitBreakerOptions { + timeout?: number; + maxFailures?: number; + resetTimeout?: number; + rollingCountTimeout?: number; + rollingCountBuckets?: number; + name?: string; + rollingPercentilesEnabled?: boolean; + capacity?: number; + errorThresholdPercentage?: number; + enabled?: boolean; + allowWarmUp?: boolean; + volumeThreshold?: number; +} + +export default function circuitBreaker( + action: Action, + options?: CircuitBreakerOptions +): CircuitBreaker; diff --git a/types/opossum/opossum-tests.ts b/types/opossum/opossum-tests.ts new file mode 100644 index 0000000000..9ec5425416 --- /dev/null +++ b/types/opossum/opossum-tests.ts @@ -0,0 +1,48 @@ +import { Transform } from "stream"; +import circuitBreaker, { CircuitBreaker, CircuitBreakerOptions } from "opossum"; + +const _blank = () => {}; +const async_blank = () => new Promise(resolve => null); + +const testNoOptions: CircuitBreaker = circuitBreaker(_blank); + +const options: CircuitBreakerOptions = { + timeout: 1, + maxFailures: 1, + resetTimeout: 1, + rollingCountTimeout: 1, + rollingCountBuckets: 1, + name: "testing", + rollingPercentilesEnabled: true, + capacity: 1, + errorThresholdPercentage: 1, + enabled: true, + allowWarmUp: true, + volumeThreshold: 1 +}; + +const testWithOptions: CircuitBreaker = circuitBreaker(_blank, options); +const shouldBeAPromise: Promise = testWithOptions.promisify(_blank); +const shouldBeATransformStream: Transform = testWithOptions.stats(); + +const healthCheck: Promise = testWithOptions.healthCheck(async_blank, 8); +const shouldBeACircuitBreaker: CircuitBreaker = testWithOptions.fallback(); +const shouldBeAPromiseGeneric: Promise = testWithOptions.fire(); + +const shouldBeVoid = (): void => testWithOptions.enable(); +const shouldBeVoid2 = (): void => testWithOptions.disable(); +const shouldBeVoid3 = (): void => testWithOptions.close(); +const shouldBeVoid4 = (): void => testWithOptions.open(); +const shouldBeVoid5 = (): void => testWithOptions.clearCache(); + +const shouldBeSymbol: symbol = CircuitBreaker.name; +const shouldBeSymbol2: symbol = CircuitBreaker.group; +const shouldBeSymbol3: symbol = CircuitBreaker.pendingClose; +const shouldBeSymbol4: symbol = CircuitBreaker.closed; +const shouldBeSymbol5: symbol = CircuitBreaker.opened; +const shouldBeSymbol6: symbol = CircuitBreaker.halfOpen; +const shouldBeSymbol7: symbol = CircuitBreaker.hystrixStats; +const shouldBeSymbol8: symbol = CircuitBreaker.status; +const shouldBeSymbol9: symbol = CircuitBreaker.enabled; +const shouldBeSymbol10: symbol = CircuitBreaker.warmUp; +const shouldBeSymbol11: symbol = CircuitBreaker.volumeThreshold; diff --git a/types/opossum/tsconfig.json b/types/opossum/tsconfig.json new file mode 100644 index 0000000000..70edefe671 --- /dev/null +++ b/types/opossum/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "target": "es5", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "opossum-tests.ts" + ] +} diff --git a/types/opossum/tslint.json b/types/opossum/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/opossum/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/optics-agent/index.d.ts b/types/optics-agent/index.d.ts index 2c8ae46283..813f528af4 100644 --- a/types/optics-agent/index.d.ts +++ b/types/optics-agent/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/apollostack/optics-agent-js#readme // Definitions by: Crevil // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.4 +// TypeScript Version: 2.8 import { GraphQLSchema } from "graphql"; import { Request, Response } from "express"; diff --git a/types/optics-agent/tsconfig.json b/types/optics-agent/tsconfig.json index 046bfaad81..fe309dafd3 100644 --- a/types/optics-agent/tsconfig.json +++ b/types/optics-agent/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "esnext.asynciterable" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/osmosis/index.d.ts b/types/osmosis/index.d.ts index 4c03388047..8d9f640f8b 100644 --- a/types/osmosis/index.d.ts +++ b/types/osmosis/index.d.ts @@ -56,8 +56,33 @@ interface Osmosis { * result data, osmosis finished */ data(callback: (param: any) => any): Osmosis; - } - declare const osmosis: Osmosis; + /** + * Set configuration options for the **preceeding** command on down the chain. + */ + config(option: string | { [key: string]: any }, value?: any): Osmosis; - export = osmosis; + /** + * Set a cookie. Short for `.config({ cookies: ... })`. Note: Setting a cookie to `null` will delete the cookie. + */ + cookie(name: string, value: string | null): Osmosis; + + /** + * Set an HTTP header. Short for `.config({ headers: ... })` + */ + header(name: string, value: string): Osmosis; + + /** + * Set multiple HTTP headers. Short for `.config({ headers: ... })`. + */ + headers(headers: { [key: string]: string }): Osmosis; + + /** + * Call a callback when the Osmosis instance has completely finished. + */ + done(callback: () => any): Osmosis; +} + +declare const osmosis: Osmosis; + +export = osmosis; diff --git a/types/osmosis/osmosis-tests.ts b/types/osmosis/osmosis-tests.ts index f0c39d4312..94f08db15e 100644 --- a/types/osmosis/osmosis-tests.ts +++ b/types/osmosis/osmosis-tests.ts @@ -12,9 +12,15 @@ const errorFunction = (error: string) => { const myError = error; }; -// example is from https://github.com/rchipka/node-osmosis#example +const doneFunction = () => {}; + +// modified example from https://github.com/rchipka/node-osmosis#example osmosis + .config({ headers: { 'test-header-name': 'test-header-value' } }) + .headers({ 'test-header-name': 'test-header-value' }) + .header('test-header-name', 'test-header-value') + .cookie('test-cookie-name', 'test-cookie-value') .get('www.craigslist.org/about/sites') .find('h1 + div a') .set('location') @@ -39,4 +45,5 @@ osmosis }) .log(logFunction) .error(errorFunction) - .debug(debugFunction); + .debug(debugFunction) + .done(doneFunction); 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/p-loading/tsconfig.json b/types/p-loading/tsconfig.json index 09fd52fdda..6f45b638aa 100644 --- a/types/p-loading/tsconfig.json +++ b/types/p-loading/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/p-queue/index.d.ts b/types/p-queue/index.d.ts index 568de0ca1d..10c1179815 100644 --- a/types/p-queue/index.d.ts +++ b/types/p-queue/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for p-queue 2.3 +// Type definitions for p-queue 3.0 // Project: https://github.com/sindresorhus/p-queue#readme // Definitions by: BendingBender // Evan Shortiss @@ -93,6 +93,9 @@ declare namespace PQueue { concurrency?: number; autoStart?: boolean; queueClass?: QueueClassConstructor; + intervalCap?: number; + interval?: number; + carryoverConcurrencyCount?: boolean; } interface DefaultAddOptions { diff --git a/types/p-queue/v2/index.d.ts b/types/p-queue/v2/index.d.ts new file mode 100644 index 0000000000..568de0ca1d --- /dev/null +++ b/types/p-queue/v2/index.d.ts @@ -0,0 +1,103 @@ +// Type definitions for p-queue 2.3 +// Project: https://github.com/sindresorhus/p-queue#readme +// Definitions by: BendingBender +// Evan Shortiss +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +export = PQueue; + +declare class PQueue { + /** + * Size of the queue. + */ + size: number; + + /** + * Number of pending promises. + */ + pending: number; + + /** + * Whether the queue is currently paused. + */ + isPaused: boolean; + + constructor(opts?: PQueue.Options); + + /** + * Returns the promise returned by calling fn. + * @param fn Promise-returning/async function. + */ + add(fn: PQueue.Task, opts?: O): Promise; + + /** + * Same as .add(), but accepts an array of async functions and + * returns a promise that resolves when all async functions are resolved. + * @param fn Array of Promise-returning/async functions. + */ + addAll(fns: Array>, opts?: O): Promise; + + /** + * Returns a promise that settles when the queue becomes empty. + * Can be called multiple times. Useful if you for example add + * additional items at a later time. + */ + onEmpty(): Promise; + + /** + * Returns a promise that settles when the queue becomes empty, and all + * promises have completed; queue.size === 0 && queue.pending === 0. + * The difference with .onEmpty is that .onIdle guarantees that all work + * from the queue has finished. .onEmpty merely signals that the queue is + * empty, but it could mean that some promises haven't completed yet. + */ + onIdle(): Promise; + + /** + * Start (or resume) executing enqueued tasks within concurrency limit. + * No need to call this if queue is not paused (via options.autoStart = false + * or by .pause() method.) + */ + start(): void; + + /** + * Clear the queue. + */ + clear(): void; + + /** + * Put queue execution on hold. + */ + pause(): void; +} + +declare namespace PQueue { + interface QueueAddOptions { + [key: string]: any; + } + + interface QueueClassConstructor { + new(): QueueClass; + } + + interface QueueClass { + size: number; + + enqueue(run: () => void, options?: O): void; + + dequeue(): (() => void) | undefined; + } + + interface Options { + concurrency?: number; + autoStart?: boolean; + queueClass?: QueueClassConstructor; + } + + interface DefaultAddOptions { + priority?: number; + } + + type Task = () => Promise; +} diff --git a/types/p-queue/v2/p-queue-tests.ts b/types/p-queue/v2/p-queue-tests.ts new file mode 100644 index 0000000000..fcd48c852d --- /dev/null +++ b/types/p-queue/v2/p-queue-tests.ts @@ -0,0 +1,51 @@ +import PQueue = require("p-queue"); + +const queue = new PQueue({ concurrency: 1 }); + +queue + .add(() => Promise.resolve("sindresorhus.com")) + .then(sindre => { + const str: string = sindre; + }); + +queue.addAll([() => Promise.resolve("oh"), () => Promise.resolve("hi")]).then(r => { + r.indexOf("h"); +}); + +Promise.resolve((): Promise => Promise.resolve("unicorn")) + .then(task => queue.add(task, { priority: 5 })) + .then(unicorn => { + const str: string = unicorn; + }); + +queue.onEmpty().then(() => {}); +queue.onIdle().then(() => {}); +queue.start(); +queue.pause(); +queue.clear(); + +let num: number; +num = queue.size; +num = queue.pending; +const paused = queue.isPaused; + +class QueueClass implements PQueue.QueueClass<{ any: string }> { + private readonly queue: Array<() => void>; + + size = 0; + + constructor() { + this.queue = []; + } + + enqueue(run: () => void, options: { any: string }) { + this.queue.push(run); + } + + dequeue() { + return this.queue.shift(); + } +} + +const queue2 = new PQueue({ queueClass: QueueClass }); +queue2.add(() => Promise.resolve(), { any: "hi" }); diff --git a/types/p-queue/v2/tsconfig.json b/types/p-queue/v2/tsconfig.json new file mode 100644 index 0000000000..49d979aa06 --- /dev/null +++ b/types/p-queue/v2/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "p-queue": [ "p-queue/v2" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-queue-tests.ts" + ] +} diff --git a/types/p-queue/v2/tslint.json b/types/p-queue/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-queue/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p-wait-for/index.d.ts b/types/p-wait-for/index.d.ts index 5e8f88d413..d7fa76e016 100644 --- a/types/p-wait-for/index.d.ts +++ b/types/p-wait-for/index.d.ts @@ -1,8 +1,15 @@ -// Type definitions for p-wait-for 1.0 +// Type definitions for p-wait-for 2.0 // Project: https://github.com/sindresorhus/p-wait-for#readme // Definitions by: BendingBender // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped export = pWaitFor; -declare function pWaitFor(condition: () => PromiseLike | boolean, interval?: number): Promise; +declare function pWaitFor(condition: () => PromiseLike | boolean, options?: pWaitFor.Options): Promise; + +declare namespace pWaitFor { + interface Options { + interval?: number; + timeout?: number; + } +} diff --git a/types/p-wait-for/p-wait-for-tests.ts b/types/p-wait-for/p-wait-for-tests.ts index 587d08d5a5..ef23ef6526 100644 --- a/types/p-wait-for/p-wait-for-tests.ts +++ b/types/p-wait-for/p-wait-for-tests.ts @@ -1,6 +1,8 @@ import pWaitFor = require('p-wait-for'); pWaitFor(() => Promise.resolve(false)).then(() => {}); -pWaitFor(() => Promise.resolve(true), 1).then(() => {}); +pWaitFor(() => Promise.resolve(true), { interval: 1 }).then(() => {}); +pWaitFor(() => Promise.resolve(true), { timeout: 1 }).then(() => {}); pWaitFor(() => false).then(() => {}); -pWaitFor(() => true, 1).then(() => {}); +pWaitFor(() => true, { interval: 1 }).then(() => {}); +pWaitFor(() => true, { timeout: 1 }).then(() => {}); diff --git a/types/p-wait-for/v1/index.d.ts b/types/p-wait-for/v1/index.d.ts new file mode 100644 index 0000000000..5e8f88d413 --- /dev/null +++ b/types/p-wait-for/v1/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for p-wait-for 1.0 +// Project: https://github.com/sindresorhus/p-wait-for#readme +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pWaitFor; + +declare function pWaitFor(condition: () => PromiseLike | boolean, interval?: number): Promise; diff --git a/types/p-wait-for/v1/p-wait-for-tests.ts b/types/p-wait-for/v1/p-wait-for-tests.ts new file mode 100644 index 0000000000..587d08d5a5 --- /dev/null +++ b/types/p-wait-for/v1/p-wait-for-tests.ts @@ -0,0 +1,6 @@ +import pWaitFor = require('p-wait-for'); + +pWaitFor(() => Promise.resolve(false)).then(() => {}); +pWaitFor(() => Promise.resolve(true), 1).then(() => {}); +pWaitFor(() => false).then(() => {}); +pWaitFor(() => true, 1).then(() => {}); diff --git a/types/p-wait-for/v1/tsconfig.json b/types/p-wait-for/v1/tsconfig.json new file mode 100644 index 0000000000..2d81275cae --- /dev/null +++ b/types/p-wait-for/v1/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "p-wait-for": [ "p-wait-for/v1" ] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "p-wait-for-tests.ts" + ] +} diff --git a/types/p-wait-for/v1/tslint.json b/types/p-wait-for/v1/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/p-wait-for/v1/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/p5/lib/addons/p5.sound.d.ts b/types/p5/lib/addons/p5.sound.d.ts index 6a057b6289..faa16f7e1b 100644 --- a/types/p5/lib/addons/p5.sound.d.ts +++ b/types/p5/lib/addons/p5.sound.d.ts @@ -1990,7 +1990,7 @@ declare module "../../index" { * Reverb adds depth to a sound through a large * number of decaying echoes. It creates the * perception that sound is occurring in a physical - * space. The p5.Reverb has paramters for Time (how + * space. The p5.Reverb has parameters for Time (how * long does the reverb last) and decayRate (how much * the sound decays with each echo) that can be set * with the .set() or .process() methods. The @@ -2511,7 +2511,7 @@ declare module "../../index" { maxIterations: number; /** - * Getters and Setters, setting any paramter will + * Getters and Setters, setting any parameter will * result in a change in the clock's frequency, that * will be reflected after the next callback beats * per minute (defaults to 60) @@ -2588,7 +2588,7 @@ declare module "../../index" { ): void; /** - * Set the paramters of a compressor. + * Set the parameters of a compressor. * @param attack The amount of time (in seconds) to * reduce the gain by 10dB, default = .003, range 0 - * 1 diff --git a/types/paho-mqtt/index.d.ts b/types/paho-mqtt/index.d.ts index fed67ff262..b1fac43793 100644 --- a/types/paho-mqtt/index.d.ts +++ b/types/paho-mqtt/index.d.ts @@ -4,9 +4,9 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.1 -/// +export = Paho.MQTT; -declare namespace Paho { +declare global { /** * Send and receive messages using web browsers. *

          @@ -40,7 +40,7 @@ declare namespace Paho { * an error with any parameter. *

          */ - namespace MQTT { + namespace Paho.MQTT { /** * The Quality of Service used to deliver a message. *

          diff --git a/types/paho-mqtt/module.d.ts b/types/paho-mqtt/module.d.ts deleted file mode 100644 index 8ab421779f..0000000000 --- a/types/paho-mqtt/module.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for paho-mqtt 1.0 -// Project: https://github.com/eclipse/paho.mqtt.javascript#readme -// Definitions by: Alex Mikhalev -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -declare module 'paho-mqtt' { - export = Paho.MQTT; -} diff --git a/types/papaparse/index.d.ts b/types/papaparse/index.d.ts index 4e52dd66a4..c7246ecb1f 100644 --- a/types/papaparse/index.d.ts +++ b/types/papaparse/index.d.ts @@ -7,6 +7,7 @@ // Alberto Restifo // Behind The Math // 3af +// Janne Liuhtonen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 @@ -23,7 +24,7 @@ export function parse(file: File, config?: ParseConfig): ParseResult; export function parse(stream: NodeJS.ReadableStream, config?: ParseConfig): ParseResult; -export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadableStream; +export function parse(stream: typeof NODE_STREAM_INPUT, config?: ParseConfig): NodeJS.ReadWriteStream; /** * Unparses javascript data objects and returns a csv string diff --git a/types/papaparse/papaparse-tests.ts b/types/papaparse/papaparse-tests.ts index 5db22091ca..57115dc0d5 100644 --- a/types/papaparse/papaparse-tests.ts +++ b/types/papaparse/papaparse-tests.ts @@ -9,6 +9,7 @@ import { ParseMeta, ParseResult } from "papaparse"; +import { Readable } from "stream"; /** * Parsing @@ -40,8 +41,19 @@ Papa.parse(file, { } }); +const readable = new Readable() +const rows = [ + "1,2,3", + "4,5,6" +] -Papa.parse(Papa.NODE_STREAM_INPUT); +rows.forEach(r => { + readable.push(r); +}); + +const papaStream: NodeJS.ReadWriteStream = Papa.parse(Papa.NODE_STREAM_INPUT); + +readable.pipe(papaStream); /** * Unparsing diff --git a/types/paper/index.d.ts b/types/paper/index.d.ts index ff75266725..d3c818b112 100644 --- a/types/paper/index.d.ts +++ b/types/paper/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Paper.js v0.11.5 +// Type definitions for Paper.js v0.11.8 // Project: http://paperjs.org/ // Definitions by: Clark Stevenson , // Jon Lucas , @@ -1332,7 +1332,12 @@ declare module paper { * The path style of the item. */ style: Style; - + + /** + * Specifies whether the item is locked. When set to true, item interactions with the mouse are disabled. + */ + locked: boolean; + /** * Specifies whether the item is visible. When set to false, the item won't be drawn. */ @@ -1486,7 +1491,7 @@ declare module paper { /** * The color of the stroke. */ - strokeColor: Color | string; + strokeColor: Color | string | null; /** * The width of the stroke. @@ -1534,7 +1539,7 @@ declare module paper { /** * The fill color of the item. */ - fillColor: Color | string; + fillColor: Color | string | null; /** * The fill-rule with which the shape gets filled. Please note that only modern browsers support fill-rules other than 'nonzero'. @@ -1546,7 +1551,7 @@ declare module paper { /** * The shadow color. */ - shadowColor: Color | string; + shadowColor: Color | string | null; /** * The shadow’s blur radius. diff --git a/types/parcel-bundler/index.d.ts b/types/parcel-bundler/index.d.ts new file mode 100644 index 0000000000..c661d105cd --- /dev/null +++ b/types/parcel-bundler/index.d.ts @@ -0,0 +1,178 @@ +// Type definitions for parcel-bundler 1.10 +// Project: https://github.com/parcel-bundler/parcel#readme +// Definitions by: pinage404 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +declare namespace ParcelBundler { + interface ParcelOptions { + /** + * The out directory to put the build files in + * + * @default "./dist" + */ + outDir?: string; + /** + * The name of the outputFile + * + * @default "index.html" + */ + outFile?: string; + /** + * The url to server on + * + * @default "./" + */ + publicUrl?: string; + /** + * Whether to watch the files and rebuild them on change + * + * @default process.env.NODE_ENV !== 'production' + */ + watch?: boolean; + /** + * Enabled or disables caching + * + * @default true + */ + cache?: boolean; + /** + * The directory cache gets put in + * + * @default ".cache" + */ + cacheDir?: string; + /** + * Disable content hash from being included on the filename + * + * @default false + */ + contentHash?: boolean; + /** + * Minify files + * + * @default process.env.NODE_ENV === 'production' + */ + minify?: boolean; + /** + * Turn on experimental scope hoisting/tree shaking flag, for smaller production bundles + * + * @default false + */ + scopeHoist?: boolean; + /** + * @default "browser" + */ + target?: "browser" | "node" | "electron"; + /** + * Define a custom {key, cert} pair + * + * Use true to generate one or false to use http + */ + https?: + | true + | false + | { + /** + * Path to custom certificate + * + * @default "./ssl/c.crt" + */ + cert?: string; + /** + * Path to custom key + * + * @default "./ssl/k.key" + */ + key?: string; + }; + /** + * 3 = log everything, 2 = log warnings & errors, 1 = log errors + * + * @default 3 + */ + logLevel?: 3 | 2 | 1; + /** + * The port the HMR socket runs on + * + * Defaults to a random free port (0 in node.js resolves to a random free port) + * + * @default 0 + */ + hmrPort?: 0 | number; + /** + * Enable or disable sourcemaps + * + * Defaults to enabled (not supported in minified builds yet) + * + * @default true + */ + sourceMaps?: boolean; + /** + * A hostname for hot module reload + * + * @default "" + */ + hmrHostname?: string; + /** + * Prints a detailed report of the bundles, assets, filesizes and times + * + * Reports are only printed if watch is disabled + * + * @default false + */ + detailedReport?: boolean; + } + + type ParcelAsset = any; + + interface ParcelBundle { + /** + * The type of assets it contains (e.g. js, css, map, ...) + */ + type: string; + /** + * The name of the bundle (generated using Asset.generateBundleName() of entryAsset) + */ + name: string; + /** + * The parent bundle, is null in case of the entry bundleany + */ + parentBundle?: any; + /** + * The entryPoint of the bundle, used for generating the name and gathering assets. + */ + entryAsset: any; + /** + * A Set of all assets inside the bundle + */ + assets: Set; + /** + * A Set of all sibling bundles + */ + siblingBundles: Set; + /** + * A Map of all sibling bundles + */ + siblingBundlesMap: Map; + /** + * A Map of all the locations of the assets inside the bundle, used to generate accurate source maps + */ + offsets: Map; + } +} + +declare class ParcelBundler { + constructor( + entryFiles?: string | string[], + options?: ParcelBundler.ParcelOptions + ); + + addAssetType(extension: string, path: string): void; + + addPackager(type: string, packager: string): void; + + bundle(): Promise; +} + +export = ParcelBundler; diff --git a/types/parcel-bundler/parcel-bundler-tests.ts b/types/parcel-bundler/parcel-bundler-tests.ts new file mode 100644 index 0000000000..5833b8527b --- /dev/null +++ b/types/parcel-bundler/parcel-bundler-tests.ts @@ -0,0 +1,13 @@ +import ParcelBundler, { ParcelOptions } from "parcel-bundler"; + +const parcelOption: ParcelOptions = { watch: false }; + +const files = ["./index.d.ts"]; + +const bundler = new ParcelBundler(files, parcelOption); + +bundler.addAssetType('md', 'markdown-asset'); + +bundler.addPackager('md', 'markdown-packager'); + +bundler.bundle().then(bundle => bundle.name); diff --git a/types/parcel-bundler/tsconfig.json b/types/parcel-bundler/tsconfig.json new file mode 100644 index 0000000000..4a806c38de --- /dev/null +++ b/types/parcel-bundler/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "allowSyntheticDefaultImports": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "parcel-bundler-tests.ts"] +} diff --git a/types/parcel-bundler/tslint.json b/types/parcel-bundler/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/parcel-bundler/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/parse-mockdb/index.d.ts b/types/parse-mockdb/index.d.ts index 94a1f63bb1..e66d67a883 100644 --- a/types/parse-mockdb/index.d.ts +++ b/types/parse-mockdb/index.d.ts @@ -4,8 +4,6 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 -/// - declare namespace ParseMockDB { function mockDB(): void; function unMockDB(): void; @@ -18,5 +16,6 @@ declare namespace ParseMockDB { } declare module "parse-mockdb" { + import * as Parse from 'parse' export = ParseMockDB; } diff --git a/types/parse-mockdb/tsconfig.json b/types/parse-mockdb/tsconfig.json index 47ec90a997..6f81a1fc2a 100644 --- a/types/parse-mockdb/tsconfig.json +++ b/types/parse-mockdb/tsconfig.json @@ -13,6 +13,10 @@ "typeRoots": [ "../" ], + "paths": { + "parse": ["parse/v1"], + "parse/*": ["parse/v1/*"] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 63bc16d17a..bf89204b04 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for parse 1.11.1 +// Type definitions for parse 2.1.0 // Project: https://parseplatform.org/ // Definitions by: Ullisen Media Group // David Poetzsch-Heffter @@ -6,12 +6,11 @@ // Flavio Negrão // Wes Grimes // Otherwise SAS +// Andrew Goldis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 /// -/// -/// declare namespace Parse { @@ -67,53 +66,6 @@ declare namespace Parse { silent?: boolean; } - /** - * A Promise is returned by async methods as a hook to provide callbacks to be - * called when the async task is fulfilled. - * - *

          Typical usage would be like:

          -     *    query.find().then(function(results) {
          -     *      results[0].set("foo", "bar");
          -     *      return results[0].saveAsync();
          -     *    }).then(function(result) {
          -     *      console.log("Updated " + result.id);
          -     *    });
          -     * 

          - * - * @see Parse.Promise.prototype.then - * @class - */ - - interface IPromise { - - then(resolvedCallback: (...values: T[]) => IPromise, rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; - catch(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; - } - - class Promise implements IPromise { - - static as(resolvedValue: U): Promise; - static error(error: any): Promise; - static is(possiblePromise: any): Boolean; - static when(promises: IPromise[]): Promise; - static when(...promises: IPromise[]): Promise; - - always(callback: Function): Promise; - done(callback: Function): Promise; - fail(callback: Function): Promise; - reject(error: any): void; - resolve(result: any): void; - then(resolvedCallback: (...values: T[]) => IPromise, - rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => IPromise): IPromise; - then(resolvedCallback: (...values: T[]) => U, - rejectedCallback?: (reason: any) => U): IPromise; - catch(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; - } - interface Pointer { __type: string; className: string; @@ -251,38 +203,6 @@ declare namespace Parse { milesTo(point: GeoPoint): number; } - /** - * History serves as a global router (per frame) to handle hashchange - * events or pushState, match the appropriate route, and trigger - * callbacks. You shouldn't ever have to create one of these yourself - * — you should use the reference to Parse.history - * that will be created for you automatically if you make use of - * Routers with routes. - * @class - * - *

          A fork of Backbone.History, provided for your convenience. If you - * use this class, you must also include jQuery, or another library - * that provides a jQuery-compatible $ function. For more information, - * see the - * Backbone documentation.

          - *

          Available in the client SDK only.

          - */ - class History { - - handlers: any[]; - interval: number; - fragment: string; - - checkUrl(e?: any): void; - getFragment(fragment?: string, forcePushState?: boolean): string; - getHash(windowOverride: Window): string; - loadUrl(fragmentOverride: any): boolean; - navigate(fragment: string, options?: any): any; - route(route: any, callback: Function): void; - start(options: any): boolean; - stop(): void; - } - /** * A class that is used to access all of the children of a many-to-many relationship. * Each instance of Parse.Relation is associated with a particular parent object and key. @@ -323,14 +243,12 @@ declare namespace Parse { *

          * * @param {Object} attributes The initial set of data to store in the object. - * @param {Object} options A set of Backbone-like options for creating the - * object. The only option currently supported is "collection". + * @param {Object} options The options for this object instance. * @see Parse.Object.extend * * @class * - *

          The fundamental unit of Parse data, which implements the Backbone Model - * interface.

          + * Creates a new model with defined attributes. */ class Object extends BaseObject { @@ -430,120 +348,6 @@ declare namespace Parse { appIdentifier: string; } - - /** - * Creates a new instance with the given models and options. Typically, you - * will not call this method directly, but will instead make a subclass using - * Parse.Collection.extend. - * - * @param {Array} models An array of instances of Parse.Object. - * - * @param {Object} options An optional object with Backbone-style options. - * Valid options are:
            - *
          • model: The Parse.Object subclass that this collection contains. - *
          • query: An instance of Parse.Query to use when fetching items. - *
          • comparator: A string property name or function to sort by. - *
          - * - * @see Parse.Collection.extend - * - * @class - * - *

          Provides a standard collection class for our sets of models, ordered - * or unordered. For more information, see the - * Backbone - * documentation.

          - */ - class Collection extends Events implements IBaseObject { - - model: Object; - models: Object[]; - query: Query; - comparator: (object: Object) => any; - - constructor(models?: Object[], options?: Collection.Options); - static extend(instanceProps: any, classProps: any): any; - - initialize(): void; - add(models: any[], options?: Collection.AddOptions): Collection; - at(index: number): Object; - chain(): _._Chain>; - fetch(options?: Collection.FetchOptions): Promise; - create(model: Object, options?: Collection.CreateOptions): Object; - get(id: string): Object; - getByCid(cid: any): any; - pluck(attr: string): any[]; - remove(model: any, options?: Collection.RemoveOptions): Collection; - remove(models: any[], options?: Collection.RemoveOptions): Collection; - reset(models: any[], options?: Collection.ResetOptions): Collection; - sort(options?: Collection.SortOptions): Collection; - toJSON(): any; - } - - namespace Collection { - interface Options { - model?: Object; - query?: Query; - comparator?: string; - } - - interface AddOptions extends SilentOption { - /** - * The index at which to add the models. - */ - at?: number; - } - - interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, ScopeOptions { - } - - interface FetchOptions extends SuccessFailureOptions, SilentOption, ScopeOptions { } - - interface RemoveOptions extends SilentOption { } - - interface ResetOptions extends SilentOption { } - - interface SortOptions extends SilentOption { } - } - - /** - * @class - * - *

          Parse.Events is a fork of Backbone's Events module, provided for your - * convenience.

          - * - *

          A module that can be mixed in to any object in order to provide - * it with custom events. You may bind callback functions to an event - * with `on`, or remove these functions with `off`. - * Triggering an event fires all callbacks in the order that `on` was - * called. - * - *

          -     *     var object = {};
          -     *     _.extend(object, Parse.Events);
          -     *     object.on('expand', function(){ alert('expanded'); });
          -     *     object.trigger('expand');

          - * - *

          For more information, see the - * Backbone - * documentation.

          - */ - class Events { - - static off(events: string[], callback?: Function, context?: any): Events; - static on(events: string[], callback?: Function, context?: any): Events; - static trigger(events: string[]): Events; - static bind(): Events; - static unbind(): Events; - - on(eventName: string, callback?: Function, context?: any): Events; - off(eventName?: string | null, callback?: Function | null, context?: any): Events; - trigger(eventName: string, ...args: any[]): Events; - bind(eventName: string, callback: Function, context?: any): Events; - unbind(eventName?: string, callback?: Function, context?: any): Events; - - } - /** * Creates a new parse Parse.Query for the given Parse.Object subclass. * @param objectClass - @@ -617,7 +421,6 @@ declare namespace Parse { addDescending(key: string[]): Query; ascending(key: string): Query; ascending(key: string[]): Query; - collection(items?: Object[], options?: Collection.Options): Collection; containedIn(key: string, values: any[]): Query; contains(key: string, substring: string): Query; containsAll(key: string, values: any[]): Query; @@ -634,6 +437,7 @@ declare namespace Parse { exists(key: string): Query; find(options?: Query.FindOptions): Promise; first(options?: Query.FirstOptions): Promise; + fullText(key: string, value: string, options?: Query.FullTextOptions): Query; get(objectId: string, options?: Query.GetOptions): Promise; greaterThan(key: string, value: any): Query; greaterThanOrEqualTo(key: string, value: any): Query; @@ -651,7 +455,7 @@ declare namespace Parse { select(...keys: string[]): Query; skip(n: number): Query; startsWith(key: string, prefix: string): Query; - subscribe(): Events; + subscribe(): LiveQuerySubscription; withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query; withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query; withinMiles(key: string, point: GeoPoint, maxDistance: number): Query; @@ -675,6 +479,95 @@ declare namespace Parse { // Sort documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sort/#pipe._S_sort sort?: {[key: string]: 1|-1}; } + + // According to https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Query.html#fullText + interface FullTextOptions { + language?: string; + caseSensitive?: boolean; + diacriticSensitive?: boolean; + } + } + + /** + * Represents a LiveQuery Subscription. + * + * @see https://docs.parseplatform.org/js/guide/#live-queries + * @see NodeJS.EventEmitter + * + * Events list + * --- + * `open` - when you call `query.subscribe()`, we send a subscribe request to + * the LiveQuery server, when we get the confirmation from the LiveQuery server, + * this event will be emitted. When the client loses WebSocket connection to the + * LiveQuery server, we will try to auto reconnect the LiveQuery server. If we + * reconnect the LiveQuery server and successfully resubscribe the ParseQuery, + * you'll also get this event. + * +``` +subscription.on('open', () => {}); +``` + * --- + * `create` - when a new ParseObject is created and it fulfills the ParseQuery you subscribe, + * you'll get this event. The object is the ParseObject which is created. + * +``` +subscription.on('create', (object: Parse.Object) => {}); +``` + * --- + * `update` event - when an existing ParseObject which fulfills the ParseQuery you subscribe + * is updated (The ParseObject fulfills the ParseQuery before and after changes), + * you'll get this event. The object is the ParseObject which is updated. + * Its content is the latest value of the ParseObject. + * +``` +subscription.on('update', (object: Parse.Object) => {}); +``` + * --- + * `enter` event - when an existing ParseObject's old value doesn't fulfill the ParseQuery + * but its new value fulfills the ParseQuery, you'll get this event. The object is the + * ParseObject which enters the ParseQuery. Its content is the latest value of the ParseObject. + * +``` +subscription.on('enter', (object: Parse.Object) => {}); +``` + * --- + * `update` event - when an existing ParseObject's old value fulfills the ParseQuery but its new value + * doesn't fulfill the ParseQuery, you'll get this event. The object is the ParseObject + * which leaves the ParseQuery. Its content is the latest value of the ParseObject. + * +``` +subscription.on('leave', (object: Parse.Object) => {}); +``` + * --- + * `delete` event - when an existing ParseObject which fulfills the ParseQuery is deleted, you'll + * get this event. The object is the ParseObject which is deleted. + * +``` +subscription.on('delete', (object: Parse.Object) => {}); +``` + * --- + * `close` event - when the client loses the WebSocket connection to the LiveQuery + * server and we stop receiving events, you'll get this event. + * +``` +subscription.on('close', () => {}); +``` + */ + class LiveQuerySubscription extends NodeJS.EventEmitter { + /** + * Creates an instance of LiveQuerySubscription. + * + * @param {string} id + * @param {string} query + * @param {string} [sessionToken] + */ + constructor(id: string, query: string, sessionToken?: string); + + /** + * Closes the subscription. + * + */ + unsubscribe(): void; } /** @@ -715,44 +608,6 @@ declare namespace Parse { isCurrentSessionRevocable(): boolean; } - /** - * Routers map faux-URLs to actions, and fire events when routes are - * matched. Creating a new one sets its `routes` hash, if not set statically. - * @class - * - *

          A fork of Backbone.Router, provided for your convenience. - * For more information, see the - * Backbone - * documentation.

          - *

          Available in the client SDK only.

          - */ - class Router extends Events { - - routes: Router.RouteMap; - - constructor(options?: Router.Options); - static extend(instanceProps: any, classProps: any): any; - - initialize(): void; - navigate(fragment: string, options?: Router.NavigateOptions): Router; - navigate(fragment: string, trigger?: boolean): Router; - route(route: string, name: string, callback: Function): Router; - } - - namespace Router { - interface Options { - routes: RouteMap; - } - - interface RouteMap { - [url: string]: string; - } - - interface NavigateOptions { - trigger?: boolean; - } - } - /** * @class * @@ -788,60 +643,6 @@ declare namespace Parse { getSessionToken(): string; } - /** - * Creating a Parse.View creates its initial element outside of the DOM, - * if an existing element is not provided... - * @class - * - *

          A fork of Backbone.View, provided for your convenience. If you use this - * class, you must also include jQuery, or another library that provides a - * jQuery-compatible $ function. For more information, see the - * Backbone - * documentation.

          - *

          Available in the client SDK only.

          - */ - class View extends Events { - - model: any; - collection: any; - id: string; - cid: string; - className: string; - tagName: string; - el: any; - $el: JQuery; - attributes: any; - - constructor(options?: View.Options); - - static extend(properties: any, classProperties?: any): any; - - $(selector?: string): JQuery; - setElement(element: HTMLElement, delegate?: boolean): View; - setElement(element: JQuery, delegate?: boolean): View; - render(): View; - remove(): View; - make(tagName: any, attributes?: View.Attribute[], content?: any): any; - delegateEvents(events?: any): any; - undelegateEvents(): any; - - } - - namespace View { - interface Options { - model?: any; - collection?: any; - el?: any; - id?: string; - className?: string; - tagName?: string; - attributes?: Attribute[]; - } - - interface Attribute { - [attributeName: string]: string | number | boolean; - } - } namespace Analytics { diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index acb194ed6a..8a2064e968 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -1,22 +1,3 @@ - - -function test_events() { - - const object = new Parse.Events(); - object.on("alert", (eventName: string) => alert("Triggered " + eventName)); - - object.trigger("alert", "an event"); - - const onChange = () => console.log('whatever'); - let context: any; - - object.off("change", onChange); - object.off("change"); - object.off(null, onChange); - object.off(null, null, context); - object.off(); -} - class GameScore extends Parse.Object { constructor(options?: any) { @@ -83,6 +64,7 @@ function test_query() { const query = new Parse.Query(GameScore); query.equalTo("playerName", "Dan Stemkoski"); query.notEqualTo("playerName", "Michael Yabuti"); + query.fullText("playerName", "dan", { language: 'en', caseSensitive: false, diacriticSensitive: true }); query.greaterThan("playerAge", 18); query.limit(10); query.skip(10); @@ -144,17 +126,30 @@ function test_query() { // Find objects with distinct key query.distinct('name'); - const testQuery = Parse.Query.or(query, query); + const testQuery = Parse.Query.or(query, query); } -class TestCollection extends Parse.Collection { +async function test_query_promise() { + // Test promise with a query + const findQuery = new Parse.Query('Test'); + findQuery.find() + .then(() => { + // success + }).catch(() => { + // error + }); - constructor(models?: Parse.Object[]) { - - super(models); + const getQuery = new Parse.Query('Test'); + try { + await getQuery.get('objectId'); + } + catch (error) { + // noop } } + + function return_a_generic_query(): Parse.Query { return new Parse.Query(Game); } @@ -163,49 +158,6 @@ function return_a_query(): Parse.Query { return new Parse.Query(Game); } -function test_collections() { - - let collection = new TestCollection(); - - const query = new Parse.Query(Game); - query.equalTo("temperature", "hot"); - query.greaterThan("degreesF", 100); - - collection = query.collection(); - - collection.comparator = (object) => { - return object.get("temperature"); - }; - - collection.add([ - { "name": "Duke" }, - { "name": "Scarlett" } - ]); - - collection.fetch().then( - (data) => { - - }, - (error) => { - console.log("Error: " + error.code + " " + error.message); - } - ); - - const model = collection.at(0); - - // Or you can get it by Parse objectId. - const modelAgain = collection.get(model.id); - - // Remove "Duke" from the collection. - collection.remove(model); - - // Completely replace all items in the collection. - collection.reset([ - { "name": "Hawk" }, - { "name": "Jane" } - ]); -} - function test_file() { const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; @@ -499,34 +451,6 @@ function test_push() { }); } -function test_view() { - - const model = Parse.User.current(); - const view = new Parse.View(); -} - -function test_promise() { - let resolved = Parse.Promise.as(true); - let rejected = Parse.Promise.error("an error object"); - Parse.Promise.when([resolved, rejected]).then(function () { - // success - }, function () { - // failed - }); - - // Test promise with a query - const query = new Parse.Query('Test'); - query.find() - .then(() => { - // success - }).catch(() => { - // error - }); - - // can check whether an object is a Parse.Promise object or not - Parse.Promise.is(resolved); -} - function test_batch_operations() { const game1 = new Game() const game2 = new Game() @@ -556,5 +480,7 @@ function test_query_subscribe() { subscription.on('create', (game: any) => { console.log(game); }); -} + // unsubscribe + subscription.unsubscribe(); +} diff --git a/types/parse/v1/index.d.ts b/types/parse/v1/index.d.ts new file mode 100644 index 0000000000..5f75772541 --- /dev/null +++ b/types/parse/v1/index.d.ts @@ -0,0 +1,1200 @@ +// Type definitions for parse 1.11.1 +// Project: https://parseplatform.org/ +// Definitions by: Ullisen Media Group +// David Poetzsch-Heffter +// Cedric Kemp +// Flavio Negrão +// Wes Grimes +// Otherwise SAS +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +/// +/// +/// + +declare namespace Parse { + + let applicationId: string; + let javaScriptKey: string | undefined; + let masterKey: string | undefined; + let serverURL: string; + let liveQueryServerURL: string; + let VERSION: string; + + interface SuccessOption { + success?: Function; + } + + interface ErrorOption { + error?: Function; + } + + interface SuccessFailureOptions extends SuccessOption, ErrorOption { + } + + interface SignUpOptions { + useMasterKey?: boolean; + installationId?: string; + } + + interface SessionTokenOption { + sessionToken?: string; + } + + interface WaitOption { + /** + * Set to true to wait for the server to confirm success + * before triggering an event. + */ + wait?: boolean; + } + + interface UseMasterKeyOption { + /** + * In Cloud Code and Node only, causes the Master Key to be used for this request. + */ + useMasterKey?: boolean; + } + + interface ScopeOptions extends SessionTokenOption, UseMasterKeyOption { + } + + interface SilentOption { + /** + * Set to true to avoid firing the event. + */ + silent?: boolean; + } + + /** + * A Promise is returned by async methods as a hook to provide callbacks to be + * called when the async task is fulfilled. + * + *

          Typical usage would be like:

          +     *    query.find().then(function(results) {
          +     *      results[0].set("foo", "bar");
          +     *      return results[0].saveAsync();
          +     *    }).then(function(result) {
          +     *      console.log("Updated " + result.id);
          +     *    });
          +     * 

          + * + * @see Parse.Promise.prototype.then + * @class + */ + + interface IPromise { + + then(resolvedCallback: (...values: T[]) => IPromise, rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; + catch(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; + } + + class Promise implements IPromise { + + static as(resolvedValue: U): Promise; + static error(error: any): Promise; + static is(possiblePromise: any): Boolean; + static when(promises: IPromise[]): Promise; + static when(...promises: IPromise[]): Promise; + + always(callback: Function): Promise; + done(callback: Function): Promise; + fail(callback: Function): Promise; + reject(error: any): void; + resolve(result: any): void; + then(resolvedCallback: (...values: T[]) => IPromise, + rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, + rejectedCallback?: (reason: any) => IPromise): IPromise; + then(resolvedCallback: (...values: T[]) => U, + rejectedCallback?: (reason: any) => U): IPromise; + catch(resolvedCallback: (...values: T[]) => U, rejectedCallback?: (reason: any) => U): IPromise; + } + + interface Pointer { + __type: string; + className: string; + objectId: string; + } + + interface IBaseObject { + toJSON(): any; + } + + class BaseObject implements IBaseObject { + toJSON(): any; + } + + /** + * Creates a new ACL. + * If no argument is given, the ACL has no permissions for anyone. + * If the argument is a Parse.User, the ACL will have read and write + * permission for only that user. + * If the argument is any other JSON object, that object will be interpretted + * as a serialized ACL created with toJSON(). + * @see Parse.Object#setACL + * @class + * + *

          An ACL, or Access Control List can be added to any + * Parse.Object to restrict access to only a subset of users + * of your application.

          + */ + class ACL extends BaseObject { + + permissionsById: any; + + constructor(arg1?: any); + + setPublicReadAccess(allowed: boolean): void; + getPublicReadAccess(): boolean; + + setPublicWriteAccess(allowed: boolean): void; + getPublicWriteAccess(): boolean; + + setReadAccess(userId: User, allowed: boolean): void; + getReadAccess(userId: User): boolean; + + setReadAccess(userId: string, allowed: boolean): void; + getReadAccess(userId: string): boolean; + + setRoleReadAccess(role: Role, allowed: boolean): void; + setRoleReadAccess(role: string, allowed: boolean): void; + getRoleReadAccess(role: Role): boolean; + getRoleReadAccess(role: string): boolean; + + setRoleWriteAccess(role: Role, allowed: boolean): void; + setRoleWriteAccess(role: string, allowed: boolean): void; + getRoleWriteAccess(role: Role): boolean; + getRoleWriteAccess(role: string): boolean; + + setWriteAccess(userId: User, allowed: boolean): void; + setWriteAccess(userId: string, allowed: boolean): void; + getWriteAccess(userId: User): boolean; + getWriteAccess(userId: string): boolean; + } + + + /** + * A Parse.File is a local representation of a file that is saved to the Parse + * cloud. + * @class + * @param name {String} The file's name. This will be prefixed by a unique + * value once the file has finished saving. The file name must begin with + * an alphanumeric character, and consist of alphanumeric characters, + * periods, spaces, underscores, or dashes. + * @param data {Array} The data for the file, as either: + * 1. an Array of byte value Numbers, or + * 2. an Object like { base64: "..." } with a base64-encoded String. + * 3. a File object selected with a file upload control. (3) only works + * in Firefox 3.6+, Safari 6.0.2+, Chrome 7+, and IE 10+. + * For example:
          +     * var fileUploadControl = $("#profilePhotoFileUpload")[0];
          +     * if (fileUploadControl.files.length > 0) {
          +     *   var file = fileUploadControl.files[0];
          +     *   var name = "photo.jpg";
          +     *   var parseFile = new Parse.File(name, file);
          +     *   parseFile.save().then(function() {
          +     *     // The file has been saved to Parse.
          +     *   }, function(error) {
          +     *     // The file either could not be read, or could not be saved to Parse.
          +     *   });
          +     * }
          + * @param type {String} Optional Content-Type header to use for the file. If + * this is omitted, the content type will be inferred from the name's + * extension. + */ + class File { + + constructor(name: string, data: any, type?: string); + name(): string; + url(): string; + save(options?: SuccessFailureOptions): Promise; + + } + + /** + * Creates a new GeoPoint with any of the following forms:
          + *
          +     *   new GeoPoint(otherGeoPoint)
          +     *   new GeoPoint(30, 30)
          +     *   new GeoPoint([30, 30])
          +     *   new GeoPoint({latitude: 30, longitude: 30})
          +     *   new GeoPoint()  // defaults to (0, 0)
          +     *   
          + * @class + * + *

          Represents a latitude / longitude point that may be associated + * with a key in a ParseObject or used as a reference point for geo queries. + * This allows proximity-based queries on the key.

          + * + *

          Only one key in a class may contain a GeoPoint.

          + * + *

          Example:

          +     *   var point = new Parse.GeoPoint(30.0, -20.0);
          +     *   var object = new Parse.Object("PlaceObject");
          +     *   object.set("location", point);
          +     *   object.save();

          + */ + class GeoPoint extends BaseObject { + + latitude: number; + longitude: number; + + constructor(arg1?: any, arg2?: any); + + current(options?: SuccessFailureOptions): GeoPoint; + radiansTo(point: GeoPoint): number; + kilometersTo(point: GeoPoint): number; + milesTo(point: GeoPoint): number; + } + + /** + * History serves as a global router (per frame) to handle hashchange + * events or pushState, match the appropriate route, and trigger + * callbacks. You shouldn't ever have to create one of these yourself + * — you should use the reference to Parse.history + * that will be created for you automatically if you make use of + * Routers with routes. + * @class + * + *

          A fork of Backbone.History, provided for your convenience. If you + * use this class, you must also include jQuery, or another library + * that provides a jQuery-compatible $ function. For more information, + * see the + * Backbone documentation.

          + *

          Available in the client SDK only.

          + */ + class History { + + handlers: any[]; + interval: number; + fragment: string; + + checkUrl(e?: any): void; + getFragment(fragment?: string, forcePushState?: boolean): string; + getHash(windowOverride: Window): string; + loadUrl(fragmentOverride: any): boolean; + navigate(fragment: string, options?: any): any; + route(route: any, callback: Function): void; + start(options: any): boolean; + stop(): void; + } + + /** + * A class that is used to access all of the children of a many-to-many relationship. + * Each instance of Parse.Relation is associated with a particular parent object and key. + */ + class Relation extends BaseObject { + + parent: S; + key: string; + targetClassName: string; + + constructor(parent?: S, key?: string); + + //Adds a Parse.Object or an array of Parse.Objects to the relation. + add(object: T | Array): void; + + // Returns a Parse.Query that is limited to objects in this relation. + query(): Query; + + // Removes a Parse.Object or an array of Parse.Objects from this relation. + remove(object: T | Array): void; + } + + /** + * Creates a new model with defined attributes. A client id (cid) is + * automatically generated and assigned for you. + * + *

          You won't normally call this method directly. It is recommended that + * you use a subclass of Parse.Object instead, created by calling + * extend.

          + * + *

          However, if you don't want to use a subclass, or aren't sure which + * subclass is appropriate, you can use this form:

          +     *     var object = new Parse.Object("ClassName");
          +     * 
          + * That is basically equivalent to:
          +     *     var MyClass = Parse.Object.extend("ClassName");
          +     *     var object = new MyClass();
          +     * 

          + * + * @param {Object} attributes The initial set of data to store in the object. + * @param {Object} options A set of Backbone-like options for creating the + * object. The only option currently supported is "collection". + * @see Parse.Object.extend + * + * @class + * + *

          The fundamental unit of Parse data, which implements the Backbone Model + * interface.

          + */ + class Object extends BaseObject { + + id: string; + createdAt: Date; + updatedAt: Date; + attributes: any; + cid: string; + changed: boolean; + className: string; + + constructor(className?: string, options?: any); + constructor(attributes?: string[], options?: any); + + static extend(className: string, protoProps?: any, classProps?: any): any; + static fromJSON(json: any, override: boolean): any; + + static fetchAll(list: T[], options: Object.FetchAllOptions): Promise; + static fetchAllIfNeeded(list: T[], options: Object.FetchAllOptions): Promise; + static destroyAll(list: T[], options?: Object.DestroyAllOptions): Promise; + static saveAll(list: T[], options?: Object.SaveAllOptions): Promise; + static registerSubclass(className: string, clazz: new (options?: any) => T): void; + static createWithoutData(id: string): T; + + initialize(): void; + add(attr: string, item: any): this; + addUnique(attr: string, item: any): any; + change(options: any): this; + changedAttributes(diff: any): boolean; + clear(options: any): any; + clone(): this; + destroy(options?: Object.DestroyOptions): Promise; + dirty(attr?: string): boolean; + dirtyKeys(): string[]; + escape(attr: string): string; + existed(): boolean; + fetch(options?: Object.FetchOptions): Promise; + get(attr: string): any | undefined; + getACL(): ACL | undefined; + has(attr: string): boolean; + hasChanged(attr: string): boolean; + increment(attr: string, amount?: number): any; + isNew(): boolean; + isValid(): boolean; + op(attr: string): any; + previous(attr: string): any; + previousAttributes(): any; + relation(attr: string): Relation; + remove(attr: string, item: any): any; + revert(): void; + save(attrs?: { [key: string]: any } | null, options?: Object.SaveOptions): Promise; + save(key: string, value: any, options?: Object.SaveOptions): Promise; + save(attrs: object, options?: Object.SaveOptions): Promise; + set(key: string, value: any, options?: Object.SetOptions): boolean; + set(attrs: object, options?: Object.SetOptions): boolean; + setACL(acl: ACL, options?: SuccessFailureOptions): boolean; + toPointer(): Pointer; + unset(attr: string, options?: any): any; + validate(attrs: any, options?: SuccessFailureOptions): boolean; + } + + namespace Object { + interface DestroyOptions extends SuccessFailureOptions, WaitOption, ScopeOptions { } + + interface DestroyAllOptions extends SuccessFailureOptions, ScopeOptions { } + + interface FetchAllOptions extends SuccessFailureOptions, ScopeOptions { } + + interface FetchOptions extends SuccessFailureOptions, ScopeOptions { } + + interface SaveOptions extends SuccessFailureOptions, SilentOption, ScopeOptions, WaitOption { } + + interface SaveAllOptions extends SuccessFailureOptions, ScopeOptions { } + + interface SetOptions extends ErrorOption, SilentOption { + promise?: any; + } + } + + /** + * Every Parse application installed on a device registered for + * push notifications has an associated Installation object. + */ + class Installation extends Object { + + badge: any; + channels: string[]; + timeZone: any; + deviceType: string; + pushType: string; + installationId: string; + deviceToken: string; + channelUris: string; + appName: string; + appVersion: string; + parseVersion: string; + appIdentifier: string; + + } + + /** + * Creates a new instance with the given models and options. Typically, you + * will not call this method directly, but will instead make a subclass using + * Parse.Collection.extend. + * + * @param {Array} models An array of instances of Parse.Object. + * + * @param {Object} options An optional object with Backbone-style options. + * Valid options are:
            + *
          • model: The Parse.Object subclass that this collection contains. + *
          • query: An instance of Parse.Query to use when fetching items. + *
          • comparator: A string property name or function to sort by. + *
          + * + * @see Parse.Collection.extend + * + * @class + * + *

          Provides a standard collection class for our sets of models, ordered + * or unordered. For more information, see the + * Backbone + * documentation.

          + */ + class Collection extends Events implements IBaseObject { + + model: Object; + models: Object[]; + query: Query; + comparator: (object: Object) => any; + + constructor(models?: Object[], options?: Collection.Options); + static extend(instanceProps: any, classProps: any): any; + + initialize(): void; + add(models: any[], options?: Collection.AddOptions): Collection; + at(index: number): Object; + chain(): _._Chain>; + fetch(options?: Collection.FetchOptions): Promise; + create(model: Object, options?: Collection.CreateOptions): Object; + get(id: string): Object; + getByCid(cid: any): any; + pluck(attr: string): any[]; + remove(model: any, options?: Collection.RemoveOptions): Collection; + remove(models: any[], options?: Collection.RemoveOptions): Collection; + reset(models: any[], options?: Collection.ResetOptions): Collection; + sort(options?: Collection.SortOptions): Collection; + toJSON(): any; + } + + namespace Collection { + interface Options { + model?: Object; + query?: Query; + comparator?: string; + } + + interface AddOptions extends SilentOption { + /** + * The index at which to add the models. + */ + at?: number; + } + + interface CreateOptions extends SuccessFailureOptions, WaitOption, SilentOption, ScopeOptions { + } + + interface FetchOptions extends SuccessFailureOptions, SilentOption, ScopeOptions { } + + interface RemoveOptions extends SilentOption { } + + interface ResetOptions extends SilentOption { } + + interface SortOptions extends SilentOption { } + } + + /** + * @class + * + *

          Parse.Events is a fork of Backbone's Events module, provided for your + * convenience.

          + * + *

          A module that can be mixed in to any object in order to provide + * it with custom events. You may bind callback functions to an event + * with `on`, or remove these functions with `off`. + * Triggering an event fires all callbacks in the order that `on` was + * called. + * + *

          +     *     var object = {};
          +     *     _.extend(object, Parse.Events);
          +     *     object.on('expand', function(){ alert('expanded'); });
          +     *     object.trigger('expand');

          + * + *

          For more information, see the + * Backbone + * documentation.

          + */ + class Events { + + static off(events: string[], callback?: Function, context?: any): Events; + static on(events: string[], callback?: Function, context?: any): Events; + static trigger(events: string[]): Events; + static bind(): Events; + static unbind(): Events; + + on(eventName: string, callback?: Function, context?: any): Events; + off(eventName?: string | null, callback?: Function | null, context?: any): Events; + trigger(eventName: string, ...args: any[]): Events; + bind(eventName: string, callback: Function, context?: any): Events; + unbind(eventName?: string, callback?: Function, context?: any): Events; + + } + + /** + * Creates a new parse Parse.Query for the given Parse.Object subclass. + * @param objectClass - + * An instance of a subclass of Parse.Object, or a Parse className string. + * @class + * + *

          Parse.Query defines a query that is used to fetch Parse.Objects. The + * most common use case is finding all objects that match a query through the + * find method. For example, this sample code fetches all objects + * of class MyClass. It calls a different function depending on + * whether the fetch succeeded or not. + * + *

          +     * var query = new Parse.Query(MyClass);
          +     * query.find({
          +     *   success: function(results) {
          +     *     // results is an array of Parse.Object.
          +     *   },
          +     *
          +     *   error: function(error) {
          +     *     // error is an instance of Parse.Error.
          +     *   }
          +     * });

          + * + *

          A Parse.Query can also be used to retrieve a single object whose id is + * known, through the get method. For example, this sample code fetches an + * object of class MyClass and id myId. It calls a + * different function depending on whether the fetch succeeded or not. + * + *

          +     * var query = new Parse.Query(MyClass);
          +     * query.get(myId, {
          +     *   success: function(object) {
          +     *     // object is an instance of Parse.Object.
          +     *   },
          +     *
          +     *   error: function(object, error) {
          +     *     // error is an instance of Parse.Error.
          +     *   }
          +     * });

          + * + *

          A Parse.Query can also be used to count the number of objects that match + * the query without retrieving all of those objects. For example, this + * sample code counts the number of objects of the class MyClass + *

          +     * var query = new Parse.Query(MyClass);
          +     * query.count({
          +     *   success: function(number) {
          +     *     // There are number instances of MyClass.
          +     *   },
          +     *
          +     *   error: function(error) {
          +     *     // error is an instance of Parse.Error.
          +     *   }
          +     * });

          + */ + class Query extends BaseObject { + + objectClass: any; + className: string; + + constructor(objectClass: string); + constructor(objectClass: new (...args: any[]) => T); + + static or(...var_args: Query[]): Query; + + aggregate(pipeline: Query.AggregationOptions|Query.AggregationOptions[]): Query; + addAscending(key: string): Query; + addAscending(key: string[]): Query; + addDescending(key: string): Query; + addDescending(key: string[]): Query; + ascending(key: string): Query; + ascending(key: string[]): Query; + collection(items?: Object[], options?: Collection.Options): Collection; + containedIn(key: string, values: any[]): Query; + contains(key: string, substring: string): Query; + containsAll(key: string, values: any[]): Query; + count(options?: Query.CountOptions): Promise; + descending(key: string): Query; + descending(key: string[]): Query; + doesNotExist(key: string): Query; + doesNotMatchKeyInQuery(key: string, queryKey: string, query: Query): Query; + doesNotMatchQuery(key: string, query: Query): Query; + distinct(key: string): Query; + each(callback: Function, options?: Query.EachOptions): Promise; + endsWith(key: string, suffix: string): Query; + equalTo(key: string, value: any): Query; + exists(key: string): Query; + find(options?: Query.FindOptions): Promise; + first(options?: Query.FirstOptions): Promise; + fullText(key: string, value: string, options?: Query.FullTextOptions): Query; + get(objectId: string, options?: Query.GetOptions): Promise; + greaterThan(key: string, value: any): Query; + greaterThanOrEqualTo(key: string, value: any): Query; + include(key: string): Query; + include(keys: string[]): Query; + lessThan(key: string, value: any): Query; + lessThanOrEqualTo(key: string, value: any): Query; + limit(n: number): Query; + matches(key: string, regex: RegExp, modifiers: any): Query; + matchesKeyInQuery(key: string, queryKey: string, query: Query): Query; + matchesQuery(key: string, query: Query): Query; + near(key: string, point: GeoPoint): Query; + notContainedIn(key: string, values: any[]): Query; + notEqualTo(key: string, value: any): Query; + select(...keys: string[]): Query; + skip(n: number): Query; + startsWith(key: string, prefix: string): Query; + subscribe(): Events; + withinGeoBox(key: string, southwest: GeoPoint, northeast: GeoPoint): Query; + withinKilometers(key: string, point: GeoPoint, maxDistance: number): Query; + withinMiles(key: string, point: GeoPoint, maxDistance: number): Query; + withinRadians(key: string, point: GeoPoint, maxDistance: number): Query; + } + + namespace Query { + interface EachOptions extends SuccessFailureOptions, ScopeOptions { } + interface CountOptions extends SuccessFailureOptions, ScopeOptions { } + interface FindOptions extends SuccessFailureOptions, ScopeOptions { } + interface FirstOptions extends SuccessFailureOptions, ScopeOptions { } + interface GetOptions extends SuccessFailureOptions, ScopeOptions { } + + // According to http://docs.parseplatform.org/rest/guide/#aggregate-queries + interface AggregationOptions { + group?: { objectId?: string, [key:string]: any }; + match?: {[key: string]: any}; + project?: {[key: string]: any}; + limit?: number; + skip?: number; + // Sort documentation https://docs.mongodb.com/v3.2/reference/operator/aggregation/sort/#pipe._S_sort + sort?: {[key: string]: 1|-1}; + } + + // According to https://parseplatform.org/Parse-SDK-JS/api/2.1.0/Parse.Query.html#fullText + interface FullTextOptions { + language?: string; + caseSensitive?: boolean; + diacriticSensitive?: boolean; + } + } + + /** + * Represents a Role on the Parse server. Roles represent groupings of + * Users for the purposes of granting permissions (e.g. specifying an ACL + * for an Object). Roles are specified by their sets of child users and + * child roles, all of which are granted any permissions that the parent + * role has. + * + *

          Roles must have a name (which cannot be changed after creation of the + * role), and must specify an ACL.

          + * @class + * A Parse.Role is a local representation of a role persisted to the Parse + * cloud. + */ + class Role extends Object { + + constructor(name: string, acl: ACL); + + getRoles(): Relation; + getUsers(): Relation; + getName(): string; + setName(name: string, options?: SuccessFailureOptions): any; + } + + class Config extends Object { + static get(options?: SuccessFailureOptions): Promise; + static current(): Config; + + get(attr: string): any; + escape(attr: string): any; + } + + class Session extends Object { + static current(): Promise; + + getSessionToken(): string; + isCurrentSessionRevocable(): boolean; + } + + /** + * Routers map faux-URLs to actions, and fire events when routes are + * matched. Creating a new one sets its `routes` hash, if not set statically. + * @class + * + *

          A fork of Backbone.Router, provided for your convenience. + * For more information, see the + * Backbone + * documentation.

          + *

          Available in the client SDK only.

          + */ + class Router extends Events { + + routes: Router.RouteMap; + + constructor(options?: Router.Options); + static extend(instanceProps: any, classProps: any): any; + + initialize(): void; + navigate(fragment: string, options?: Router.NavigateOptions): Router; + navigate(fragment: string, trigger?: boolean): Router; + route(route: string, name: string, callback: Function): Router; + } + + namespace Router { + interface Options { + routes: RouteMap; + } + + interface RouteMap { + [url: string]: string; + } + + interface NavigateOptions { + trigger?: boolean; + } + } + + /** + * @class + * + *

          A Parse.User object is a local representation of a user persisted to the + * Parse cloud. This class is a subclass of a Parse.Object, and retains the + * same functionality of a Parse.Object, but also extends it with various + * user specific methods, like authentication, signing up, and validation of + * uniqueness.

          + */ + class User extends Object { + + static current(): User | undefined; + static signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; + static logIn(username: string, password: string, options?: SuccessFailureOptions): Promise; + static logOut(): Promise; + static allowCustomUserClass(isAllowed: boolean): void; + static become(sessionToken: string, options?: SuccessFailureOptions): Promise; + static requestPasswordReset(email: string, options?: SuccessFailureOptions): Promise; + static extend(protoProps?: any, classProps?: any): any; + + signUp(attrs: any, options?: SignUpOptions): Promise; + logIn(options?: SuccessFailureOptions): Promise; + authenticated(): boolean; + isCurrent(): boolean; + + getEmail(): string | undefined; + setEmail(email: string, options?: SuccessFailureOptions): boolean; + + getUsername(): string | undefined; + setUsername(username: string, options?: SuccessFailureOptions): boolean; + + setPassword(password: string, options?: SuccessFailureOptions): boolean; + getSessionToken(): string; + } + + /** + * Creating a Parse.View creates its initial element outside of the DOM, + * if an existing element is not provided... + * @class + * + *

          A fork of Backbone.View, provided for your convenience. If you use this + * class, you must also include jQuery, or another library that provides a + * jQuery-compatible $ function. For more information, see the + * Backbone + * documentation.

          + *

          Available in the client SDK only.

          + */ + class View extends Events { + + model: any; + collection: any; + id: string; + cid: string; + className: string; + tagName: string; + el: any; + $el: JQuery; + attributes: any; + + constructor(options?: View.Options); + + static extend(properties: any, classProperties?: any): any; + + $(selector?: string): JQuery; + setElement(element: HTMLElement, delegate?: boolean): View; + setElement(element: JQuery, delegate?: boolean): View; + render(): View; + remove(): View; + make(tagName: any, attributes?: View.Attribute[], content?: any): any; + delegateEvents(events?: any): any; + undelegateEvents(): any; + + } + + namespace View { + interface Options { + model?: any; + collection?: any; + el?: any; + id?: string; + className?: string; + tagName?: string; + attributes?: Attribute[]; + } + + interface Attribute { + [attributeName: string]: string | number | boolean; + } + } + + namespace Analytics { + + function track(name: string, dimensions: any): Promise; + } + + /** + * Provides a set of utilities for using Parse with Facebook. + * @namespace + * Provides a set of utilities for using Parse with Facebook. + */ + namespace FacebookUtils { + + function init(options?: any): void; + function isLinked(user: User): boolean; + function link(user: User, permissions: any, options?: SuccessFailureOptions): void; + function logIn(permissions: any, options?: SuccessFailureOptions): void; + function unlink(user: User, options?: SuccessFailureOptions): void; + } + + /** + * @namespace Contains functions for calling and declaring + * cloud functions. + *

          + * Some functions are only available from Cloud Code. + *

          + */ + namespace Cloud { + + interface CookieOptions { + domain?: string; + expires?: Date; + httpOnly?: boolean; + maxAge?: number; + path?: string; + secure?: boolean; + } + + interface HttpResponse { + buffer?: Buffer; + cookies?: any; + data?: any; + headers?: any; + status?: number; + text?: string; + } + + interface JobRequest { + params: any; + } + + interface JobStatus { + error?: (response: any) => void; + message?: (response: any) => void; + success?: (response: any) => void; + } + + interface FunctionRequest { + installationId?: String; + master?: boolean; + params?: any; + user?: User; + } + + interface FunctionResponse { + success: (response: any) => void; + error (code: number, response: any): void; + error (response: any): void; + } + + interface Cookie { + name?: string; + options?: CookieOptions; + value?: string; + } + + interface TriggerRequest { + installationId?: String; + master?: boolean; + user?: User; + ip: string; + headers: any; + triggerName: string; + log: any; + object: Object; + original?: Parse.Object; + } + + interface AfterSaveRequest extends TriggerRequest { } + interface AfterDeleteRequest extends TriggerRequest { } + interface BeforeDeleteRequest extends TriggerRequest { } + interface BeforeDeleteResponse extends FunctionResponse { } + interface BeforeSaveRequest extends TriggerRequest { } + interface BeforeSaveResponse extends FunctionResponse { + success: () => void; + } + + // Read preference describes how MongoDB driver route read operations to the members of a replica set. + enum ReadPreferenceOption { + Primary = 'PRIMARY', + PrimaryPreferred = 'PRIMARY_PREFERRED', + Secondary = 'SECONDARY', + SecondaryPreferred = 'SECONDARY_PREFERRED', + Nearest = 'NEAREST' + } + + interface BeforeFindRequest extends TriggerRequest { + query: Query + count: boolean + isGet: boolean + readPreference?: ReadPreferenceOption + } + + interface AfterFindRequest extends TriggerRequest { + objects: Object[] + } + + interface AfterFindResponse extends FunctionResponse { + success: (objects: Object[]) => void; + } + + function afterDelete(arg1: any, func?: (request: AfterDeleteRequest) => void): void; + function afterSave(arg1: any, func?: (request: AfterSaveRequest) => void): void; + function beforeDelete(arg1: any, func?: (request: BeforeDeleteRequest, response: BeforeDeleteResponse) => void): void; + function beforeSave(arg1: any, func?: (request: BeforeSaveRequest, response: BeforeSaveResponse) => void): void; + function beforeFind(arg1: any, func?: (request: BeforeFindRequest) => void): void; + function afterFind(arg1: any, func?: (request: AfterFindRequest, response: AfterFindResponse) => void): void; + function define(name: string, func?: (request: FunctionRequest, response: FunctionResponse) => void): void; + function httpRequest(options: HTTPOptions): Promise; + function job(name: string, func?: (request: JobRequest, status: JobStatus) => void): HttpResponse; + function run(name: string, data?: any, options?: RunOptions): Promise; + function useMasterKey(): void; + + interface RunOptions extends SuccessFailureOptions, ScopeOptions { } + + /** + * To use this Cloud Module in Cloud Code, you must require 'buffer' in your JavaScript file. + * + * import Buffer = require("buffer").Buffer; + */ + let HTTPOptions: new () => HTTPOptions; + interface HTTPOptions { + /** + * The body of the request. + * If it is a JSON object, then the Content-Type set in the headers must be application/x-www-form-urlencoded or application/json. + * You can also set this to a Buffer object to send raw bytes. + * If you use a Buffer, you should also set the Content-Type header explicitly to describe what these bytes represent. + */ + body?: string | Buffer | Object; + /** + * Defaults to 'false'. + */ + followRedirects?: boolean; + /** + * The headers for the request. + */ + headers?: { + [headerName: string]: string | number | boolean; + }; + /** + *The method of the request (i.e GET, POST, etc). + */ + method?: string; + /** + * The query portion of the url. + */ + params?: any; + /** + * The url to send the request to. + */ + url: string; + + success?: (response: any) => void; + error?: (response: any) => void; + } + } + + + class Error { + + code: ErrorCode; + message: string; + + constructor(code: ErrorCode, message: string); + + } + + /* + * We need to inline the codes in order to make compilation work without this type definition as dependency. + */ + const enum ErrorCode { + + OTHER_CAUSE = -1, + INTERNAL_SERVER_ERROR = 1, + CONNECTION_FAILED = 100, + OBJECT_NOT_FOUND = 101, + INVALID_QUERY = 102, + INVALID_CLASS_NAME = 103, + MISSING_OBJECT_ID = 104, + INVALID_KEY_NAME = 105, + INVALID_POINTER = 106, + INVALID_JSON = 107, + COMMAND_UNAVAILABLE = 108, + NOT_INITIALIZED = 109, + INCORRECT_TYPE = 111, + INVALID_CHANNEL_NAME = 112, + PUSH_MISCONFIGURED = 115, + OBJECT_TOO_LARGE = 116, + OPERATION_FORBIDDEN = 119, + CACHE_MISS = 120, + INVALID_NESTED_KEY = 121, + INVALID_FILE_NAME = 122, + INVALID_ACL = 123, + TIMEOUT = 124, + INVALID_EMAIL_ADDRESS = 125, + MISSING_CONTENT_TYPE = 126, + MISSING_CONTENT_LENGTH = 127, + INVALID_CONTENT_LENGTH = 128, + FILE_TOO_LARGE = 129, + FILE_SAVE_ERROR = 130, + DUPLICATE_VALUE = 137, + INVALID_ROLE_NAME = 139, + EXCEEDED_QUOTA = 140, + SCRIPT_FAILED = 141, + VALIDATION_ERROR = 142, + INVALID_IMAGE_DATA = 150, + UNSAVED_FILE_ERROR = 151, + INVALID_PUSH_TIME_ERROR = 152, + FILE_DELETE_ERROR = 153, + REQUEST_LIMIT_EXCEEDED = 155, + INVALID_EVENT_NAME = 160, + USERNAME_MISSING = 200, + PASSWORD_MISSING = 201, + USERNAME_TAKEN = 202, + EMAIL_TAKEN = 203, + EMAIL_MISSING = 204, + EMAIL_NOT_FOUND = 205, + SESSION_MISSING = 206, + MUST_CREATE_USER_THROUGH_SIGNUP = 207, + ACCOUNT_ALREADY_LINKED = 208, + INVALID_SESSION_TOKEN = 209, + LINKED_ID_MISSING = 250, + INVALID_LINKED_SESSION = 251, + UNSUPPORTED_SERVICE = 252, + AGGREGATE_ERROR = 600, + FILE_READ_ERROR = 601, + X_DOMAIN_REQUEST = 602 + } + + /** + * @class + * A Parse.Op is an atomic operation that can be applied to a field in a + * Parse.Object. For example, calling object.set("foo", "bar") + * is an example of a Parse.Op.Set. Calling object.unset("foo") + * is a Parse.Op.Unset. These operations are stored in a Parse.Object and + * sent to the server as part of object.save() operations. + * Instances of Parse.Op should be immutable. + * + * You should not create subclasses of Parse.Op or instantiate Parse.Op + * directly. + */ + namespace Op { + + interface BaseOperation extends IBaseObject { + objects(): any[]; + } + + interface Add extends BaseOperation { + } + + interface AddUnique extends BaseOperation { + } + + interface Increment extends IBaseObject { + amount: number; + } + + interface Relation extends IBaseObject { + added(): Object[]; + removed: Object[]; + } + + interface Set extends IBaseObject { + value(): any; + } + + interface Unset extends IBaseObject { + } + + } + + /** + * Contains functions to deal with Push in Parse + * @name Parse.Push + * @namespace + */ + namespace Push { + function send(data: PushData, options?: SendOptions): Promise; + + interface PushData { + channels?: string[]; + push_time?: Date; + expiration_time?: Date; + expiration_interval?: number; + where?: Query; + data?: any; + alert?: string; + badge?: string; + sound?: string; + title?: string; + } + + interface SendOptions extends UseMasterKeyOption { + success?: () => void; + error?: (error: Error) => void; + } + } + + /** + * Call this method first to set up your authentication tokens for Parse. + * You can get your keys from the Data Browser on parse.com. + * @param {String} applicationId Your Parse Application ID. + * @param {String} javaScriptKey (optional) Your Parse JavaScript Key (Not needed for parse-server) + * @param {String} masterKey (optional) Your Parse Master Key. (Node.js only!) + */ + function initialize(applicationId: string, javaScriptKey?: string, masterKey?: string): void; + + /** + * Additionally on React-Native / Expo environments, add AsyncStorage from 'react-native' package + * @param AsyncStorage AsyncStorage from 'react-native' package + */ + function setAsyncStorage(AsyncStorage: any): void; + +} + +declare module "parse/node" { + export = Parse; +} + +declare module "parse" { + import * as parse from "parse/node"; + export = parse +} + +declare module "parse/react-native" { + import * as parse from "parse/node"; + export = parse +} diff --git a/types/parse/v1/parse-tests.ts b/types/parse/v1/parse-tests.ts new file mode 100644 index 0000000000..7f7f72e072 --- /dev/null +++ b/types/parse/v1/parse-tests.ts @@ -0,0 +1,561 @@ + + +function test_events() { + + const object = new Parse.Events(); + object.on("alert", (eventName: string) => alert("Triggered " + eventName)); + + object.trigger("alert", "an event"); + + const onChange = () => console.log('whatever'); + let context: any; + + object.off("change", onChange); + object.off("change"); + object.off(null, onChange); + object.off(null, null, context); + object.off(); +} + +class GameScore extends Parse.Object { + + constructor(options?: any) { + + super("GameScore", options); + } +} + +class Game extends Parse.Object { + + constructor(options?: any) { + + super("Game", options); + } +} + +function test_object() { + + const game = new Game(); + + if (!game.isNew()) { + console.error("Game should be new"); + } + + if (game.toPointer().className !== "Game") { + console.log("Class name should be 'Game") + } + + game.fetch({ + success(g: Game) { } + }); + + // Create a new instance of that class. + const gameScore = new GameScore(); + + gameScore.set("score", 1337); + gameScore.set("playerName", "Sean Plott"); + gameScore.set("cheatMode", false); + + + // Setting attrs using object + gameScore.set({ + level: '10', + difficult: 15 + }); + + const score = gameScore.get("score"); + const playerName = gameScore.get("playerName"); + const cheatMode = gameScore.get("cheatMode"); + + gameScore.increment("score"); + gameScore.addUnique("skills", "flying"); + gameScore.addUnique("skills", "kungfu"); + + game.set("gameScore", gameScore); + + const gameCopy = Game.fromJSON(JSON.parse(JSON.stringify(game)), true); +} + +function test_query() { + + const gameScore = new GameScore(); + + const query = new Parse.Query(GameScore); + query.equalTo("playerName", "Dan Stemkoski"); + query.notEqualTo("playerName", "Michael Yabuti"); + query.fullText("playerName", "dan", { language: 'en', caseSensitive: false, diacriticSensitive: true }); + query.greaterThan("playerAge", 18); + query.limit(10); + query.skip(10); + + // Sorts the results in ascending order by the score field + query.ascending("score"); + + // Sorts the results in descending order by the score field + query.descending("score"); + + // Restricts to wins < 50 + query.lessThan("wins", 50); + + // Restricts to wins <= 50 + query.lessThanOrEqualTo("wins", 50); + + // Restricts to wins > 50 + query.greaterThan("wins", 50); + + // Restricts to wins >= 50 + query.greaterThanOrEqualTo("wins", 50); + + // Finds scores from any of Jonathan, Dario, or Shawn + query.containedIn("playerName", + ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); + + // Finds scores from anyone who is neither Jonathan, Dario, nor Shawn + query.notContainedIn("playerName", + ["Jonathan Walsh", "Dario Wunsch", "Shawn Simon"]); + + // Finds objects that have the score set + query.exists("score"); + + // Finds objects that don't have the score set + query.doesNotExist("score"); + query.matchesKeyInQuery("hometown", "city", query); + query.doesNotMatchKeyInQuery("hometown", "city", query); + query.select("score", "playerName"); + + // Find objects where the array in arrayKey contains 2. + query.equalTo("arrayKey", 2); + + // Find objects where the array in arrayKey contains all of the elements 2, 3, and 4. + query.containsAll("arrayKey", [2, 3, 4]); + + query.startsWith("name", "Big Daddy's"); + query.equalTo("score", gameScore); + query.exists("score"); + query.include("score"); + query.include(["score.team"]); + + // Find objects that match the aggregation pipeline + query.aggregate({ + group:{ + objectId: '$name' + } + }); + + // Find objects with distinct key + query.distinct('name'); + + const testQuery = Parse.Query.or(query, query); +} + +class TestCollection extends Parse.Collection { + + constructor(models?: Parse.Object[]) { + + super(models); + } +} + +function return_a_generic_query(): Parse.Query { + return new Parse.Query(Game); +} + +function return_a_query(): Parse.Query { + return new Parse.Query(Game); +} + +function test_collections() { + + let collection = new TestCollection(); + + const query = new Parse.Query(Game); + query.equalTo("temperature", "hot"); + query.greaterThan("degreesF", 100); + + collection = query.collection(); + + collection.comparator = (object) => { + return object.get("temperature"); + }; + + collection.add([ + { "name": "Duke" }, + { "name": "Scarlett" } + ]); + + collection.fetch().then( + (data) => { + + }, + (error) => { + console.log("Error: " + error.code + " " + error.message); + } + ); + + const model = collection.at(0); + + // Or you can get it by Parse objectId. + const modelAgain = collection.get(model.id); + + // Remove "Duke" from the collection. + collection.remove(model); + + // Completely replace all items in the collection. + collection.reset([ + { "name": "Hawk" }, + { "name": "Jane" } + ]); +} + +function test_file() { + + const base64 = "V29ya2luZyBhdCBQYXJzZSBpcyBncmVhdCE="; + let file = new Parse.File("myfile.txt", { base64: base64 }); + + const bytes = [0xBE, 0xEF, 0xCA, 0xFE]; + file = new Parse.File("myfile.txt", bytes); + + file = new Parse.File("myfile.zzz", {}, "image/png"); + + const src = file.url(); + + file.save().then( + () => { + // The file has been saved to Parse. + }, + (error) => { + // The file either could n ot be read, or could not be saved to Parse. + }); + + Parse.Cloud.httpRequest({ url: file.url() }).then((response: Parse.Cloud.HttpResponse) => { + // result + }); + + // TODO: Check +} + +function test_analytics() { + + const dimensions = { + // Define ranges to bucket data points into meaningful segments + priceRange: '1000-1500', + // Did the user filter the query? + source: 'craigslist', + // Do searches happen more often on weekdays or weekends? + dayType: 'weekday' + }; + // Send the dimensions to Parse along with the 'search' event + Parse.Analytics.track('search', dimensions); + + const codeString = '404'; + Parse.Analytics.track('error', { code: codeString }) +} + +function test_relation() { + var game1 = new Game(); + var game2 = new Game(); + + new Parse.User().relation("games").query().find().then((g: Game[]) => { }); + new Parse.User().relation("games").add(game1) + new Parse.User().relation("games").add([game1, game2]) + + new Parse.User().relation("games").remove(game1) + new Parse.User().relation("games").remove([game1, game2]) +} + +function test_user() { + const user = new Parse.User(); + user.set("username", "my name"); + user.set("password", "my pass"); + user.set("email", "email@example.com"); + user.signUp(null, { useMasterKey: true }); +} + +function test_user_acl_roles() { + + const user = new Parse.User(); + user.set("username", "my name"); + user.set("password", "my pass"); + user.set("email", "email@example.com"); + + // other fields can be set just like with Parse.Object + user.set("phone", "415-392-0202"); + + const currentUser = Parse.User.current(); + if (currentUser) { + // do stuff with the user + } else { + // show the signup or login page + } + + Parse.User.become("session-token-here").then(function (user) { + // The current user is now set to user. + }, function (error) { + // The token could not be validated. + }); + + const game = new Game(); + game.set("score", new GameScore()); + game.setACL(new Parse.ACL(Parse.User.current())); + game.save().then((game: Game) => { }); + game.save(null, { useMasterKey: true }); + game.save({ score: '10' }, { useMasterKey: true }).then(function (game) { + // Update game then revert it to the last saved state. + game.set("score", '20'); + game.revert(); + }, function (error) { + // The save failed + }); + + const groupACL = new Parse.ACL(); + + const userList: Parse.User[] = [Parse.User.current()!]; + // userList is an array with the users we are sending this message to. + for (let i = 0; i < userList.length; i++) { + groupACL.setReadAccess(userList[i], true); + groupACL.setWriteAccess(userList[i], true); + } + + groupACL.setPublicReadAccess(true); + + game.setACL(groupACL); + + Parse.User.requestPasswordReset("email@example.com").then(function (data) { + // The current user is now set to user. + }, function (error) { + // The token could not be validated. + }); + + // By specifying no write privileges for the ACL, we can ensure the role cannot be altered. + const role = new Parse.Role("Administrator", groupACL); + role.getUsers().add(userList[0]); + role.getRoles().add(role); + role.save(); + + Parse.User.logOut().then(function (data) { + // logged out + }); +} + +function test_facebook_util() { + + Parse.FacebookUtils.init({ + appId: 'YOUR_APP_ID', // Facebook App ID + channelUrl: '//WWW.YOUR_DOMAIN.COM/channel.html', // Channel File + cookie: true, // enable cookies to allow Parse to access the session + xfbml: true // parse XFBML + }); + + Parse.FacebookUtils.logIn(null, { + success: (user: Parse.User) => { + if (!user.existed()) { + alert("User signed up and logged in through Facebook!"); + } else { + alert("User logged in through Facebook!"); + } + }, + error: (user: Parse.User, error: any) => { + alert("User cancelled the Facebook login or did not fully authorize."); + } + }); + + const user = Parse.User.current()!; + + if (!Parse.FacebookUtils.isLinked(user)) { + Parse.FacebookUtils.link(user, null, { + success: (user: any) => { + alert("Woohoo, user logged in with Facebook!"); + }, + error: (user: any, error: any) => { + alert("User cancelled the Facebook login or did not fully authorize."); + } + }); + } + + Parse.FacebookUtils.unlink(user, { + success: (user: Parse.User) => { + alert("The user is no longer associated with their Facebook account."); + } + }); +} + +function test_cloud_functions() { + + Parse.Cloud.run('hello', {}, { + success: (result: any) => { + // result + }, + error: (error: any) => { + } + }); + + Parse.Cloud.afterDelete('MyCustomClass', (request: Parse.Cloud.AfterDeleteRequest) => { + // result + }); + + Parse.Cloud.afterSave('MyCustomClass', (request: Parse.Cloud.AfterSaveRequest) => { + // result + }); + + Parse.Cloud.beforeDelete('MyCustomClass', (request: Parse.Cloud.BeforeDeleteRequest, + response: Parse.Cloud.BeforeDeleteResponse) => { + // result + }); + + const CUSTOM_ERROR_INVALID_CONDITION = 1001 + const CUSTOM_ERROR_IMMUTABLE_FIELD = 1002 + + Parse.Cloud.beforeSave('MyCustomClass', (request: Parse.Cloud.BeforeSaveRequest, + response: Parse.Cloud.BeforeSaveResponse) => { + + if (request.object.isNew()) { + if (!request.object.has('immutable')) return response.error('Field immutable is required') + } else { + const original = request.original; + if (original == null) { // When the object is not new, request.original must be defined + return response.error(CUSTOM_ERROR_INVALID_CONDITION, 'Original must me defined for an existing object') + } + + if (original.get('immutable') !== request.object.get('immutable')) { + return response.error(CUSTOM_ERROR_IMMUTABLE_FIELD, 'This field cannot be changed') + } + } + response.success() + }); + + Parse.Cloud.beforeFind('MyCustomClass', (request: Parse.Cloud.BeforeFindRequest) => { + let query = request.query; // the Parse.Query + let user = request.user; // the user + let isMaster = request.master; // if the query is run with masterKey + let isCount = request.count; // if the query is a count operation (available on parse-server 2.4.0 or up) + let isGet = request.isGet; // if the query is a get operation + + // All possible read preferences + request.readPreference = Parse.Cloud.ReadPreferenceOption.Primary + request.readPreference = Parse.Cloud.ReadPreferenceOption.PrimaryPreferred + request.readPreference = Parse.Cloud.ReadPreferenceOption.Secondary + request.readPreference = Parse.Cloud.ReadPreferenceOption.SecondaryPreferred + request.readPreference = Parse.Cloud.ReadPreferenceOption.Nearest + }); +} + +class PlaceObject extends Parse.Object { } + +function test_geo_points() { + + const point = new Parse.GeoPoint({ latitude: 40.0, longitude: -30.0 }); + + const userObject = Parse.User.current()!; + + // User's location + const userGeoPoint = userObject.get("location"); + + // Create a query for places + const query = new Parse.Query(Parse.User); + // Interested in locations near user. + query.near("location", userGeoPoint); + // Limit what could be a lot of points. + query.limit(10); + + const southwestOfSF = new Parse.GeoPoint(37.708813, -122.526398); + const northeastOfSF = new Parse.GeoPoint(37.822802, -122.373962); + + const query2 = new Parse.Query(PlaceObject); + query2.withinGeoBox("location", southwestOfSF, northeastOfSF); + + const query3 = new Parse.Query("PlaceObject").find().then((o: Parse.Object[]) => { }); +} + +function test_push() { + + Parse.Push.send({ + channels: ["Gia nts", "Mets"], + data: { + alert: "The Giants won against the Mets 2-3." + } + }, { + success: () => { + // Push was successful + }, + error: (error: any) => { + // Handle error + } + }); + + const query = new Parse.Query(Parse.Installation); + query.equalTo('injuryReports', true); + + Parse.Push.send({ + where: query, // Set our Installation query + data: { + alert: "Willie Hayes injured by own pop fly." + } + }, { + success: function () { + // Push was successful + }, + error: function (error: any) { + // Handle error + } + }); +} + +function test_view() { + + const model = Parse.User.current(); + const view = new Parse.View(); +} + +function test_promise() { + let resolved = Parse.Promise.as(true); + let rejected = Parse.Promise.error("an error object"); + Parse.Promise.when([resolved, rejected]).then(function () { + // success + }, function () { + // failed + }); + + // Test promise with a query + const query = new Parse.Query('Test'); + query.find() + .then(() => { + // success + }).catch(() => { + // error + }); + + // can check whether an object is a Parse.Promise object or not + Parse.Promise.is(resolved); +} + +function test_batch_operations() { + const game1 = new Game() + const game2 = new Game() + const games = [game1, game2] + + // Master key + Parse.Object.saveAll(games, { useMasterKey: true }) + Parse.Object.destroyAll(games, { useMasterKey: true }) + Parse.Object.fetchAll(games, { useMasterKey: true }) + Parse.Object.fetchAllIfNeeded(games, { useMasterKey: true }) + + // Session token + Parse.Object.saveAll(games, { sessionToken: '' }) + Parse.Object.destroyAll(games, { sessionToken: '' }) + Parse.Object.fetchAll(games, { sessionToken: '' }) + Parse.Object.fetchAllIfNeeded(games, { sessionToken: '' }) +} + +function test_query_subscribe() { + // create new query from Game object type + const query = new Parse.Query(Game); + + // create subscription to Game object + const subscription = query.subscribe(); + + // listen for new Game objects created on Parse server + subscription.on('create', (game: any) => { + console.log(game); + }); +} + diff --git a/types/parse/v1/tsconfig.json b/types/parse/v1/tsconfig.json new file mode 100644 index 0000000000..971be64447 --- /dev/null +++ b/types/parse/v1/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": ["../../"], + "paths": { + "parse": ["parse/v1"], + "parse/*": ["parse/v1/*"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "parse-tests.ts"] +} diff --git a/types/parse/v1/tslint.json b/types/parse/v1/tslint.json new file mode 100644 index 0000000000..e2172b7f24 --- /dev/null +++ b/types/parse/v1/tslint.json @@ -0,0 +1,81 @@ +{ + "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-const-enum": 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, + "use-default-type-parameter": false, + "void-return": false, + "whitespace": false + } +} diff --git a/types/passport-auth0/index.d.ts b/types/passport-auth0/index.d.ts index 5bcfced19c..a915c2b724 100644 --- a/types/passport-auth0/index.d.ts +++ b/types/passport-auth0/index.d.ts @@ -1,6 +1,8 @@ // Type definitions for passport-auth0 1.0 // Project: https://github.com/auth0/passport-auth0 // Definitions by: John Umeh +// Vishnu Sankar +// Duncan Hall // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -31,10 +33,11 @@ export interface StrategyOption { clientID: string; clientSecret: string; callbackURL: string; - + domain: string; scopeSeparator?: string; enableProof?: boolean; profileFields?: string[]; + state?: boolean; } export interface StrategyOptionWithRequest extends StrategyOption { diff --git a/types/passport-auth0/passport-auth0-tests.ts b/types/passport-auth0/passport-auth0-tests.ts index 76e7ca85a0..5f3437106a 100644 --- a/types/passport-auth0/passport-auth0-tests.ts +++ b/types/passport-auth0/passport-auth0-tests.ts @@ -15,7 +15,8 @@ const User = { passport.use(new auth0.Strategy({ clientID: process.env.PASSPORT_AUTH0_CLIENT_ID as string, clientSecret: process.env.PASSPORT_AUTH0_CLIENT_SECRET as string, - callbackURL: process.env.PASSPORT_AUTH0_CALLBACK_URL as string + callbackURL: process.env.PASSPORT_AUTH0_CALLBACK_URL as string, + domain : process.env.PASSPORT_AUTH0_DOMAIN as string }, (accessToken: string, refreshToken: string, extraParams: auth0.ExtraVerificationParams, profile: auth0.Profile, done: (error: any, user?: any) => void) => { User.findOrCreate(profile.id, profile.provider, (err, user) => { @@ -29,6 +30,7 @@ passport.use(new auth0.Strategy({ clientID: process.env.PASSPORT_AUTH0_CLIENT_ID as string, clientSecret: process.env.PASSPORT_AUTH0_CLIENT_SECRET as string, callbackURL: process.env.PASSPORT_AUTH0_CALLBACK_URL as string, + domain : process.env.PASSPORT_AUTH0_DOMAIN as string, passReqToCallback: true }, (req: express.Request, accessToken: string, refreshToken: string, profile: auth0.Profile, done: (error: any, user?: any) => void) => { @@ -42,7 +44,8 @@ passport.use(new auth0.Strategy({ passport.use(new auth0.Strategy({ clientID: process.env.PASSPORT_AUTH0_CLIENT_ID as string, clientSecret: process.env.PASSPORT_AUTH0_CLIENT_SECRET as string, - callbackURL: process.env.PASSPORT_AUTH0_CALLBACK_URL as string + callbackURL: process.env.PASSPORT_AUTH0_CALLBACK_URL as string, + domain : process.env.PASSPORT_AUTH0_DOMAIN as string }, (accessToken: string, refreshToken: string, extraParams: auth0.ExtraVerificationParams, profile: auth0.Profile, done: (error: any, user?: any, info?: any) => void) => { done(null, false, { message: 'Some error.' }); diff --git a/types/passport-azure-ad/bearer-strategy.d.ts b/types/passport-azure-ad/bearer-strategy.d.ts new file mode 100644 index 0000000000..6ea48809c1 --- /dev/null +++ b/types/passport-azure-ad/bearer-strategy.d.ts @@ -0,0 +1,34 @@ +import * as passport from "passport"; +import { Request } from "express"; +import { IBaseStrategyOption, ITokenPayload, VerifyCallback } from "./common"; + +export type VerifyBearerFunction = (token: ITokenPayload, done: VerifyCallback) => void; + +export type VerifyBearerFunctionWithReq = ( + req: Request, + token: ITokenPayload, + done: VerifyCallback +) => void; + +export interface IBearerStrategyOption extends IBaseStrategyOption { + audience?: string | string[]; + policyName?: String; + allowMultiAudiencesInToken?: boolean; + scope?: string[]; +} + +export interface IBearerStrategyOptionWithRequest extends IBearerStrategyOption { + passReqToCallback: true; +} + +export class BearerStrategy implements passport.Strategy { + constructor( + options: IBearerStrategyOptionWithRequest, + verify: VerifyBearerFunctionWithReq + ); + constructor(options: IBearerStrategyOption, verify: VerifyBearerFunction); + + name: string; + + authenticate(req: Request, options?: object): void; +} diff --git a/types/passport-azure-ad/common.d.ts b/types/passport-azure-ad/common.d.ts new file mode 100644 index 0000000000..49b04baef8 --- /dev/null +++ b/types/passport-azure-ad/common.d.ts @@ -0,0 +1,79 @@ +import { Request } from "express"; + +export interface IBaseStrategyOption { + identityMetadata: string; + clientID: string; + isB2C?: boolean; + validateIssuer?: boolean; + issuer?: string | string[]; + loggingLevel?: "info" | "warn" | "error"; + loggingNoPII?: boolean; + clockSkew?: number; +} + +export interface ITokenPayload { + /** An App ID URI. Identifies the intended recipient of the token. */ + aud?: string; + /** A security token service(STS) URI. Identifies the STS that constructs and returns the token, + * and the Azure AD tenant in which the user was authenticated.*/ + iss?: string; + /** "Issued At" indicates when the authentication for this token occurred. */ + iat?: number; + /** The "nbf" (not before) claim identifies the time before which the JWT must not be accepted for processing. */ + nbf?: number; + /** The "exp" (expiration time) claim identifies the expiration time on or after which the JWT must not be accepted for processing. */ + exp?: number; + /** The "Authentication context class" claim. A value of "0" indicates the end-user authentication did not meet the requirements of ISO/IEC 29115. */ + acr?: "0" | "1"; + /** An internal claim used by Azure AD to record data for token reuse. */ + aio?: string; + /** Identifies how the subject of the token was authenticated. */ + amr?: string[]; + /** GUID represents the application ID of the client using the token. */ + appid?: string; + /** Indicates how the client was authenticated. For a public client, the value is "0". + * If client ID and client secret are used, the value is "1". If a client certificate was used for authentication, the value is "2". */ + appidacr?: "0" | "1" | "2"; + /** Only present in v2.0 tokens. The application ID of the client using the token. */ + azp?: string; + /** Only present in v2.0 tokens. Indicates how the client was authenticated. + * For a public client, the value is "0". If client ID and client secret are used, the value is "1". If a client certificate was used for authentication, the value is "2". */ + azpacr?: "0" | "1" | "2"; + /** Provides object IDs that represent the subject's group memberships. */ + groups?: string | string[]; + /** Denoting the user is in at least one group. */ + hasgroups?: true; + /** Only present in v2.0 tokens. The primary username that represents the user. It could be an email address, phone number, or a generic username without a specified format */ + preferred_name?: string; + /** Provides a human-readable value that identifies the subject of the token. + * The value is not guaranteed to be unique, it is mutable, and it's designed to be used only for display purposes. The profile scope is required in order to receive this claim. */ + name?: string; + /** GUID represents a user. This ID uniquely identifies the user across applications. */ + oid?: string; + /** An internal claim used by Azure to revalidate tokens. */ + rh?: string; + /** The set of scopes exposed by your application for which the client application has requested (and received) consent. */ + scp?: string; + /** The set of permissions exposed by your application that the requesting application has been given permission to call. */ + roles?: string; + /** The principal about which the token asserts information, such as the user of an app. This value is immutable and cannot be reassigned or reused. + * It can be used to perform authorization checks safely, such as when the token is used to access a resource, + * and can be used as a key in database tables. Because the subject is always present in the tokens that Azure AD issues, + * we recommend using this value in a general-purpose authorization system. The subject is, however, a pairwise identifier - it is unique to a particular application ID. */ + sub?: string; + /** Represents the Azure AD tenant that the user is from. */ + tid?: string; + /** Only present in v1.0 tokens. Provides a human readable value that identifies the subject of the token. */ + unique_name?: string; + /** The username of the user. May be a phone number, email address, or unformatted string. */ + upn?: string; + /** An internal claim used by Azure to revalidate tokens. */ + uti?: string; + /** Indicates the version of the access token. */ + ver?: string; +} + +export interface VerifyCallback { + (error: any, user?: any, info?: any): void; +} + \ No newline at end of file diff --git a/types/passport-azure-ad/index.d.ts b/types/passport-azure-ad/index.d.ts new file mode 100644 index 0000000000..450d31064f --- /dev/null +++ b/types/passport-azure-ad/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for passport-azure-ad 4.0 +// Project: https://github.com/AzureAD/passport-azure-ad#readme +// Definitions by: Shekhar Nain +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export { ITokenPayload, VerifyCallback } from "./common"; +export { + BearerStrategy, + IBearerStrategyOption, + IBearerStrategyOptionWithRequest, + VerifyBearerFunction, + VerifyBearerFunctionWithReq +} from "./bearer-strategy"; +export { + OIDCStrategy, + IOIDCStrategyOption, + IOIDCStrategyOptionWithRequest, + IProfile, + VerifyOIDCFunction, + VerifyOIDCFunctionWithReq +} from "./oidc-strategy"; diff --git a/types/passport-azure-ad/oidc-strategy.d.ts b/types/passport-azure-ad/oidc-strategy.d.ts new file mode 100644 index 0000000000..672694d5a9 --- /dev/null +++ b/types/passport-azure-ad/oidc-strategy.d.ts @@ -0,0 +1,65 @@ +import * as passport from "passport"; +import { Request } from "express"; +import { IBaseStrategyOption, VerifyCallback } from "./common"; + +export interface IOIDCStrategyOption extends IBaseStrategyOption { + responseType: "code" | "code id_token" | "id_token code" | "id_token"; + responseMode: "query" | "form_post"; + redirectUrl: string; + allowHttpForRedirectUrl?: boolean; + clientSecret?: string; + thumbprint?: string; + privatePEMKey?: string; + useCookieInsteadOfSession?: boolean; + cookieEncryptionKeys?: {key: string, iv: string}[]; + nonceLifetime?: number; + nonceMaxAmount?: number; + scope?: string | string[]; +} + +export interface IOIDCStrategyOptionWithRequest extends IOIDCStrategyOption { + passReqToCallback: true; +} + +export interface IProfile { + sub?: string; + oid?: string; + upn?: string; + displayName?: string; + name?: { + familyName?: string; + givenName?: string; + middleName?: string; + }; + emails?: any; + _raw?: string; + _json?: any; +} + +export type VerifyOIDCFunction = + ((profile: IProfile, done: VerifyCallback) => void) | + ((iss: string, sub: string, done: VerifyCallback) => void) | + ((iss: string, sub: string, profile: IProfile, done: VerifyCallback) => void) | + ((iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, done: VerifyCallback) => void) | + ((iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void) | + ((iss: string, sub: string, profile: IProfile, jwtClaims: any, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void); + +export type VerifyOIDCFunctionWithReq = + ((req: Request, profile: IProfile, done: VerifyCallback) => void) | + ((req: Request, iss: string, sub: string, done: VerifyCallback) => void) | + ((req: Request, iss: string, sub: string, profile: IProfile, done: VerifyCallback) => void) | + ((req: Request, iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, done: VerifyCallback) => void) | + ((req: Request, iss: string, sub: string, profile: IProfile, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void) | + ((req: Request, iss: string, sub: string, profile: IProfile, jwtClaims: any, access_token: string, refresh_token: string, params: any, done: VerifyCallback) => void); + +export class OIDCStrategy implements passport.Strategy { + constructor( + options: IOIDCStrategyOptionWithRequest, + verify: VerifyOIDCFunction + ); + constructor(options: IOIDCStrategyOption, verify: VerifyOIDCFunctionWithReq); + + name: string; + + authenticate(req: Request, options?: object): void; +} diff --git a/types/passport-azure-ad/passport-azure-ad-tests.ts b/types/passport-azure-ad/passport-azure-ad-tests.ts new file mode 100644 index 0000000000..becac28160 --- /dev/null +++ b/types/passport-azure-ad/passport-azure-ad-tests.ts @@ -0,0 +1,42 @@ +import { Request } from "express"; +import { + BearerStrategy, + OIDCStrategy, + IBearerStrategyOptionWithRequest, + IOIDCStrategyOptionWithRequest, + VerifyBearerFunctionWithReq, + VerifyOIDCFunctionWithReq, + IProfile, + VerifyCallback +} from "passport-azure-ad"; + +const bearerStrategyOptions: IBearerStrategyOptionWithRequest = { + identityMetadata: "https://api.test.com", + clientID: "XXXXX", + passReqToCallback: true +}; + +const oidcStrategyOptions: IOIDCStrategyOptionWithRequest = { + identityMetadata: "https://api.test.com", + clientID: "XXXXX", + passReqToCallback: true, + responseType: "id_token", + responseMode: "query", + redirectUrl: "https://api.test.com" +}; + +const verifyBearer: VerifyBearerFunctionWithReq = (req, token, done) => { + if (!token.oid) + done(null, token); + else done(new Error("Invalid token")); +}; + +const verifyOidc: VerifyOIDCFunctionWithReq = (req: Request, profile: IProfile, done: VerifyCallback) => { + if (!profile.oid) + done(null, profile); + else done(new Error("Invalid token")); +}; + +new BearerStrategy(bearerStrategyOptions, verifyBearer); + +new OIDCStrategy(oidcStrategyOptions, verifyOidc); diff --git a/types/passport-azure-ad/tsconfig.json b/types/passport-azure-ad/tsconfig.json new file mode 100644 index 0000000000..1fc2742bd3 --- /dev/null +++ b/types/passport-azure-ad/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-azure-ad-tests.ts" + ] +} diff --git a/types/passport-azure-ad/tslint.json b/types/passport-azure-ad/tslint.json new file mode 100644 index 0000000000..95d5bcf169 --- /dev/null +++ b/types/passport-azure-ad/tslint.json @@ -0,0 +1,13 @@ +{ + "extends": "dtslint/dt.json", + "rules": { + // TODOs + "array-type": false, + "ban-types": false, + "callable-types": false, + "eofline": false, + "interface-name": false, + "jsdoc-format": false, + "no-trailing-whitespace": false + } +} 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 91adbb6567..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; @@ -21,12 +23,11 @@ export interface StrategyOption extends passport.AuthenticateOptions { scope?: string[]; userAgent?: string; - state?: boolean; authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } @@ -42,12 +43,12 @@ export interface _StrategyOptionsBase extends OAuth2StrategyOptionsWithoutRequir scope?: string[]; userAgent?: string; - state?: boolean; + state?: string; authorizationURL?: string; tokenURL?: string; scopeSeparator?: string; - customHeaders?: string; + customHeaders?: OutgoingHttpHeaders; userProfileURL?: string; } diff --git a/types/passport-local-mongoose/index.d.ts b/types/passport-local-mongoose/index.d.ts index 512b68179f..e175dc8d1e 100644 --- a/types/passport-local-mongoose/index.d.ts +++ b/types/passport-local-mongoose/index.d.ts @@ -10,18 +10,33 @@ declare module 'mongoose' { import passportLocal = require('passport-local'); + export interface AuthenticationResult { + user: any; + error: any; + } + // methods export interface PassportLocalDocument extends Document { + setPassword(password: string): Promise; setPassword(password: string, cb: (err: any, res: any) => void): void; - authenticate(password: string, cb: (err: any, res: any, error: any) => void): void; + changePassword(oldPassword: string, newPassword: string): Promise; + changePassword(oldPassword: string, newPassword: string, cb: (err: any, res: any) => void): void; + authenticate(password: string): Promise; + authenticate(password: string, cb: (err: any, user: any, error: any) => void): void; + resetAttempts(): Promise; + resetAttempts(cb: (err: any, res: any) => void): void; } // statics interface PassportLocalModel extends Model { - authenticate(): (username: string, password: string, cb: (err: any, res: T, error: any) => void) => void; + authenticate(): (username: string, password: string) => Promise; + authenticate(): (username: string, password: string, cb: (err: any, user: T | boolean, error: any) => void) => void; serializeUser(): (user: PassportLocalModel, cb: (err: any, id?: any) => void) => void; deserializeUser(): (username: string, cb: (err: any, user?: any) => void) => void; + + register(user: T, password: string): Promise; register(user: T, password: string, cb: (err: any, account: any) => void): void; + findByUsername(username: string, selectHashSaltFields: boolean): Query; findByUsername(username: string, selectHashSaltFields: boolean, cb: (err: any, account: any) => void): any; createStrategy(): passportLocal.Strategy; } diff --git a/types/passport-local-mongoose/tslint.json b/types/passport-local-mongoose/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/passport-local-mongoose/tslint.json +++ b/types/passport-local-mongoose/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/passport-oauth2/index.d.ts b/types/passport-oauth2/index.d.ts index 7d7f3de21d..28a1a06348 100644 --- a/types/passport-oauth2/index.d.ts +++ b/types/passport-oauth2/index.d.ts @@ -2,12 +2,15 @@ // Project: https://github.com/jaredhanson/passport-oauth2#readme // 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; @@ -31,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 = @@ -46,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 6a5d09ef27..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'; @@ -51,6 +52,39 @@ const err3 = new InternalOAuthError('Hello', {}); class MyStrategy extends OAuth2Strategy { useProtectedProperty() { - this._oauth2.get('http://www.example.com/profile', 'token', 'http://www.example.com/callback'); + 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); } } + +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/passport-windowsauth/index.d.ts b/types/passport-windowsauth/index.d.ts new file mode 100644 index 0000000000..dd425a1f59 --- /dev/null +++ b/types/passport-windowsauth/index.d.ts @@ -0,0 +1,49 @@ +// Type definitions for passport-windowsauth 3.0 +// Project: https://github.com/auth0/passport-windowsauth#readme +// Definitions by: Emily Marigold Klassen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import * as express from 'express'; +import * as passport from 'passport'; +import * as ldapjs from 'ldapjs'; +import { TlsOptions } from 'tls'; + +declare namespace windowsauth { + interface Options { + ldap?: { + url?: string + maxConnections?: number + base?: string + bindDN?: string + bindCredentials?: string + tlsOptions?: TlsOptions; + reconnect?: boolean | { + initialDelay?: number, + maxDelay?: number, + failAfter?: number + }; + timeout?: number; + connectTimeout?: number; + idleTimeout?: number; + binder?: ldapjs.Client + client?: ldapjs.Client + }; + integrated?: boolean; + getUserNameFromHeader?(req: express.Request): string; + passReqToCallback?: boolean; + usernameField?: string; + passwordField?: string; + } + type Verified = (err: Error | undefined | null, user?: object, info?: object) => void; + type Verify = (profile: passport.Profile, done: Verified) => void; + type VerifyWithReq = (req: express.Request, profile: passport.Profile, done: Verified) => void; +} + +declare class windowsauth extends passport.Strategy { + constructor(options: windowsauth.Options & {passReqToCallback: true}, verify: windowsauth.VerifyWithReq); + constructor(options: windowsauth.Options, verify: windowsauth.Verify); + constructor(verify: windowsauth.Verify); +} + +export = windowsauth; diff --git a/types/passport-windowsauth/passport-windowsauth-tests.ts b/types/passport-windowsauth/passport-windowsauth-tests.ts new file mode 100644 index 0000000000..cca632ed60 --- /dev/null +++ b/types/passport-windowsauth/passport-windowsauth-tests.ts @@ -0,0 +1,28 @@ +import * as passport from 'passport'; +import * as WindowsStrategy from 'passport-windowsauth'; + +const auth = new passport.Authenticator(); +auth.use(new WindowsStrategy({integrated: true}, (profile, done) => { + console.log(profile); + done(null, profile); +})); + +passport.use(new WindowsStrategy({ + ldap: { + url: 'ldap://wellscordoba.wellscordobabank.com/DC=wellscordobabank,DC=com', + base: 'DC=wellscordobabank,DC=com', + bindDN: 'someAccount', + bindCredentials: 'andItsPass' + } +}, (profile, done) => { + console.log('logged in', profile.id); + done(null, profile); +})); + +passport.use(new WindowsStrategy({ + integrated: true, + passReqToCallback: true +}, (req, profile, done) => { + console.log('logged in', req, profile.id); + done(null, profile); +})); diff --git a/types/passport-windowsauth/tsconfig.json b/types/passport-windowsauth/tsconfig.json new file mode 100644 index 0000000000..070b3d98ed --- /dev/null +++ b/types/passport-windowsauth/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-windowsauth-tests.ts" + ] +} diff --git a/types/passport-windowsauth/tslint.json b/types/passport-windowsauth/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/passport-windowsauth/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/passport/index.d.ts b/types/passport/index.d.ts index fe0c26c775..1a8afed691 100644 --- a/types/passport/index.d.ts +++ b/types/passport/index.d.ts @@ -45,6 +45,7 @@ declare namespace passport { successMessage?: boolean | string; successRedirect?: string; successReturnToOrRedirect?: string; + state?: string; pauseStream?: boolean; userProperty?: string; passReqToCallback?: boolean; diff --git a/types/paypal-rest-sdk/index.d.ts b/types/paypal-rest-sdk/index.d.ts index 414c3fa0f5..0d2eea80a9 100644 --- a/types/paypal-rest-sdk/index.d.ts +++ b/types/paypal-rest-sdk/index.d.ts @@ -162,7 +162,7 @@ export interface Transaction { }; notify_url?: string; order_url?: string; - readonly related_resources?: RelatedResources; + readonly related_resources?: RelatedResources[]; } export interface Payee { @@ -258,6 +258,22 @@ export interface Item { url?: string; } +export interface PayerInfo { + email?: string; + readonly salutation?: string; + readonly first_name?: string; + readonly middle_name?: string; + readonly last_name?: string; + readonly suffix?: string; + readonly payer_id?: string; + birth_date?: string; + tax_id?: string; + tax_id_type?: string; + country_code?: string; + billing_address?: Address; + readonly shipping_address?: Address; +} + export interface RefundRequest { amount?: Amount; description?: string; @@ -266,8 +282,7 @@ export interface RefundRequest { invoice_number?: string; refund_advice?: boolean; items?: Item[]; - // TODO: Type this https://developer.paypal.com/docs/api/payments/#definition-payer_info - payer_info?: any; + payer_info?: PayerInfo; supplementary_data?: any[]; } diff --git a/types/pbf/index.d.ts b/types/pbf/index.d.ts index fdcb9b53ce..692ca491bf 100644 --- a/types/pbf/index.d.ts +++ b/types/pbf/index.d.ts @@ -9,7 +9,7 @@ declare class Pbf { type: number; length: number; - constructor(buffer?: Uint8Array); + constructor(buffer?: Uint8Array|ArrayBuffer); destroy(): void; readFields(readField: (tag: number, result?: T, pbf?: Pbf) => void, result?: T, end?: number): T; diff --git a/types/pbf/pbf-tests.ts b/types/pbf/pbf-tests.ts index c0a8556c42..f6914f5e13 100644 --- a/types/pbf/pbf-tests.ts +++ b/types/pbf/pbf-tests.ts @@ -2,6 +2,7 @@ import Pbf = require('pbf'); const pbf = new Pbf(new Uint8Array(1)); new Pbf(); +new Pbf(new ArrayBuffer(8)); pbf.buf; pbf.pos; pbf.type; diff --git a/types/pdf2image/index.d.ts b/types/pdf2image/index.d.ts new file mode 100644 index 0000000000..b02ccb8852 --- /dev/null +++ b/types/pdf2image/index.d.ts @@ -0,0 +1,53 @@ +// Type definitions for pdf2image 1.2 +// Project: https://bitbucket.org/RicardoCacheira/pdf2image#readme +// Definitions by: taoqf +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.9 + +/** + * A token starts with the character '%' + * + * d - the page number, if the first page of the PDF is page 1 + * D - the page number, if the first page of the PDF is page 0 + * i - the processed page number, if the first processed page is page 1 + * I - the processed page number, if the first processed page is page 0 + * t - the total number of pages in the pdf + * T - the total of processed pages + * s - the name of the pdf file + * p - the path of the pdf file + * % - the character '%' + * {...} - a custom piece of code where all of the above values can be used + */ + +/// + +export type OutputFormat = ((pageNum: number, pageIndex: number, totalPagesProcessed: number, totalPDFPages: number, name: string, path: string, vm: typeof import ('vm')) => string) | string; + +export interface Options { + density: number; + height: number; + width: number; + outputType: 'jpg' | 'png' | '.jpg' | '.png'; + quality: number; + pages: '*' | string; // * | even | odd | '/1,/3,5-6,-8, 9-' + singleProcess: boolean; + backgroundColor: string; // #ffffff + outputFormat: OutputFormat; +} + +export interface ConvertedFile { + page: number; + index: number; + name: string; + path: string; +} + +export function convertPDF(pdfFilePath: string, options?: Partial): Promise; + +export interface Converter { + convertPDF(pdfFilePath: string): Promise; + convertPDFList(pdfList: string[]): Promise; +} + +export function compileConverter(options?: Partial): Converter; diff --git a/types/pdf2image/pdf2image-tests.ts b/types/pdf2image/pdf2image-tests.ts new file mode 100644 index 0000000000..5b12192b2d --- /dev/null +++ b/types/pdf2image/pdf2image-tests.ts @@ -0,0 +1,8 @@ +import { convertPDF } from 'pdf2image'; + +// converts all the pages of the given pdf using the default options +convertPDF('example.pdf').then( + (pageList) => { + console.log(pageList); + } +); diff --git a/types/pdf2image/tsconfig.json b/types/pdf2image/tsconfig.json new file mode 100644 index 0000000000..9593266a66 --- /dev/null +++ b/types/pdf2image/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", + "pdf2image-tests.ts" + ] +} \ No newline at end of file diff --git a/types/pdf2image/tslint.json b/types/pdf2image/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pdf2image/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pdfjs-dist/tslint.json b/types/pdfjs-dist/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/pdfjs-dist/tslint.json +++ b/types/pdfjs-dist/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/pdfmake/index.d.ts b/types/pdfmake/index.d.ts index fdc0a9de05..a812611400 100644 --- a/types/pdfmake/index.d.ts +++ b/types/pdfmake/index.d.ts @@ -2,7 +2,9 @@ // Project: http://pdfmake.org // Definitions by: Milen Stefanov // Rajab Shakirov +// Enzo Volkmann // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 declare module 'pdfmake/build/vfs_fonts' { let pdfMake: { @@ -16,15 +18,61 @@ declare module 'pdfmake/build/pdfmake' { let fonts: { [name: string]: TFontFamilyTypes }; function createPdf(documentDefinitions: TDocumentDefinitions): TCreatedPdf; - type pageSizeType = - '4A0' | '2A0' | 'A0' | 'A1' | 'A2' | 'A3' | 'A4' | 'A5' | 'A6' | 'A7' | 'A8' | 'A9' | 'A10' | - 'B0' | 'B1' | 'B2' | 'B3' | 'B4' | 'B5' | 'B6' | 'B7' | 'B8' | 'B9' | 'B10' | - 'C0' | 'C1' | 'C2' | 'C3' | 'C4' | 'C5' | 'C6' | 'C7' | 'C8' | 'C9' | 'C10' | - 'RA0' | 'RA1' | 'RA2' | 'RA3' | 'RA4' | - 'SRA0' | 'SRA1' | 'SRA2' | 'SRA3' | 'SRA4' | - 'EXECUTIVE' | 'FOLIO' | 'LEGAL' | 'LETTER' | 'TABLOID'; + enum PageSize { + A0_x_4 = '4A0', + A0_x_2 = '2A0', + AO = 'A0', + A1 = 'A1', + A2 = 'A2', + A3 = 'A3', + A4 = 'A4', + A5 = 'A5', + A6 = 'A6', + A7 = 'A7', + A8 = 'A8', + A9 = 'A9', + A1O = 'A10', + BO = 'B0', + B1 = 'B1', + B2 = 'B2', + B3 = 'B3', + B4 = 'B4', + B5 = 'B5', + B6 = 'B6', + B7 = 'B7', + B8 = 'B8', + B9 = 'B9', + B1O = 'B10', + CO = 'C0', + C1 = 'C1', + C2 = 'C2', + C3 = 'C3', + C4 = 'C4', + C5 = 'C5', + C6 = 'C6', + C7 = 'C7', + C8 = 'C8', + C9 = 'C9', + C1O = 'C10', + RA1 = 'RA1', + RA2 = 'RA2', + RA3 = 'RA3', + RA4 = 'RA4', + SRA1 = 'SRA1', + SRA2 = 'SRA2', + SRA3 = 'SRA3', + SRA4 = 'SRA4', + EXECUTIVE = 'EXECUTIVE', + FOLIO = 'FOLIO', + LEGAL = 'LEGAL', + LETTER = 'LETTER', + TABLOID = 'TABLOID' + } - type pageOrientationType = "portrait" | "landscape"; + enum PageOrientation { + PORTRAIT = 'PORTRAIT', + LANDSCAPE = 'LANDSCAPE' + } let pdfMake: pdfMakeStatic; @@ -48,18 +96,90 @@ declare module 'pdfmake/build/pdfmake' { type TDocumentHeaderFooterFunction = (currentPage: number, pageCount: number) => any; + type Margins = number | [number, number] | [number, number, number, number]; + + type Alignment = 'left' | 'right' | 'justify' | 'center' | string; + + interface Style { + font?: any; + fontSize?: number; + fontFeatures?: any; + bold?: boolean; + italics?: boolean; + alignment?: Alignment; + color?: string; + columnGap?: any; + fillColor?: string; + decoration?: any; + decorationany?: any; + decorationColor?: string; + background?: any; + lineHeight?: number; + characterSpacing?: number; + noWrap?: boolean; + markerColor?: string; + leadingIndent?: any; + [additionalProperty: string]: any; + } + + type TableRowFunction = (row: number) => number; + + interface TableLayoutFunctions { + hLineWidth?: (i: number, node: any) => number; + vLineWidth?: (i: number, node: any) => number; + hLineColor?: (i: number, node: any) => string; + vLineColor?: (i: number, node: any) => string; + fillColor?: (i: number, node: any) => string; + paddingLeft?: (i: number, node: any) => number; + paddingRight?: (i: number, node: any) => number; + paddingTop?: (i: number, node: any) => number; + paddingBottom?: (i: number, node: any) => number; + } + + interface TableCell { + text: string; + rowSpan?: number; + colSpan?: number; + fillColor?: string; + border?: [boolean, boolean, boolean, boolean]; + } + + interface Table { + widths?: Array<(string | number)>; + heights?: Array<(string | number)> | TableRowFunction; + headerRows?: number; + body: Content[][] | TableCell[][]; + layout?: string | TableLayoutFunctions; + } + + interface Content { + style?: 'string'; + margin?: Margins; + text?: string | string[] | Content[]; + columns?: Content[]; + stack?: Content[]; + image?: string; + width?: string | number; + height?: string | number; + fit?: [number, number]; + pageBreak?: 'before' | 'after'; + alignment?: Alignment; + table?: Table; + ul?: Content[]; + ol?: Content[]; + [additionalProperty: string]: any; + } + interface TDocumentDefinitions { info?: TDocumentInformation; - header?: any; - footer?: any; - content: any; - styles?: any; - pageSize?: pageSizeType; - pageOrientation?: pageOrientationType; - pageMargins?: [number, number, number, number]; - defaultStyle?: { - font?: string; - }; + header?: TDocumentHeaderFooterFunction; + footer?: TDocumentHeaderFooterFunction; + content: string | Content; + styles?: Style; + pageSize?: PageSize; + pageOrientation?: PageOrientation; + pageMargins?: Margins; + defaultStyle?: Style; } type CreatedPdfParams = ( diff --git a/types/pdfmake/pdfmake-tests.ts b/types/pdfmake/pdfmake-tests.ts index 0f23e5c5d5..1913e3fe8a 100644 --- a/types/pdfmake/pdfmake-tests.ts +++ b/types/pdfmake/pdfmake-tests.ts @@ -1,10 +1,1330 @@ import * as pdfMake from 'pdfmake/build/pdfmake'; import * as pdfFonts from 'pdfmake/build/vfs_fonts'; -const docDefinition = { content: 'This is an sample PDF printed with pdfMake' }; +const definitions = [ + { + content: [ + 'First paragraph', + 'Another paragraph, this time a little bit longer to make sure, this line will be divided into at least two lines' + ] + }, + { + content: [ + { + text: 'This is a header, using header style', + style: 'header' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 1 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'Subheader 2 - using subheader style', + style: 'subheader' + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. \n\n', + { + text: 'It is possible to apply multiple styles, ', + style: ['quote', 'small'] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + subheader: { + fontSize: 15, + bold: true + }, + quote: { + italics: true + }, + small: { + fontSize: 8 + } + } + }, + { + content: [ + { + text: 'This is a header (whole paragraph uses the same header style)\n\n', + style: 'header' + }, + { + text: [ + 'It is however possible to provide an array of texts ', + 'to the paragraph (instead of a single string) and have ', + { text: 'a better ', fontSize: 15, bold: true }, + 'control over it. \nEach inline can be ', + { text: 'styled ', fontSize: 20 }, + { text: 'independently ', italics: true, fontSize: 40 }, + 'then.\n\n' + ] + }, + { text: 'Mixing named styles and style-overrides', style: 'header' }, + { + style: 'bigger', + italics: false, + text: [ + 'We can also mix named-styles and style-overrides at both paragraph and inline level. ', + 'For example, this paragraph uses the "bigger" style, which changes fontSize to 15 and sets italics to true. ', + 'Texts are not italics though. It\'s because we\'ve overriden italics back to false at ', + 'the paragraph level. \n\n', + 'We can also change the style of a single inline. Let\'s use a named style called header: ', + { text: 'like here.\n', style: 'header' }, + 'It got bigger and bold.\n\n', + 'OK, now we\'re going to mix named styles and style-overrides at the inline level. ', + 'We\'ll use header style (it makes texts bigger and bold), but we\'ll override ', + 'bold back to false: ', + { text: 'wow! it works!', style: 'header', bold: false }, + '\n\nMake sure to take a look into the sources to understand what\'s going on here.' + ] + } + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + } + }, + { + content: [ + { + text: 'This paragraph uses header style and extends the alignment property', + style: 'header', + alignment: 'center' + }, + { + text: [ + 'This paragraph uses header style and overrides bold value setting it back to false.\n', + 'Header style in this example sets alignment to justify, so this paragraph should be rendered \n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Malit profecta versatur nomine ocurreret ' + ], + style: 'header', + bold: false + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'justify' + } + } + }, + { + content: [ + 'By default paragraphs are stacked one on top of (or actually - below) another. ', + 'It\'s possible however to split any paragraph (or even the whole document) into columns.\n\n', + 'Here we go with 2 star-sized columns, with justified text and gap set to 20:\n\n', + { + alignment: 'justify', + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nStar-sized columns have always equal widths, so if we define 3 of those, ', + 'it\'ll look like this (make sure to scroll to the next page, as we have a couple of more examples):\n\n', + { + columns: [ + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nYou can also specify accurate widths for some (or all columns)', + { + columns: [ + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: '*', + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + }, + { + width: 90, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' + } + ] + }, + '\nWe also support auto columns. They set their widths based on the content:\n\n', + { + columns: [ + { + width: 'auto', + text: 'auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining' + + ' space divided by the number of all star-sized columns.' + }, + { + width: 50, + text: 'this one has specific width set to 50' + }, + { + width: 'auto', + text: 'another auto column' + }, + { + width: '*', + text: 'This is a star-sized column. It should get the remaining space ' + + 'divided by the number of all star-sized columns.' + }, + ] + }, + '\nIf all auto columns fit within available width, the table does not occupy whole space:\n\n', + { + columns: [ + { + width: 'auto', + text: 'val1' + }, + { + width: 'auto', + text: 'val2' + }, + { + width: 'auto', + text: 'value3' + }, + { + width: 'auto', + text: 'value 4' + }, + ] + }, + '\nAnother cool feature of pdfmake is the ability to have nested elements.', + { + columns: [ + { + width: 100, + fontSize: 9, + text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ' + }, + [ + 'As you can see in the document definition - this column is not defined with ', + 'an object, but an array, which means it\'s treated as an array of paragraphs rendered one below another.', + 'Just like on the top-level of the document. Let\'s try to divide the remaing space into 3 star-sized columns:\n\n', + { + columns: [ + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + { text: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.' }, + ] + } + ] + ] + }, + '\n\nOh, don\'t forget, we can use everything from styling examples (named styles, custom overrides) here as well.\n\n', + 'For instance - our next paragraph will use the \'bigger\' style (with fontSize set to 15 and italics - true).', + ' We\'ll split it into three columns and make sure they inherit the style:\n\n', + { + style: 'bigger', + columns: [ + 'First column (BTW - it\'s defined as a single string value. pdfmake will turn it into appropriate structure ', + 'automatically and make sure it inherits the styles', + { + fontSize: 20, + text: 'In this column, we\'ve overriden fontSize to 20. It means the content should have italics=true' + + ' (inherited from the style) and be a little bit bigger' + }, + { + style: 'header', + text: 'Last column does not override any styling properties, but applies a new style (header) to itself.' + + ' Eventually - texts here have italics=true (from bigger) and derive fontSize from the style.' + + ' OK, but which one? Both styles define it. As we already know from our styling examples, multiple' + + ' styles can be applied to the element and their order is important. Because \'header\' style has been' + + ' set after \'bigger\' its fontSize takes precedence over the fontSize from \'bigger\'. This is how it works. ' + + 'You will find more examples in the unit tests.' + } + ] + }, + '\n\nWow, you\'ve read the whole document! Congratulations :D' + ], + styles: { + header: { + fontSize: 18, + bold: true + }, + bigger: { + fontSize: 15, + italics: true + } + }, + defaultStyle: { + columnGap: 20 + } + }, + { + content: [ + { text: 'Tables', style: 'header' }, + 'Official documentation is in progress, this document is just', + ' a glimpse of what is possible with pdfmake and its layout engine.', + { text: 'A simple table (no headers, no width specified, no spans, no styling)', + style: 'subheader' }, + 'The following table has nothing more than a body array', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + ['One value goes here', 'Another one here', 'OK?'] + ] + } + }, + { text: 'A simple table with nested elements', style: 'subheader' }, + 'It is of course possible to nest any other type of nodes available in ', + 'pdfmake inside table cells', + { + style: 'tableExample', + table: { + body: [ + ['Column 1', 'Column 2', 'Column 3'], + [ + { + stack: [ + 'Let\'s try an unordered list', + { + ul: [ + 'item 1', + 'item 2' + ] + } + ] + }, + [ + 'or a nested table', + { + table: { + body: [ + ['Col1', 'Col2', 'Col3'], + ['1', '2', '3'], + ['1', '2', '3'] + ] + }, + } + ], + { + text: [ + 'Inlines can be ', + { text: 'styled\n', italics: true }, + { text: 'easily as everywhere else', fontSize: 10 }] + } + ] + ] + } + }, + { text: 'Defining column widths', style: 'subheader' }, + 'Tables support the same width definitions as standard columns:', + { + bold: true, + ul: [ + 'auto', + 'star', + 'fixed value' + ] + }, + { + style: 'tableExample', + table: { + widths: [100, '*', 200, '*'], + body: [ + ['width=100', 'star-sized', 'width=200', 'star-sized'], + ['fixed-width cells have exactly the specified width', + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }, + { text: 'nothing interesting here', italics: true, color: 'gray' }] + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column, will wrap to accomodate all the text in this cell.', 'I am auto sized.'], + ] + } + }, + { + style: 'tableExample', + table: { + widths: ['*', 'auto'], + body: [ + ['This is a star-sized column. The next column over, an auto-sized column', + { text: 'I am auto sized.', noWrap: true }], + ] + } + }, + { text: 'Defining row heights', style: 'subheader' }, + { + style: 'tableExample', + table: { + heights: [20, 50, 70], + body: [ + ['row 1 with height 20', 'column B'], + ['row 2 with height 50', 'column B'], + ['row 3 with height 70', 'column B'] + ] + } + }, + 'With same height:', + { + style: 'tableExample', + table: { + heights: 40, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + 'With height from function:', + { + style: 'tableExample', + table: { + heights: (row: number) => { + return (row + 1) * 25; + }, + body: [ + ['row 1', 'column B'], + ['row 2', 'column B'], + ['row 3', 'column B'] + ] + } + }, + { text: 'Column/row spans', pageBreak: 'before', style: 'subheader' }, + 'Each cell-element can set a rowSpan or colSpan', + { + style: 'tableExample', + color: '#444', + table: { + widths: [200, 'auto', 'auto'], + headerRows: 2, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header with Colspan = 2', style: 'tableHeader', colSpan: 2, alignment: 'center' }, + {}, { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + [{ text: 'Header 1', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 2', style: 'tableHeader', alignment: 'center' }, + { text: 'Header 3', style: 'tableHeader', alignment: 'center' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + [{ rowSpan: 3, text: 'rowSpan set to 3\nLorem ipsum dolor sit amet' }, + 'Sample value 2', 'Sample value 3'], + ['', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', { colSpan: 2, rowSpan: 2, text: 'Both:\nrowSpan and colSpan\ncan be defined at the same time' }, ''], + ['Sample value 1', '', ''], + ] + } + }, + { text: 'Headers', pageBreak: 'before', style: 'subheader' }, + 'You can declare how many rows should be treated as a header. Headers are', + ' automatically repeated on the following pages', + { text: ['It is also possible to set keepWithHeaderRows to make sure there will be no page-break' + + 'between the header and these rows. Take a look at the document-definition and play with it. ' + + 'If you set it to one, the following table will automatically start on the next page, ' + + 'since there\'s not enough space for the first row to be rendered here'], color: 'gray', italics: true }, + { + style: 'tableExample', + table: { + headerRows: 1, + // dontBreakRows: true, + // keepWithHeaderRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + [ + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + 'Lorem ipsum dolor sit amet, ', + ] + ] + } + }, + { text: 'Styling tables', style: 'subheader' }, + 'You can provide a custom styler for the table. Currently it supports:', + { + ul: [ + 'line widths', + 'line colors', + 'cell paddings', + ] + }, + 'with more options coming soon...\n\npdfmake currently has a few predefined styles (see them on the next page)', + { text: 'noBorders:', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'noBorders' + }, + { text: 'headerLineOnly:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, + { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'headerLineOnly' + }, + { text: 'lightHorizontalLines:', fontSize: 14, bold: true, margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: 'lightHorizontalLines' + }, + { text: 'but you can provide a custom styler as well', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + headerRows: 1, + body: [ + [{ text: 'Header 1', style: 'tableHeader' }, { text: 'Header 2', style: 'tableHeader' }, { text: 'Header 3', style: 'tableHeader' }], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + hLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 2 : 1; + }, + vLineWidth: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 2 : 1; + }, + hLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.body.length) ? 'black' : 'gray'; + }, + vLineColor: (i: number, node: any) => { + return (i === 0 || i === node.table.widths.length) ? 'black' : 'gray'; + }, + // paddingLeft: function(i, node) { return 4; }, + // paddingRight: function(i, node) { return 4; }, + // paddingTop: function(i, node) { return 2; }, + // paddingBottom: function(i, node) { return 2; }, + // fillColor: (i: number, node: any) => { return null; } + } + }, + { text: 'zebra style', margin: [0, 20, 0, 8] }, + { + style: 'tableExample', + table: { + body: [ + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ['Sample value 1', 'Sample value 2', 'Sample value 3'], + ] + }, + layout: { + fillColor: (i: number, node: any) => { + return (i % 2 === 0) ? '#CCCCCC' : null; + } + } + }, + { text: 'Optional border', fontSize: 14, bold: true, pageBreak: 'before', margin: [0, 0, 0, 8] }, + 'Each cell contains an optional border property: an array of 4 booleans for left border, top border, right border, bottom border.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, true, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, true, false, false]' + }, + { + border: [false, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[false, false, false, false]' + }, + { + border: [true, true, true, true], + fillColor: '#eeeeee', + text: 'border:\n[true, true, true, true]' + } + ], + [ + { + rowSpan: 3, + border: [true, true, true, true], + fillColor: '#eeeeff', + text: 'rowSpan: 3\n\nborder:\n[true, true, true, true]' + }, + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, false, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, false, false, false]' + } + ], + [ + '', + { + colSpan: 2, + border: [true, true, true, true], + fillColor: '#eeffee', + text: 'colSpan: 2\n\nborder:\n[true, true, true, true]' + }, + '' + ], + [ + '', + { + border: undefined, + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [false, false, true, true], + fillColor: '#dddddd', + text: 'border:\n[false, false, true, true]' + } + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + 'For every cell without a border property, whether it has all borders or not is determined by ', + 'layout.defaultBorder, which is false in the table above and true (by default) in the table below.', + { + style: 'tableExample', + table: { + body: [ + [ + { + border: [false, false, false, false], + fillColor: '#eeeeee', + text: 'border:\n[false, false, false, false]' + }, + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + ], + [ + { + fillColor: '#dddddd', + text: 'border:\nundefined' + }, + { + fillColor: '#eeeeee', + text: 'border:\nundefined' + }, + { + border: [true, true, false, false], + fillColor: '#dddddd', + text: 'border:\n[true, true, false, false]' + }, + ] + ] + } + }, + 'And some other examples with rowSpan/colSpan...', + { + style: 'tableExample', + table: { + body: [ + [ + '', + 'column 1', + 'column 2', + 'column 3' + ], + [ + 'row 1', + { + rowSpan: 3, + colSpan: 3, + border: [true, true, true, true], + fillColor: '#cccccc', + text: 'rowSpan: 3\ncolSpan: 3\n\nborder:\n[true, true, true, true]' + }, + '', + '' + ], + [ + 'row 2', + '', + '', + '' + ], + [ + 'row 3', + '', + '', + '' + ] + ] + }, + layout: { + defaultBorder: false, + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { + colSpan: 3, + text: 'colSpan: 3\n\nborder:\n[false, false, false, false]', + fillColor: '#eeeeee', + border: [false, false, false, false] + }, + '', + '' + ], + [ + 'border:\nundefined', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + }, + { + style: 'tableExample', + table: { + body: [ + [ + { rowSpan: 3, text: 'rowSpan: 3\n\nborder:\n[false, false, false, false]', fillColor: '#eeeeee', border: [false, false, false, false] }, + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ], + [ + '', + 'border:\nundefined', + 'border:\nundefined' + ] + ] + } + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + margin: [0, 0, 0, 10] + }, + subheader: { + fontSize: 16, + bold: true, + margin: [0, 10, 0, 5] + }, + tableExample: { + margin: [0, 5, 0, 15] + }, + tableHeader: { + bold: true, + fontSize: 13, + color: 'black' + } + }, + defaultStyle: { + // alignment: 'justify' + } + }, + { + content: [ + { text: 'Unordered list', style: 'header' }, + { + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with longer lines', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list', style: 'header' }, + { + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with longer lines', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + 'item 3' + ] + }, + { text: '\n\nOrdered list should be descending', style: 'header' }, + { + reversed: true, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with start value', style: 'header' }, + { + start: 50, + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own values', style: 'header' }, + { + ol: [ + { text: 'item 1', counter: 10 }, + { text: 'item 2', counter: 20 }, + { text: 'item 3', counter: 30 }, + { text: 'item 4 without own value' } + ] + }, + { text: '\n\nNested lists (ordered)', style: 'header' }, + { + ol: [ + 'item 1', + [ + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.', + { + ol: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + } + ], + 'item 3\nsecond line of item3' + ] + }, + { text: '\n\nNested lists (unordered)', style: 'header' }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ul: [ + 'subitem 1', + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered lists inside columns', style: 'header' }, + { + columns: [ + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nOrdered lists inside columns', style: 'header' }, + { + columns: [ + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + }, + { + ol: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + ] + } + ] + }, + { text: '\n\nNested lists width columns', style: 'header' }, + { + ul: [ + 'item 1', + 'Lorem ipsum dolor sit amet', + { + ol: [ + [ + { + columns: [ + 'column 1', + { + stack: [ + 'column 2', + { + ul: [ + 'item 1', + 'item 2', + { + ul: [ + 'item', + 'item', + 'item', + ] + }, + 'item 4', + ] + } + ] + }, + 'column 3', + 'column 4', + ] + }, + 'subitem 1 in a vertical container', + 'subitem 2 in a vertical container', + ], + 'subitem 2', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + { + text: [ + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + ] + }, + + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 3 - Lorem ipsum dolor sit amet', + 'subitem 4', + 'subitem 5', + ] + }, + 'item 3\nsecond line of item3', + ] + }, + { text: '\n\nUnordered list with square marker type', style: 'header' }, + { + type: 'square', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list with circle marker type', style: 'header' }, + { + type: 'circle', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list', style: 'header' }, + { + color: 'blue', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored unordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list', style: 'header' }, + { + color: 'blue', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nColored ordered list with own marker color', style: 'header' }, + { + color: 'blue', + markerColor: 'red', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: lower-alpha', style: 'header' }, + { + type: 'lower-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list - type: upper-alpha', style: 'header' }, + { + type: 'upper-alpha', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + + { text: '\n\nOrdered list - type: upper-roman', style: 'header' }, + { + type: 'upper-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: lower-roman', style: 'header' }, + { + type: 'lower-roman', + ol: [ + 'item 1', + 'item 2', + 'item 3', + 'item 4', + 'item 5' + ] + }, + { text: '\n\nOrdered list - type: none', style: 'header' }, + { + type: 'none', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nUnordered list - type: none', style: 'header' }, + { + type: 'none', + ul: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own separator', style: 'header' }, + { + separator: ')', + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own complex separator', style: 'header' }, + { + separator: ['(', ')'], + ol: [ + 'item 1', + 'item 2', + 'item 3' + ] + }, + { text: '\n\nOrdered list with own items type', style: 'header' }, + { + ol: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'upper-roman' } + ] + }, + { text: '\n\nUnordered list with own items type', style: 'header' }, + { + ul: [ + 'item 1', + { text: 'item 2', listType: 'none' }, + { text: 'item 3', listType: 'circle' } + ] + }, + ], + styles: { + header: { + bold: true, + fontSize: 15 + } + }, + defaultStyle: { + fontSize: 12 + } + }, + { + content: [ + { + stack: [ + 'This header has both top and bottom margins defined', + { text: 'This is a subheader', style: 'subheader' }, + ], + style: 'header' + }, + { + text: [ + 'Margins have slightly different behavior than other layout properties. ', + 'They are not inherited, unlike anything else. They\'re applied only to those nodes which explicitly ', + 'set margin or style property.\n', + ] + }, + { + text: 'This paragraph (consisting of a single line) directly sets top and bottom margin to 20', + margin: [0, 20], + }, + { + stack: [ + { + text: [ + 'This line begins a stack of paragraphs. The whole stack uses a ', + { text: 'superMargin', italics: true }, + ' style (with margin and fontSize properties).', + ] + }, + { text: ['When you look at the', { text: ' document definition', italics: true }, + ', you will notice that fontSize is inherited by all paragraphs inside the stack.'] }, + 'Margin however is only applied once (to the whole stack).' + ], + style: 'superMargin' + }, + { + stack: [ + 'I\'m not sure yet if this is the desired behavior. I find it a better approach however.', + ' One thing to be considered in the future is an explicit layout property called inheritMargin which could opt-in the inheritance.\n\n', + { + fontSize: 15, + text: [ + 'Currently margins for ', + /* the following margin definition doesn't change anything */ + { text: 'inlines', margin: 20 }, + ' are ignored\n\n' + ], + }, + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + 'Lorem ipsum dolor sit amet, consectetur adipisicing elit.\n', + ], + margin: [0, 20, 0, 0], + alignment: 'justify' + } + ], + styles: { + header: { + fontSize: 18, + bold: true, + alignment: 'right', + margin: [0, 190, 0, 80] + }, + subheader: { + fontSize: 14 + }, + superMargin: { + margin: [20, 0, 40, 0], + fontSize: 15 + } + } + }, + { + content: [ + 'pdfmake (since it\'s based on pdfkit) supports JPEG and PNG format', + 'If no width/height/fit is provided, image original size will be used', + { + image: 'sampleImage.jpg', + }, + 'If you specify width, image will scale proportionally', + { + image: 'sampleImage.jpg', + width: 150 + }, + 'If you specify both width and height - image will be stretched', + { + image: 'sampleImage.jpg', + width: 150, + height: 150, + }, + 'You can also fit the image inside a rectangle', + { + image: 'sampleImage.jpg', + fit: [100, 100], + pageBreak: 'after' + }, + // Warning! Make sure to copy this definition and paste it to an + // external text editor, as the online AceEditor has some troubles + // with long dataUrl lines and the following image values look like + // they're empty. + 'Images can be also provided in dataURL format...', + { + image: 'data:image/gif;base64,...', + width: 200 + }, + 'or be declared in an "images" dictionary and referenced by name', + { + image: 'building', + width: 200 + }, + ], + images: { + building: 'data:image/gif;base64,...' + } + } +]; const createPdf = () => { const pdf = pdfMake; pdf.vfs = pdfFonts.pdfMake.vfs; - pdfMake.createPdf(docDefinition).download(); + + for (const definition of definitions) { + const typedDefinition: pdfMake.TDocumentDefinitions = definition; + pdfMake.createPdf(typedDefinition).download(); + } }; diff --git a/types/pg/index.d.ts b/types/pg/index.d.ts index 621a3aa1b8..44863aee0b 100644 --- a/types/pg/index.d.ts +++ b/types/pg/index.d.ts @@ -18,6 +18,7 @@ export interface ConnectionConfig { connectionString?: string; keepAlive?: boolean; stream?: stream.Duplex; + statement_timeout?: false | number; } export interface Defaults extends ConnectionConfig { @@ -153,7 +154,7 @@ export class Pool extends events.EventEmitter { end(callback: () => void): void; query(queryStream: T): T; - query(queryConfig: QueryArrayConfig): Promise; + query(queryConfig: QueryArrayConfig, values?: any[]): Promise; query(queryConfig: QueryConfig): Promise; query(queryTextOrConfig: string | QueryConfig, values?: any[]): Promise; query(queryConfig: QueryArrayConfig, callback: (err: Error, result: QueryArrayResult) => void): Query; @@ -171,7 +172,7 @@ export class ClientBase extends events.EventEmitter { connect(callback: (err: Error) => void): void; query(queryStream: T): T; - query(queryConfig: QueryArrayConfig): Promise; + query(queryConfig: QueryArrayConfig, values?: any[]): Promise; query(queryConfig: QueryConfig): Promise; query(queryTextOrConfig: string | QueryConfig, values?: any[]): Promise; query(queryConfig: QueryArrayConfig, callback: (err: Error, result: QueryArrayResult) => void): Query; diff --git a/types/phantom/tslint.json b/types/phantom/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/phantom/tslint.json +++ b/types/phantom/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/phonegap/tslint.json b/types/phonegap/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/phonegap/tslint.json +++ b/types/phonegap/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/physijs/test/collisions.ts b/types/physijs/test/collisions.ts index 20493189e0..41f09e351d 100644 --- a/types/physijs/test/collisions.ts +++ b/types/physijs/test/collisions.ts @@ -90,7 +90,7 @@ spawnBox = (function() { var box_geometry = new THREE.BoxGeometry( 4, 4, 4 ), handleCollision = function( collided_with ) { - var target = this; + var target = this as any; target.collisions = 0; switch (++target.collisions) { @@ -168,4 +168,4 @@ render = function() { render_stats.update(); }; -window.onload = initScene; \ No newline at end of file +window.onload = initScene; diff --git a/types/physijs/test/vehicle.ts b/types/physijs/test/vehicle.ts index b8643de3b0..37f32279a8 100644 --- a/types/physijs/test/vehicle.ts +++ b/types/physijs/test/vehicle.ts @@ -186,11 +186,11 @@ initScene = function() { ); } - input = { + input = { power: null, direction: null, steering: 0 - }; + } as any; document.addEventListener('keydown', function( ev ) { switch ( ev.keyCode ) { case 37: // left diff --git a/types/physijs/tslint.json b/types/physijs/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/physijs/tslint.json +++ b/types/physijs/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/pigpio/index.d.ts b/types/pigpio/index.d.ts index 79d0ebe0f9..8eaa6491bb 100644 --- a/types/pigpio/index.d.ts +++ b/types/pigpio/index.d.ts @@ -1,6 +1,6 @@ -// Type definitions for pigpio 0.4 +// Type definitions for pigpio 1.2 // Project: https://github.com/fivdi/pigpio -// Definitions by: ManerFan +// Definitions by: ManerFan , erikma // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped /// @@ -424,3 +424,27 @@ export function configureClock(microseconds: number, peripheral: number): void; * @param port an unsigned integer specifying the pigpio socket port number */ export function configureSocketPort(port: number): void; + +/** + * Returns the Raspberry Pi hardware revision as an unsigned integer. Returns 0 + * if the hardware revision can not be determined. + */ +export function hardwareRevision(): number; + +/** + * Gets the current unsigned 32-bit integer value of the number of microseconds + * since system boot. This value wraps around the 32-bit space in just over an hour. + * Use tickDiff() to get the difference between two tick values, to + * ensure the correct JavaScript operations are used to account for the possibility + * of overflow. + */ +export function getTick(): number; + +/** + * Returns the difference in microseconds between the end and start tick counts. + * The tick counts can be retrieved using getTick(), or may be passed + * in a GPIO event callback. + * @param startTick The start of the measured interval. An unsigned integer tick value. + * @param endTick The end of the measured interval. An unsigned integer tick value. + */ +export function tickDiff(startTick: number, endTick: number): number; diff --git a/types/pigpio/pigpio-tests.ts b/types/pigpio/pigpio-tests.ts index 90e7d4485d..f756058b03 100644 --- a/types/pigpio/pigpio-tests.ts +++ b/types/pigpio/pigpio-tests.ts @@ -880,6 +880,15 @@ import * as assert from 'assert'; }, 2000); })(); +(function tickAndTickDiff(): void { + const startTick: number = pigpio.getTick(); + setTimeout(() => { + const endTick: number = pigpio.getTick(); + const diff: number = pigpio.tickDiff(startTick, endTick); + assert.ok(diff > 0, 'expected tick count to increase across a timer call'); + }, 50); +})(); + (function gpio_glitch_filter(): void { const Gpio = pigpio.Gpio; const input = new Gpio(7, { diff --git a/types/pikaday-time/tslint.json b/types/pikaday-time/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/pikaday-time/tslint.json +++ b/types/pikaday-time/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/pikaday/index.d.ts b/types/pikaday/index.d.ts index 7f2fb7eca4..63967d3169 100644 --- a/types/pikaday/index.d.ts +++ b/types/pikaday/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for pikaday 1.6 +// Type definitions for pikaday 1.7 // Project: https://github.com/dbushell/Pikaday // Definitions by: Rudolph Gottesheim // Åke Wivänge +// Istvan Mezo // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -173,6 +174,11 @@ declare namespace Pikaday { */ bound?: boolean; + /** + * Data-attribute on the input field with an aria assistance test (only applied when bound is set) + */ + ariaLabel?: string; + /** * Preferred position of the datepicker relative to the form field * (e.g. 'top right'). Automatic adjustment may occur to avoid @@ -241,6 +247,11 @@ declare namespace Pikaday { */ showWeekNumber?: boolean; + /** + * Select a whole week instead of a day (default false) + */ + pickWholeWeek?: boolean; + /** * Reverse the calendar for right-to-left languages. Default: false. */ @@ -266,6 +277,11 @@ declare namespace Pikaday { */ showDaysInNextAndPreviousMonths?: boolean; + /** + * Allows user to select date that is in the next or previous months (default: false) + */ + enableSelectionDaysInNextAndPreviousMonths?: boolean; + /** * Number of visible calendars. */ @@ -278,12 +294,22 @@ declare namespace Pikaday { */ mainCalendar?: string; + /** + * Array of dates that you would like to differentiate from regular days (e.g. ['Sat Jun 28 2017', 'Sun Jun 29 2017', 'Tue Jul 01 2017',]) + */ + events?: string[]; + /** * Define a class name that can be used as a hook for styling different * themes. Default: null. */ theme?: string; + /** + * Defines if the field is blurred when a date is selected (default true) + */ + blurFieldOnSelect?: boolean; + /** * The default flag for moment's strict date parsing (requires Moment.js for custom formatting). Default: false */ @@ -320,5 +346,10 @@ declare namespace Pikaday { * Callback function for when the picker draws a new month. */ onDraw?(): void; + + /** + * Enable keyboard input support. Default: true + */ + keyboardInput?: boolean; } } diff --git a/types/pikaday/pikaday-tests.ts b/types/pikaday/pikaday-tests.ts index 3f77683cd4..14250d0df3 100644 --- a/types/pikaday/pikaday-tests.ts +++ b/types/pikaday/pikaday-tests.ts @@ -67,6 +67,7 @@ new Pikaday({field: $('#datepicker')[0]}); format: 'YYYY-MM-DD', trigger: document.getElementById('datepicker'), bound: false, + ariaLabel: 'myLabel', position: 'top right', reposition: false, container: document.getElementById('myTag'), @@ -79,20 +80,25 @@ new Pikaday({field: $('#datepicker')[0]}); disableDayFn: (date) => true, yearRange: [2000, 2020], showWeekNumber: true, + pickWholeWeek: true, isRTL: true, yearSuffix: 'r', showMonthAfterYear: false, showDaysInNextAndPreviousMonths: true, + enableSelectionDaysInNextAndPreviousMonths: true, numberOfMonths: 2, mainCalendar: 'right', + events: ['Sat Jun 28 2017'], theme: 'myTheme', + blurFieldOnSelect: false, formatStrict: true, toString: (date) => '2017-08-23', parse: () => new Date('2017-08-23'), onSelect: () => {}, onOpen: () => {}, onClose: () => {}, - onDraw: () => {} + onDraw: () => {}, + keyboardInput: false }); })(); diff --git a/types/pikaday/tslint.json b/types/pikaday/tslint.json index 495d29983d..1c36270d47 100644 --- a/types/pikaday/tslint.json +++ b/types/pikaday/tslint.json @@ -1,5 +1,6 @@ { "extends": "dtslint/dt.json", "rules": { + "no-angle-bracket-type-assertion": false } } diff --git a/types/pino-http/index.d.ts b/types/pino-http/index.d.ts new file mode 100644 index 0000000000..a93abf406f --- /dev/null +++ b/types/pino-http/index.d.ts @@ -0,0 +1,28 @@ +// Type definitions for pino-http 4.0 +// Project: https://github.com/pinojs/pino-http#readme +// Definitions by: Christian Rackerseder +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { IncomingMessage, ServerResponse } from 'http'; +import { Level, Logger, LoggerOptions } from 'pino'; + +export = PinoHttp; + +declare function PinoHttp(opts?: PinoHttp.Options): PinoHttp.HttpLogger; + +declare namespace PinoHttp { + type HttpLogger = (req: IncomingMessage, res: ServerResponse) => void; + + interface Options extends LoggerOptions { + logger?: Logger; + genReqId?: (req: IncomingMessage) => number; + useLevel?: Level; + } +} + +declare module 'http' { + interface IncomingMessage { + log: Logger; + } +} diff --git a/types/pino-http/pino-http-tests.ts b/types/pino-http/pino-http-tests.ts new file mode 100644 index 0000000000..96207c8d9d --- /dev/null +++ b/types/pino-http/pino-http-tests.ts @@ -0,0 +1,16 @@ +import http = require('http'); +import pino = require('pino'); +import pinoHttp = require('pino-http'); + +const logger = pino(); +const httpLogger = pinoHttp(); + +function handle(req: http.IncomingMessage, res: http.ServerResponse) { + httpLogger(req, res); + req.log.info('something else'); +} + +pinoHttp({ logger }); +pinoHttp({ genReqId: (req) => req.statusCode || 200 }); +pinoHttp({ useLevel: 'error' }); +pinoHttp({ prettyPrint: true }); diff --git a/types/pino-http/tsconfig.json b/types/pino-http/tsconfig.json new file mode 100644 index 0000000000..3adac9b376 --- /dev/null +++ b/types/pino-http/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", + "pino-http-tests.ts" + ] +} diff --git a/types/pino-http/tslint.json b/types/pino-http/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pino-http/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pino/index.d.ts b/types/pino/index.d.ts index 71cb957643..8efaa85d33 100644 --- a/types/pino/index.d.ts +++ b/types/pino/index.d.ts @@ -1,17 +1,20 @@ -// Type definitions for pino 5.6 +// Type definitions for pino 5.8 // Project: https://github.com/pinojs/pino.git // Definitions by: Peter Snider // BendingBender // Christian Rackerseder // GP +// Alex Ferrando +// Oleksandr Sidko // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// -import * as stream from 'stream'; -import * as http from 'http'; -import { EventEmitter } from 'events'; +import stream = require('stream'); +import http = require('http'); +import EventEmitter = require('events'); +import SonicBoom = require('sonic-boom'); export = P; @@ -20,7 +23,7 @@ export = P; * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; /** * @param [options]: an options object @@ -28,7 +31,7 @@ declare function P(optionsOrStream?: P.LoggerOptions | stream.Writable | stream. * relative protocol is enabled. Default: process.stdout * @returns a new logger instance. */ -declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream): P.Logger; +declare function P(options: P.LoggerOptions, stream: stream.Writable | stream.Duplex | stream.Transform | NodeJS.WritableStream | SonicBoom): P.Logger; declare namespace P { /** @@ -75,11 +78,6 @@ declare namespace P { * The default time function for Pino. Returns a string like `,"time":1493426328206`. */ epochTime: TimeFn; - /** - * Returns an ISO formatted string like `,"time":"2017-04-29T004749.354Z"`. It is highly recommended that you avoid this function. - * It incurs a significant performance penalty. - */ - slowTime: TimeFn; /** * Returns an empty string. This function is used when the `timestamp` option is set to `false`. */ @@ -87,12 +85,36 @@ declare namespace P { }; /** - * Provides access to the CLI log prettifier as an API. - * This can also be enabled via the constructor by setting the `prettyPrint` option to either `true` or a configuration object described in this section. - * @param [options]: an options object - * @returns A transform stream to be used as input for the constructor. + * Create a Pino Destination instance: a stream-like object with significantly more throughput (over 30%) than a standard Node.js stream. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function */ - function pretty(options?: PrettyOptions): stream.Transform; + function destination(fileDescriptor?: string | number): SonicBoom; + + /** + * Create an extreme mode destination. This yields an additional 60% performance boost. + * There are trade-offs that should be understood before usage. + * @param [fileDescriptor]: File path or numerical file descriptor, by default 1 + * @returns A Sonic-Boom stream to be used as destination for the pino function + */ + function extreme(fileDescriptor?: string | number): SonicBoom; + + /** + * The pino.final method can be used to create an exit listener function. + * This listener function can be supplied to process exit events. + * The exit listener function will cal the handler with + * @param [logger]: pino logger that serves as reference for the final logger + * @param [handler]: Function that will be called by the handler returned from this function + * @returns Exit listener function that can be supplied to process exit events and will call the supplied handler function + */ + function final(logger: Logger, handler: (error: Error, finalLogger: Logger, ...args: any[]) => void): (error: Error | null, ...args: any[]) => void; + + /** + * The pino.final method can be used to acquire a final logger instance that synchronously flushes on every write. + * @param [logger]: pino logger that serves as reference for the final logger + * @returns Final, synchronous logger + */ + function final(logger: Logger): Logger; interface LevelMapping { /** @@ -128,19 +150,6 @@ declare namespace P { * Caution: any sort of formatted time will significantly slow down Pino's performance. */ timestamp?: TimeFn | false; - /** - * @deprecated - * This option is scheduled to be removed in Pino 5.0.0. Use `timestamp: pino.stdTimeFunctions.slowTime` instead. - * Outputs ISO time stamps ('2016-03-09T15:18:53.889Z') instead of Epoch time stamps (1457536759176). - * WARNING: This option carries a 25% performance drop, we recommend using default Epoch timestamps and transforming logs after if required. - * The pino -t command will do this for you (see CLI). Default: `false`. - */ - slowtime?: boolean; - /** - * Enables extreme mode, yields an additional 60% performance (from 250ms down to 100ms per 10000 ops). - * There are trade-off's should be understood before usage. See Extreme mode explained. Default: `false`. - */ - extreme?: boolean; /** * One of the supported levels or `silent` to disable logging. Any other value defines a custom level and * requires supplying a level value via `levelVal`. Default: 'info'. @@ -150,6 +159,10 @@ declare namespace P { * Outputs the level as a string instead of integer. Default: `false`. */ useLevelLabels?: boolean; + /** + * Changes the property `level` to any string value you pass in. Default: 'level' + */ + changeLevelName?: string; /** * Use this option to define additional logging levels. * The keys of the object correspond the namespace of the log level, and the values should be the numerical value of the level. @@ -161,6 +174,20 @@ declare namespace P { * Warning: this option may not be supported by downstream transports. */ useOnlyCustomLevels?: boolean; + + /** + * As an array, the redact option specifies paths that should have their values redacted from any log output. + * + * Each path must be a string using a syntax which corresponds to JavaScript dot and bracket notation. + * + * If an object is supplied, three options can be specified: + * + * paths (String[]): Required. An array of paths + * censor (String): Optional. A value to overwrite key which are to be redacted. Default: '[Redacted]' + * remove (Boolean): Optional. Instead of censoring the value, remove both the key and the value. Default: false + */ + redact?: string[] | redactOptions; + /** * When defining a custom log level via level, set to an integer value to define the new level. Default: `undefined`. */ @@ -217,13 +244,12 @@ declare namespace P { interface PrettyOptions { /** - * If set to true, it will only covert the unix timestamp to ISO 8601 date format, and reserialize the JSON (equivalent to pino -t). + * Translate the epoch time value into a human readable date and time string. + * This flag also can set the format string to apply when translating the date to human readable format. + * The default format is yyyy-mm-dd HH:MM:ss.l o in UTC. + * For a list of available pattern letters see the {@link https://www.npmjs.com/package/dateformat|dateformat documentation}. */ - timeTransOnly?: boolean; - /** - * A custom function to format the line, is passed the JSON object as an argument and should return a string value. - */ - formatter?(log: LogDescriptor): string; + translateTime?: boolean | string; /** * If set to true, it will print the name of the log level as the first field in the log line. Default: `false`. */ @@ -235,7 +261,24 @@ declare namespace P { /** * If set to true, will add color information to the formatted output message. Default: `false`. */ - forceColor?: boolean; + colorize?: boolean; + /** + * Appends carriage return and line feed, instead of just a line feed, to the formatted log line. + */ + crlf?: boolean; + /** + * Define the log keys that are associated with error like objects. Default: ["err", "error"] + */ + errorLikeObjectKeys?: string[]; + /** + * When formatting an error object, display this list of properties. + * The list should be a comma separated list of properties. Default: '' + */ + errorProps?: string; + /** + * Specify a search pattern according to {@link http://jmespath.org|jmespath} + */ + search?: string; } type Level = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace'; @@ -408,4 +451,10 @@ declare namespace P { (msg: string, ...args: any[]): void; (obj: object, msg?: string, ...args: any[]): void; } + + interface redactOptions { + paths: string[]; + censor?: string; + remove?: boolean; + } } diff --git a/types/pino/pino-tests.ts b/types/pino/pino-tests.ts index 356f84da30..3a6283c3e4 100644 --- a/types/pino/pino-tests.ts +++ b/types/pino/pino-tests.ts @@ -7,9 +7,9 @@ const error = log.error; info('hello world'); error('this is at error level'); info('the answer is %d', 42); -info({obj: 42}, 'hello world'); -info({obj: 42, b: 2}, 'hello world'); -info({obj: {aa: 'bbb'}}, 'another'); +info({ obj: 42 }, 'hello world'); +info({ obj: 42, b: 2 }, 'hello world'); +info({ obj: { aa: 'bbb' } }, 'another'); setImmediate(info, 'after setImmediate'); error(new Error('an error')); @@ -22,15 +22,6 @@ const log2: pino.Logger = pino({ } }); -const pretty = pino.pretty(); -pretty.pipe(process.stdout); -const log3 = pino({ - name: 'app', - safe: true -}, pretty); -log3.child({widget: 'foo'}).info('hello'); -log3.child({widget: 'bar'}).warn('hello 2'); - pino({ browser: { write(o) { @@ -50,27 +41,27 @@ pino({ }); pino({ base: null }); -pino({ base: { foo: 'bar' } }); +pino({ base: { foo: 'bar' }, changeLevelName: 'severity' }); if ('pino' in log) console.log(`pino version: ${log.pino}`); -log.child({a: 'property'}).info('hello child!'); +log.child({ a: 'property' }).info('hello child!'); log.level = 'error'; log.info('nope'); -const child = log.child({foo: 'bar'}); +const child = log.child({ foo: 'bar' }); child.info('nope again'); child.level = 'info'; child.info('hooray'); log.info('nope nope nope'); -log.child({foo: 'bar', level: 'debug'}).debug('debug!'); +log.child({ foo: 'bar', level: 'debug' }).debug('debug!'); const customSerializers = { test() { return 'this is my serializer'; } }; -pino().child({serializers: customSerializers}).info({test: 'should not show up'}); -const child2 = log.child({father: true}); -const childChild = child2.child({baby: true}); +pino().child({ serializers: customSerializers }).info({ test: 'should not show up' }); +const child2 = log.child({ father: true }); +const childChild = child2.child({ baby: true }); log.level = 'info'; if (log.levelVal === 30) { @@ -100,3 +91,48 @@ logstderr.error('on stderr instead of stdout'); log.useLevelLabels = true; log.info('lol'); log.level === 'info'; + +const extremeDest = pino.extreme(); +const logExtreme = pino(extremeDest); + +const handler = pino.final(logExtreme, (err: Error, finalLogger: pino.BaseLogger) => { + if (err) { + finalLogger.error(err, 'error caused exit'); + } +}); + +handler(new Error('error')); + +const redacted = pino({ + redact: ['path'] +}); + +redacted.info({ + msg: 'logged with redacted properties', + path: 'Not shown' +}); + +const anotherRedacted = pino({ + redact: { + paths: ['anotherPath'], + censor: 'Not the log you\re looking for' + } +}); + +anotherRedacted.info({ + msg: 'another logged with redacted properties', + anotherPath: 'Not shown' +}); + +const pretty = pino({ + prettyPrint: { + colorize: true, + crlf: false, + errorLikeObjectKeys: ['err', 'error'], + errorProps: '', + levelFirst: false, + messageKey: 'msg', + translateTime: 'UTC:h:MM:ss TT Z', + search: 'foo == `bar`' + } +}); diff --git a/types/pixi.js/index.d.ts b/types/pixi.js/index.d.ts index 17913f4903..4d86533fed 100644 --- a/types/pixi.js/index.d.ts +++ b/types/pixi.js/index.d.ts @@ -261,7 +261,7 @@ declare namespace PIXI { getRectangle(rect?: Rectangle): Rectangle; addPoint(point: Point): void; - addQuad(vertices: number[]): Bounds | undefined; + addQuad(vertices: ArrayLike): Bounds | undefined; addFrame( transform: Transform, x0: number, @@ -271,7 +271,7 @@ declare namespace PIXI { ): void; addVertices( transform: Transform, - vertices: number[], + vertices: ArrayLike, beginOffset: number, endOffset: number ): void; @@ -289,9 +289,7 @@ declare namespace PIXI { height: number; protected onChildrenChange: (...args: any[]) => void; - addChild( - ...children: T[] - ): T; + addChild(...children: T[]): T; addChildAt(child: T, index: number): T; swapChildren(child: DisplayObject, child2: DisplayObject): void; getChildIndex(child: DisplayObject): number; @@ -379,9 +377,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { - [key: number]: interaction.InteractionTrackingData; - }; + trackedPointers: { [key: number]: interaction.InteractionTrackingData; }; // Deprecated defaultCursor: string; // end interactive target @@ -608,6 +604,7 @@ declare namespace PIXI { boundsPadding: number; protected _localBounds: Bounds; dirty: number; + canvasTintDirty: number; fastRectDirty: number; clearDirty: number; boundsDirty: number; @@ -869,6 +866,8 @@ declare namespace PIXI { } class ObservablePoint extends PointLike { constructor(cb: () => any, scope?: any, x?: number, y?: number); + clone(cb?: Function, scope?: any): ObservablePoint; + equals(p: Point | ObservablePoint | PointLike): boolean; cb: () => any; scope: any; } @@ -1148,7 +1147,7 @@ declare namespace PIXI { displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, - transform?: PIXI.Transform, + transform?: PIXI.Matrix, skipUpdateTransform?: boolean ): void; setBlendMode(blendMode: number): void; @@ -1267,7 +1266,7 @@ declare namespace PIXI { displayObject: PIXI.DisplayObject, renderTexture?: PIXI.RenderTexture, clear?: boolean, - transform?: PIXI.Transform, + transform?: PIXI.Matrix, skipUpdateTransform?: boolean ): void; setObjectRenderer(objectRenderer: ObjectRenderer): void; @@ -1281,7 +1280,7 @@ declare namespace PIXI { ): WebGLRenderer; bindRenderTexture( renderTexture: RenderTexture, - transform: Transform + transform: Matrix ): WebGLRenderer; bindRenderTarget(renderTarget: RenderTarget): WebGLRenderer; bindShader(shader: Shader, autoProject?: boolean): WebGLRenderer; @@ -1586,7 +1585,7 @@ declare namespace PIXI { constructor( vertexSrc?: string, fragmentSrc?: string, - uniforms?: UniformDataMap + uniformData?: UniformDataMap ); protected _blendMode: number; @@ -2162,7 +2161,8 @@ declare namespace PIXI { frame?: Rectangle, orig?: Rectangle, trim?: Rectangle, - rotate?: number + rotate?: number, + anchor?: Point ); noFrame: boolean; @@ -2173,6 +2173,7 @@ declare namespace PIXI { requiresUpdate: boolean; protected _uvs: TextureUvs; orig: Rectangle; + defaultAnchor: Point; protected _updateID: number; transform: TextureMatrix; textureCacheIds: string[]; @@ -2198,9 +2199,16 @@ declare namespace PIXI { ): Texture; static fromVideo( video: HTMLVideoElement | string, - scaleMode?: number + scaleMode?: number, + crossorigin?: boolean, + autoPlay?: boolean + ): Texture; + static fromVideoUrl( + videoUrl: string, + scaleMode?: number, + crossorigin?: boolean, + autoPlay?: boolean ): Texture; - static fromVideoUrl(videoUrl: string, scaleMode?: number): Texture; static from( source: | number @@ -2304,6 +2312,7 @@ declare namespace PIXI { ); baseTexture: BaseTexture; + animations: { [key: string]: Texture[] }; textures: { [key: string]: Texture }; data: any; resolution: number; @@ -2323,12 +2332,17 @@ declare namespace PIXI { ): void; protected _processFrames(initialFrameIndex: number): void; protected _parseComplete(): void; + protected _processAnimations(): void; protected _nextBatch(): void; destroy(destroyBase?: boolean): void; } class VideoBaseTexture extends BaseTexture { - constructor(source: HTMLVideoElement, scaleMode?: number); + constructor( + source: HTMLVideoElement, + scaleMode?: number, + autoPlay?: boolean + ); autoUpdate: boolean; autoPlay: boolean; @@ -2344,11 +2358,13 @@ declare namespace PIXI { static fromVideo( video: HTMLVideoElement, - scaleMode?: number + scaleMode?: number, + autoPlay?: boolean ): VideoBaseTexture; static fromUrl( videoSrc: string | any | string[] | any[], - crossOrigin?: boolean + crossorigin?: boolean, + autoPlay?: boolean ): VideoBaseTexture; static fromUrls( videoSrc: string | any | string[] | any[] @@ -2793,7 +2809,7 @@ declare namespace PIXI { | PIXI.HitArea; buttonMode: boolean; cursor: string; - trackedPointers(): { [key: number]: InteractionTrackingData }; + trackedPointers: { [key: number]: InteractionTrackingData }; // Deprecated defaultCursor: string; @@ -3330,6 +3346,7 @@ declare namespace PIXI { spineAtlas: any; spineData: any; textures?: TextureDictionary; + spritesheet?: Spritesheet; } const shared: Loader; } diff --git a/types/pixi.js/pixi.js-tests.ts b/types/pixi.js/pixi.js-tests.ts index 48581e67fe..c311c1281b 100644 --- a/types/pixi.js/pixi.js-tests.ts +++ b/types/pixi.js/pixi.js-tests.ts @@ -1508,7 +1508,7 @@ function filters() { maggot.scale.set(1 + Math.random() * 0.3); //tslint:disable-next-line:whitespace - maggot.original = (maggot.scale).clone(); + maggot.original = (maggot.scale as PIXI.Point).clone(); this.maggots.push(maggot); } diff --git a/types/pkg-up/index.d.ts b/types/pkg-up/index.d.ts new file mode 100644 index 0000000000..d5a511543f --- /dev/null +++ b/types/pkg-up/index.d.ts @@ -0,0 +1,12 @@ +// Type definitions for pkg-up 2.0 +// Project: https://github.com/sindresorhus/pkg-up#readme +// Definitions by: Emily Marigold Klassen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = pkgUp; + +declare function pkgUp(cwd?: string): Promise; + +declare namespace pkgUp { + function sync(cwd?: string): string; +} diff --git a/types/pkg-up/pkg-up-tests.ts b/types/pkg-up/pkg-up-tests.ts new file mode 100644 index 0000000000..79803ffd68 --- /dev/null +++ b/types/pkg-up/pkg-up-tests.ts @@ -0,0 +1,6 @@ +import pkgUp = require('pkg-up'); + +pkgUp().then(filepath => { + filepath; + // => '/Users/sindresorhus/foo/package.json' +}); diff --git a/types/pkg-up/tsconfig.json b/types/pkg-up/tsconfig.json new file mode 100644 index 0000000000..bd078c902c --- /dev/null +++ b/types/pkg-up/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", + "pkg-up-tests.ts" + ] +} diff --git a/types/pkg-up/tslint.json b/types/pkg-up/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pkg-up/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/playcanvas/index.d.ts b/types/playcanvas/index.d.ts index 24fe7ec6ee..fd3fbbcfbc 100644 --- a/types/playcanvas/index.d.ts +++ b/types/playcanvas/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/playcanvas/engine // Definitions by: Philippe Vaillancourt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.2 /// /// diff --git a/types/playcanvas/tslint.json b/types/playcanvas/tslint.json index 3db14f85ea..a2bb521763 100644 --- a/types/playcanvas/tslint.json +++ b/types/playcanvas/tslint.json @@ -1 +1,26 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + // All are TODOs + "array-type": false, + "ban-types": false, + "eofline": false, + "interface-over-type-literal": false, + "jsdoc-format": false, + "max-line-length": false, + "member-access": false, + "no-consecutive-blank-lines": false, + "no-padding": false, + "no-redundant-jsdoc-2": false, + "no-trailing-whitespace": false, + "no-unnecessary-class": false, + "no-unnecessary-generics": false, + "no-unnecessary-qualifier": false, + "no-var-keyword": false, + "semicolon": false, + "space-before-function-paren": false, + "strict-export-declare-modifiers": false, + "unified-signatures": false, + "void-return": false + } +} diff --git a/types/playerframework/tslint.json b/types/playerframework/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/playerframework/tslint.json +++ b/types/playerframework/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": false, diff --git a/types/plist/index.d.ts b/types/plist/index.d.ts index b7064e55a3..f97b267df4 100644 --- a/types/plist/index.d.ts +++ b/types/plist/index.d.ts @@ -20,9 +20,9 @@ export type PlistValue = string | number | boolean | Date | Buffer | PlistObject | PlistArray; export interface PlistObject { - [x: string]: PlistValue; + readonly [x: string]: PlistValue; } -export interface PlistArray extends Array { } +export interface PlistArray extends ReadonlyArray { } // PlistBuildOptions // The instance of this type is passed to 'xmlbuilder' module as it is. diff --git a/types/plist/plist-tests.ts b/types/plist/plist-tests.ts index a94cb4cf71..00dc33b56c 100644 --- a/types/plist/plist-tests.ts +++ b/types/plist/plist-tests.ts @@ -79,3 +79,10 @@ console.log(plistString1); const plistString2 = plist.build(plistValue2, {pretty: false}); console.log(plistString2); + +function f(a: ReadonlyArray) { + plist.build(a); +} + +// $ExpectError +plist.build(() => 0); diff --git a/types/plotly.js/index.d.ts b/types/plotly.js/index.d.ts index 8e6ae187e1..8a8823ac8c 100644 --- a/types/plotly.js/index.d.ts +++ b/types/plotly.js/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for plotly.js 1.38 +// Type definitions for plotly.js 1.41 // Project: https://plot.ly/javascript/ // Definitions by: Chris Gervang // Martin Duparc @@ -13,7 +13,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -/// +import * as _d3 from "d3"; export as namespace Plotly; export interface StaticPlots { @@ -39,8 +39,19 @@ export interface PlotScatterDataPoint { yaxis: LayoutAxis; } +export interface PlotDatum { + curveNumber: number; + data: PlotData; + pointIndex: number; + pointNumber: number; + x: Datum; + xaxis: LayoutAxis; + y: Datum; + yaxis: LayoutAxis; +} + export interface PlotMouseEvent { - points: PlotScatterDataPoint[]; + points: PlotDatum[]; event: MouseEvent; } @@ -55,10 +66,10 @@ export interface SelectionRange { y: number[]; } -export type PlotSelectedData = Partial; +export type PlotSelectedData = Partial; export interface PlotSelectionEvent { - points: PlotScatterDataPoint[]; + points: PlotDatum[]; range?: SelectionRange; lassoPoints?: SelectionRange; } @@ -155,6 +166,7 @@ export interface PlotlyHTMLElement extends HTMLElement { on(event: 'plotly_afterexport' | 'plotly_afterplot' | 'plotly_animated' | 'plotly_animationinterrupted' | 'plotly_autosize' | 'plotly_beforeexport' | 'plotly_deselect' | 'plotly_doubleclick' | 'plotly_framework' | 'plotly_redraw' | 'plotly_transitioning' | 'plotly_transitioninterrupted', callback: () => void): void; + removeAllListeners: (handler: string) => void; } export interface ToImgopts { @@ -177,7 +189,7 @@ export function plot(root: Root, data: Data[], layout?: Partial, config? export function relayout(root: Root, layout: Partial): Promise; export function redraw(root: Root): Promise; export function purge(root: Root): void; -export const d3: any; +export const d3: typeof _d3; export function restyle(root: Root, aobj: Data, traces?: number[] | number): Promise; export function update(root: Root, traceUpdate: Data, layoutUpdate: Partial, traces?: number[] | number): Promise; export function addTraces(root: Root, traces: Data | Data[], newIndices?: number[] | number): Promise; @@ -251,6 +263,7 @@ export interface Layout { legend: Partial; font: Partial; scene: Partial; + barmode: "stack" | "group" | "overlay" | "relative"; } export interface Legend extends Label { @@ -338,6 +351,7 @@ export interface LayoutAxis extends Axis { position: number; rangeslider: Partial; rangeselector: Partial; + automargin: boolean; } export interface SceneAxis extends Axis { @@ -465,7 +479,7 @@ export type DataTransform = Partial; export type ScatterData = PlotData; // Bar Scatter export interface PlotData { - type: 'bar' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; + type: 'bar' | 'box' | 'heatmap' | 'histogram' | 'pointcloud' | 'scatter' | 'scattergl' | 'scatter3d' | 'surface'; x: Datum[] | Datum[][] | TypedArray; y: Datum[] | Datum[][] | TypedArray; z: Datum[] | Datum[][] | Datum[][][] | TypedArray; @@ -516,6 +530,18 @@ export interface PlotData { visible: boolean | 'legendonly'; transforms: DataTransform[]; orientation: 'v' | 'h'; + boxmean: boolean | 'sd'; + colorscale: string | Array<[number, string]>; + zsmooth: 'fast' | 'best' | false; + ygap: number; + xgap: number; + transpose: boolean; + autobinx: boolean; + xbins: { + start: number | string; + end: number | string; + size: number | string; + }; } /** @@ -548,6 +574,54 @@ export interface Transform { value: any; order: 'ascending' | 'descending'; } + +export interface ColorBar { + thicknessmode: 'fraction' | 'pixels'; + thickness: number; + lenmode: 'fraction' | 'pixels'; + len: number; + x: number; + xanchor: 'left' | 'center' | 'right'; + xpad: number; + y: number; + yanchor: 'top' | 'middle' | 'bottom'; + ypad: number; + outlinecolor: Color; + outlinewidth: number; + bordercolor: Color; + borderwidth: Color; + bgcolor: Color; + tickmode: 'auto' | 'linear' | 'array'; + nticks: number; + tick0: number | string; + dtick: number | string; + tickvals: Datum[] | Datum[][] | Datum[][][] | TypedArray; + ticktext: Datum[] | Datum[][] | Datum[][][] | TypedArray; + ticks: 'outside' | 'inside' | ''; + ticklen: number; + tickwidth: number; + tickcolor: Color; + showticklabels: boolean; + tickfont: Font; + tickangle: number; + tickformat: string; + tickformatstops: { + dtickrange: any[]; + value: string; + }; + tickprefix: string; + showtickprefix: 'all' | 'first' | 'last' | 'none'; + ticksuffix: string; + showticksuffix: 'all' | 'first' | 'last' | 'none'; + separatethousands: boolean; + exponentformat: 'none' | 'e' | 'E' | 'power' | 'SI' | 'B'; + showexponent: 'all' | 'first' | 'last' | 'none'; + title: string; + titlefont: Font; + titleside: 'right' | 'top' | 'bottom'; + tickvalssrc: any; + ticktextsrc: any; +} /** * Any combination of "x", "y", "z", "text", "name" joined with a "+" OR "all" or "none" or "skip". * examples: "x", "y", "x+y", "x+y+z", "all" @@ -572,53 +646,7 @@ export interface PlotMarker { showscale: boolean; line: Partial; width: number; - colorbar: { - thicknessmode: 'fraction' | 'pixels', - thickness: number, - lenmode: 'fraction' | 'pixels', - len: number, - x: number, - xanchor: 'left' | 'center' | 'right', - xpad: number, - y: number, - yanchor: 'top' | 'middle' | 'bottom', - ypad: number, - outlinecolor: Color, - outlinewidth: number, - bordercolor: Color, - borderwidth: Color, - bgcolor: Color, - tickmode: 'auto' | 'linear' | 'array', - nticks: number, - tick0: number | string, - dtick: number | string, - tickvals: Datum[] | Datum[][] | Datum[][][] | TypedArray, - ticktext: Datum[] | Datum[][] | Datum[][][] | TypedArray, - ticks: 'outside' | 'inside' | '', - ticklen: number, - tickwidth: number, - tickcolor: Color, - showticklabels: boolean, - tickfont: Font, - tickangle: number, - tickformat: string, - tickformatstops: { - dtickrange: any[], - value: string, - }, - tickprefix: string, - showtickprefix: 'all' | 'first' | 'last' | 'none', - ticksuffix: string, - showticksuffix: 'all' | 'first' | 'last' | 'none', - separatethousands: boolean, - exponentformat: 'none' | 'e' | 'E' | 'power' | 'SI' | 'B', - showexponent: 'all' | 'first' | 'last' | 'none', - title: string, - titlefont: Font, - titleside: 'right' | 'top' | 'bottom', - tickvalssrc: any, - ticktextsrc: any, - }; + colorbar: Partial; gradient: { type: 'radial' | 'horizontal' | 'vertical' | 'none', color: Color, @@ -776,6 +804,9 @@ export interface Config { /** Which localization should we use? Should be a string like 'en' or 'en-US' */ locale: string; + + /** Make the chart responsive to window size */ + responsive: boolean; } // Components diff --git a/types/plotly.js/test/core-tests.ts b/types/plotly.js/test/core-tests.ts index 6e35de55c6..ba48a8ee03 100644 --- a/types/plotly.js/test/core-tests.ts +++ b/types/plotly.js/test/core-tests.ts @@ -1,5 +1,5 @@ import * as Plotly from 'plotly.js/lib/core'; -import { ScatterData, Layout, PlotlyHTMLElement, newPlot } from 'plotly.js/lib/core'; +import { Datum, ScatterData, Layout, PlotlyHTMLElement, newPlot } from 'plotly.js/lib/core'; const graphDiv = '#test'; @@ -336,8 +336,8 @@ function rand() { }); myPlot.on('plotly_selected', (data) => { - const x = [] as number[]; - const y = [] as number[]; + const x = [] as Datum[]; + const y = [] as Datum[]; const N = 1000; const color1 = '#7b3294'; const color1Light = '#c2a5cf'; diff --git a/types/plotly.js/test/index-tests.ts b/types/plotly.js/test/index-tests.ts index d4b274b321..79343f43f7 100644 --- a/types/plotly.js/test/index-tests.ts +++ b/types/plotly.js/test/index-tests.ts @@ -1,5 +1,5 @@ import * as Plotly from 'plotly.js'; -import { Layout, PlotData, PlotlyHTMLElement, newPlot } from 'plotly.js'; +import { Datum, Layout, PlotData, PlotlyHTMLElement, newPlot } from 'plotly.js'; const graphDiv = '#test'; @@ -446,8 +446,8 @@ function rand() { }); myPlot.on('plotly_selected', (data) => { - const x = [] as number[]; - const y = [] as number[]; + const x = [] as Datum[]; + const y = [] as Datum[]; const N = 1000; const color1 = '#7b3294'; const color1Light = '#c2a5cf'; @@ -546,5 +546,6 @@ function rand() { myPlot.on('plotly_transitioninterrupted', () => { console.log('transition interrupted'); }); + + myPlot.removeAllListeners('plotly_restyle'); })(); -////////////////////////////////////////////////////////////////////// diff --git a/types/plotly.js/tsconfig.json b/types/plotly.js/tsconfig.json index dd21321c49..fe2dfd96bd 100644 --- a/types/plotly.js/tsconfig.json +++ b/types/plotly.js/tsconfig.json @@ -13,6 +13,9 @@ "typeRoots": [ "../" ], + "paths": { + "d3": [ "d3/v3" ] + }, "types": [], "noEmit": true, "forceConsistentCasingInFileNames": true diff --git a/types/pollyjs__adapter-fetch/index.d.ts b/types/pollyjs__adapter-fetch/index.d.ts new file mode 100644 index 0000000000..d38313db9d --- /dev/null +++ b/types/pollyjs__adapter-fetch/index.d.ts @@ -0,0 +1,9 @@ +// 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 +// TypeScript Version: 2.4 + +import Adapter from '@pollyjs/adapter'; + +export default class FetchAdapter extends Adapter {} diff --git a/types/pollyjs__adapter-fetch/pollyjs__adapter-fetch-tests.ts b/types/pollyjs__adapter-fetch/pollyjs__adapter-fetch-tests.ts new file mode 100644 index 0000000000..61b8ef734d --- /dev/null +++ b/types/pollyjs__adapter-fetch/pollyjs__adapter-fetch-tests.ts @@ -0,0 +1,8 @@ +import FetchAdapter from '@pollyjs/adapter-fetch'; +import { Polly } from '@pollyjs/core'; + +Polly.register(FetchAdapter); + +new Polly('', { + adapters: ['xhr', FetchAdapter] +}); diff --git a/types/pollyjs__adapter-fetch/tsconfig.json b/types/pollyjs__adapter-fetch/tsconfig.json new file mode 100644 index 0000000000..03d3076b3c --- /dev/null +++ b/types/pollyjs__adapter-fetch/tsconfig.json @@ -0,0 +1,40 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/adapter": [ + "pollyjs__adapter" + ], + "@pollyjs/adapter-fetch": [ + "pollyjs__adapter-fetch" + ], + "@pollyjs/persister": [ + "pollyjs__persister" + ], + "@pollyjs/utils": [ + "pollyjs__utils" + ] + } + }, + "files": [ + "index.d.ts", + "pollyjs__adapter-fetch-tests.ts" + ] +} diff --git a/types/pollyjs__adapter-fetch/tslint.json b/types/pollyjs__adapter-fetch/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__adapter-fetch/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pollyjs__adapter/index.d.ts b/types/pollyjs__adapter/index.d.ts new file mode 100644 index 0000000000..0bc49fd73b --- /dev/null +++ b/types/pollyjs__adapter/index.d.ts @@ -0,0 +1,10 @@ +// 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 +export default class Adapter { + static readonly name: string; + static readonly type: string; + connect(): void; + disconnect(): void; +} diff --git a/types/pollyjs__adapter/pollyjs__adapter-tests.ts b/types/pollyjs__adapter/pollyjs__adapter-tests.ts new file mode 100644 index 0000000000..1e5c82a586 --- /dev/null +++ b/types/pollyjs__adapter/pollyjs__adapter-tests.ts @@ -0,0 +1,4 @@ +import Adapter from '@pollyjs/adapter'; + +Adapter.name; +Adapter.type; diff --git a/types/pollyjs__adapter/tsconfig.json b/types/pollyjs__adapter/tsconfig.json new file mode 100644 index 0000000000..ad121d2d9d --- /dev/null +++ b/types/pollyjs__adapter/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/adapter": [ + "pollyjs__adapter" + ], + "@pollyjs/persister": [ + "pollyjs__persister" + ], + "@pollyjs/utils": [ + "pollyjs__utils" + ] + } + }, + "files": [ + "index.d.ts", + "pollyjs__adapter-tests.ts" + ] +} diff --git a/types/pollyjs__adapter/tslint.json b/types/pollyjs__adapter/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__adapter/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pollyjs__core/index.d.ts b/types/pollyjs__core/index.d.ts new file mode 100644 index 0000000000..4f6d308d0d --- /dev/null +++ b/types/pollyjs__core/index.d.ts @@ -0,0 +1,169 @@ +// 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 +// TypeScript Version: 2.4 + +import { MODES } from '@pollyjs/utils'; +import Adapter from '@pollyjs/adapter'; +import Persister from '@pollyjs/persister'; + +export const Timing: { + fixed(ms: number): () => Promise; + relative(ratio: number): (ms: number) => Promise; +}; + +export type MatchBy = (input: T) => R; +export interface PollyConfig { + mode?: MODES | string; + + adapters?: Array; + adapterOptions?: any; + + persister?: string | typeof Persister; + persisterOptions?: { + keepUnusedRequests?: boolean; + [key: string]: any; + }; + + logging?: boolean; + + recordIfMissing?: boolean; + recordIfExpired?: boolean; + recordFailedRequests?: boolean; + + expiresIn?: string | null; + timing?: ((ms: number) => Promise) | (() => Promise); + + matchRequestsBy?: { + method?: boolean | MatchBy; + headers?: boolean | { exclude: string[] } | MatchBy>; + body?: boolean | MatchBy; + order?: boolean; + + url?: { + protocol?: boolean | MatchBy; + username?: boolean | MatchBy; + password?: boolean | MatchBy; + hostname?: boolean | MatchBy; + port?: boolean | MatchBy; + pathname?: boolean | MatchBy; + query?: boolean | MatchBy; + hash?: boolean | MatchBy; + }; + }; +} +export interface Request { + getHeader(name: string): string | null; + setHeader(name: string, value: string): Request; + setHeaders(headers: any): Request; + hasHeader(name: string): boolean; + type(contentType: string): Request; + send(body: any): Request; + json(body: any): Request; + jsonBody(): any; + + method: string; + url: string; + protocol: string; + hostname: string; + port: string; + pathname: string; + hash: string; + headers: Record; + body: any; + query: any; + params: any; + recordingName: string; + responseTime?: number; +} +export interface Response { + statusCode?: number; + headers: Record; + body: any; + status(status: number): Response; + getHeader(name: string): string | null; + setHeader(name: string, value: string): Response; + setHeaders(headers: any): Response; + hasHeader(name: string): boolean; + type(contentType: string): Response; + send(body: any): Response; + sendStatus(status: number): Response; + json(body: any): Response; + jsonBody(): any; + end(): Readonly; +} +export interface Intercept { + abort(): void; + passthrough(): void; +} +export type RequestRouteEvent = 'request'; +export type RecordingRouteEvent = 'beforeReplay' | 'beforePersist'; +export type ResponseRouteEvent = 'beforeResponse' | 'response'; + +export type EventListenerResponse = any; +export type RequestEventListener = (req: Request) => EventListenerResponse; +export type RecordingEventListener = (req: Request, recording: any) => EventListenerResponse; +export type ResponseEventListener = (req: Request, res: Response) => EventListenerResponse; +export type InterceptHandler = ( + req: Request, + res: Response, + intercept: Intercept +) => EventListenerResponse; +export class RouteHandler { + on(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; + on(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; + on(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + off(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; + off(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; + off(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + once(event: RequestRouteEvent, listener: RequestEventListener): RouteHandler; + once(event: RecordingRouteEvent, listener: RecordingEventListener): RouteHandler; + once(event: ResponseRouteEvent, listener: ResponseEventListener): RouteHandler; + + passthrough(value?: boolean): RouteHandler; + intercept( + fn: (req: Request, res: Response, intercept: Intercept) => EventListenerResponse + ): RouteHandler; + recordingName(recordingName: string): RouteHandler; + configure(config: PollyConfig): RouteHandler; +} +export class PollyServer { + timeout: (ms: number) => Promise; + get: (...args: any[]) => RouteHandler; + put: (...args: any[]) => RouteHandler; + post: (...args: any[]) => RouteHandler; + delete: (...args: any[]) => RouteHandler; + patch: (...args: any[]) => RouteHandler; + head: (...args: any[]) => RouteHandler; + options: (...args: any[]) => RouteHandler; + any: (...args: any[]) => RouteHandler; + host(host: string, callback: () => void): void; + namespace(path: string, callback: () => void): void; +} +export type PollyEvent = 'create' | 'stop' | 'register'; +export type PollyEventListener = (poll: Polly) => void; +export class Polly { + static register(Factory: typeof Adapter | typeof Persister): void; + static on(event: PollyEvent, listener: PollyEventListener): void; + static off(event: PollyEvent, listener: PollyEventListener): void; + static once(event: PollyEvent, listener: PollyEventListener): void; + + constructor(name: string, options?: PollyConfig); + + readonly recordingName: string | null; + mode: MODES; + server: PollyServer; + persister: Persister; + + pause: () => void; + play: () => void; + replay: () => void; + record: () => void; + stop: () => Promise; + flush: () => Promise; + configure(config: PollyConfig): void; + connectTo(name: string | typeof Adapter): void; + disconnectFrom(name: string | typeof Adapter): void; + disconnect(): void; +} diff --git a/types/pollyjs__core/pollyjs__core-tests.ts b/types/pollyjs__core/pollyjs__core-tests.ts new file mode 100644 index 0000000000..0644eff7f4 --- /dev/null +++ b/types/pollyjs__core/pollyjs__core-tests.ts @@ -0,0 +1,131 @@ +import { Polly, Timing } from '@pollyjs/core'; +import { MODES } from '@pollyjs/utils'; + +const polly = new Polly('test recording', { + mode: MODES.PASSTHROUGH, + recordFailedRequests: true, + adapters: ['xhr', 'fetch'], + persister: 'rest', + 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) { + // no op +} + +async function test() { + polly.pause(); + polly.play(); + const { server } = polly; + server.get('/session').on('request', req => { + req.headers['X-AUTH'] = ''; + req.query.email = 'test@app.com'; + }); + server.get('/session').on('beforeResponse', (req, res) => { + res.setHeader('X-AUTH', ''); + }); + server.get('/session').on('response', (req, res) => { + log(`${req.url} took ${req.responseTime}ms with a status of ${res.statusCode}.`); + }); + + polly.configure({ + adapterOptions: { + fetch: { + context: null + } + } + }); + + server + .get('/session') + .once('request', req => { + req.headers['X-AUTH'] = ''; + req.query.email = 'test@app.com'; + }) + .once('request', () => { + /* Do something else */ + }); + + /* Intercept all Google Analytic requests and respond with a 200 */ + server.get('/google-analytics/*path').intercept((req, res, intercept) => { + if (req.pathname === 'test') { + intercept.abort(); + } else { + res.sendStatus(200); + } + }); + + /* Pass-through all GET requests to /coverage */ + server.get('/coverage') + .configure({ expiresIn: '5d' }) + .passthrough(); + + await polly.flush(); +} diff --git a/types/pollyjs__core/tsconfig.json b/types/pollyjs__core/tsconfig.json new file mode 100644 index 0000000000..4b91defc70 --- /dev/null +++ b/types/pollyjs__core/tsconfig.json @@ -0,0 +1,37 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/utils": [ + "pollyjs__utils" + ], + "@pollyjs/persister": [ + "pollyjs__persister" + ], + "@pollyjs/adapter": [ + "pollyjs__adapter" + ] + } + }, + "files": [ + "index.d.ts", + "pollyjs__core-tests.ts" + ] +} diff --git a/types/pollyjs__core/tslint.json b/types/pollyjs__core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pollyjs__persister-fs/index.d.ts b/types/pollyjs__persister-fs/index.d.ts new file mode 100644 index 0000000000..fc7f9ad656 --- /dev/null +++ b/types/pollyjs__persister-fs/index.d.ts @@ -0,0 +1,9 @@ +// 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 +// TypeScript Version: 2.4 + +import Persister from '@pollyjs/persister'; + +export default class FSPersister extends Persister {} diff --git a/types/pollyjs__persister-fs/pollyjs__persister-fs-tests.ts b/types/pollyjs__persister-fs/pollyjs__persister-fs-tests.ts new file mode 100644 index 0000000000..2d624a0f8d --- /dev/null +++ b/types/pollyjs__persister-fs/pollyjs__persister-fs-tests.ts @@ -0,0 +1,8 @@ +import FSPersister from '@pollyjs/persister-fs'; +import { Polly } from '@pollyjs/core'; + +Polly.register(FSPersister); + +new Polly('', { + persister: FSPersister +}); diff --git a/types/pollyjs__persister-fs/tsconfig.json b/types/pollyjs__persister-fs/tsconfig.json new file mode 100644 index 0000000000..7a7eb6733c --- /dev/null +++ b/types/pollyjs__persister-fs/tsconfig.json @@ -0,0 +1,41 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/persister": [ + "pollyjs__persister" + ], + "@pollyjs/persister-fs": [ + "pollyjs__persister-fs" + ], + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/utils": [ + "pollyjs__utils" + ], + "@pollyjs/adapter": [ + "pollyjs__adapter" + ] + } + + }, + "files": [ + "index.d.ts", + "pollyjs__persister-fs-tests.ts" + ] +} diff --git a/types/pollyjs__persister-fs/tslint.json b/types/pollyjs__persister-fs/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__persister-fs/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pollyjs__persister/index.d.ts b/types/pollyjs__persister/index.d.ts new file mode 100644 index 0000000000..87e1c27f5b --- /dev/null +++ b/types/pollyjs__persister/index.d.ts @@ -0,0 +1,10 @@ +// 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 + +export default class Persister { + static readonly name: string; + static readonly type: string; + persist(): Promise; +} diff --git a/types/pollyjs__persister/pollyjs__persister-tests.ts b/types/pollyjs__persister/pollyjs__persister-tests.ts new file mode 100644 index 0000000000..7e9448aae0 --- /dev/null +++ b/types/pollyjs__persister/pollyjs__persister-tests.ts @@ -0,0 +1,4 @@ +import Persister from '@pollyjs/persister'; + +Persister.name; +Persister.type; diff --git a/types/pollyjs__persister/tsconfig.json b/types/pollyjs__persister/tsconfig.json new file mode 100644 index 0000000000..b47bfbaa9f --- /dev/null +++ b/types/pollyjs__persister/tsconfig.json @@ -0,0 +1,31 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "paths": { + "@pollyjs/core": [ + "pollyjs__core" + ], + "@pollyjs/persister": [ + "pollyjs__persister" + ] + } + }, + "files": [ + "index.d.ts", + "pollyjs__persister-tests.ts" + ] +} diff --git a/types/pollyjs__persister/tslint.json b/types/pollyjs__persister/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__persister/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pollyjs__utils/index.d.ts b/types/pollyjs__utils/index.d.ts new file mode 100644 index 0000000000..ca3e7735ef --- /dev/null +++ b/types/pollyjs__utils/index.d.ts @@ -0,0 +1,12 @@ +// 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 +// TypeScript Version: 2.4 + +export enum MODES { + RECORD = 'record', + REPLAY = 'replay', + PASSTHROUGH = 'passthrough', + STOPPED = 'stopped' +} diff --git a/types/pollyjs__utils/pollyjs__utils-tests.ts b/types/pollyjs__utils/pollyjs__utils-tests.ts new file mode 100644 index 0000000000..463a4b4329 --- /dev/null +++ b/types/pollyjs__utils/pollyjs__utils-tests.ts @@ -0,0 +1,6 @@ +import { MODES } from '@pollyjs/utils'; + +MODES.PASSTHROUGH; +MODES.RECORD; +MODES.REPLAY; +MODES.STOPPED; diff --git a/types/babel__parser/tsconfig.json b/types/pollyjs__utils/tsconfig.json similarity index 83% rename from types/babel__parser/tsconfig.json rename to types/pollyjs__utils/tsconfig.json index 53fd02ec18..7b5421a32f 100644 --- a/types/babel__parser/tsconfig.json +++ b/types/pollyjs__utils/tsconfig.json @@ -16,13 +16,13 @@ "noEmit": true, "forceConsistentCasingInFileNames": true, "paths": { - "@babel/parser": [ - "babel__parser" + "@pollyjs/utils": [ + "pollyjs__utils" ] } }, "files": [ "index.d.ts", - "babel__parser-tests.ts" + "pollyjs__utils-tests.ts" ] } diff --git a/types/pollyjs__utils/tslint.json b/types/pollyjs__utils/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/pollyjs__utils/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-calc/index.d.ts b/types/postcss-calc/index.d.ts new file mode 100644 index 0000000000..c9ac8e30bb --- /dev/null +++ b/types/postcss-calc/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for postcss-calc 7.0 +// Project: https://github.com/postcss/postcss-calc +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace calc { + interface Options { + precision?: number; + preserve?: boolean; + warnWhenCannotResolve?: boolean; + mediaQueries?: boolean; + selectors?: boolean; + } + + type Calc = Plugin; +} + +declare const calc: calc.Calc; +export = calc; diff --git a/types/postcss-calc/package.json b/types/postcss-calc/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-calc/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-calc/postcss-calc-tests.ts b/types/postcss-calc/postcss-calc-tests.ts new file mode 100644 index 0000000000..937741a1f3 --- /dev/null +++ b/types/postcss-calc/postcss-calc-tests.ts @@ -0,0 +1,12 @@ +import calc = require("postcss-calc"); +import { Transformer } from 'postcss'; + +const ap1: Transformer = calc(); + +const ap2: Transformer = calc({ + precision: 5, + preserve: false, + warnWhenCannotResolve: false, + mediaQueries: false, + selectors: false +}); diff --git a/types/postcss-calc/tsconfig.json b/types/postcss-calc/tsconfig.json new file mode 100644 index 0000000000..d21d8b4969 --- /dev/null +++ b/types/postcss-calc/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", + "postcss-calc-tests.ts" + ] +} diff --git a/types/postcss-calc/tslint.json b/types/postcss-calc/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-calc/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-icss-values/index.d.ts b/types/postcss-icss-values/index.d.ts new file mode 100644 index 0000000000..f7133420e8 --- /dev/null +++ b/types/postcss-icss-values/index.d.ts @@ -0,0 +1,10 @@ +// Type definitions for postcss-icss-values 2.0 +// Project: https://github.com/css-modules/postcss-icss-values +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare const values: Plugin<{}>; +export = values; diff --git a/types/postcss-icss-values/package.json b/types/postcss-icss-values/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-icss-values/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-icss-values/postcss-icss-values-tests.ts b/types/postcss-icss-values/postcss-icss-values-tests.ts new file mode 100644 index 0000000000..ac63f19aa0 --- /dev/null +++ b/types/postcss-icss-values/postcss-icss-values-tests.ts @@ -0,0 +1,4 @@ +import values = require("postcss-icss-values"); +import { Transformer } from "postcss"; + +const ap1: Transformer = values(); diff --git a/types/postcss-icss-values/tsconfig.json b/types/postcss-icss-values/tsconfig.json new file mode 100644 index 0000000000..354ce66470 --- /dev/null +++ b/types/postcss-icss-values/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", + "postcss-icss-values-tests.ts" + ] +} diff --git a/types/postcss-icss-values/tslint.json b/types/postcss-icss-values/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-icss-values/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-extract-imports/index.d.ts b/types/postcss-modules-extract-imports/index.d.ts new file mode 100644 index 0000000000..6be0a7e2c8 --- /dev/null +++ b/types/postcss-modules-extract-imports/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for postcss-modules-extract-imports 2.0 +// Project: https://github.com/css-modules/postcss-modules-extract-imports +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace extractImports { + interface Options { + failOnWrongOrder?: boolean; + createImportedName?: (importName: string, importPath: string) => string; + } + + type ExtractImports = Plugin; +} + +declare const extractImports: extractImports.ExtractImports; +export = extractImports; diff --git a/types/postcss-modules-extract-imports/package.json b/types/postcss-modules-extract-imports/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-extract-imports/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-extract-imports/postcss-modules-extract-imports-tests.ts b/types/postcss-modules-extract-imports/postcss-modules-extract-imports-tests.ts new file mode 100644 index 0000000000..121cc61290 --- /dev/null +++ b/types/postcss-modules-extract-imports/postcss-modules-extract-imports-tests.ts @@ -0,0 +1,10 @@ +import extractImports = require("postcss-modules-extract-imports"); +import { Transformer } from "postcss"; + +const ap1: Transformer = extractImports(); + +const ap2: Transformer = extractImports({ + failOnWrongOrder: true, + createImportedName: (importName, importPath) => + `i__imported_${importName.replace(/\W/g, "_")}_${importPath.replace(/\W/g, "_")}` +}); diff --git a/types/postcss-modules-extract-imports/tsconfig.json b/types/postcss-modules-extract-imports/tsconfig.json new file mode 100644 index 0000000000..2ae6e99ad7 --- /dev/null +++ b/types/postcss-modules-extract-imports/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", + "postcss-modules-extract-imports-tests.ts" + ] +} diff --git a/types/postcss-modules-extract-imports/tslint.json b/types/postcss-modules-extract-imports/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-extract-imports/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-local-by-default/index.d.ts b/types/postcss-modules-local-by-default/index.d.ts new file mode 100644 index 0000000000..5421ecd58b --- /dev/null +++ b/types/postcss-modules-local-by-default/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for postcss-modules-local-by-default 1.2 +// Project: https://github.com/css-modules/postcss-modules-local-by-default +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace localByDefault { + interface Options { + mode?: "global" | "local" | "pure"; + rewriteUrl?: (global: boolean, url: string) => string; + } + + type LocalByDefault = Plugin; +} + +declare const localByDefault: localByDefault.LocalByDefault; +export = localByDefault; diff --git a/types/postcss-modules-local-by-default/package.json b/types/postcss-modules-local-by-default/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-local-by-default/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-local-by-default/postcss-modules-local-by-default-tests.ts b/types/postcss-modules-local-by-default/postcss-modules-local-by-default-tests.ts new file mode 100644 index 0000000000..7d388471ab --- /dev/null +++ b/types/postcss-modules-local-by-default/postcss-modules-local-by-default-tests.ts @@ -0,0 +1,21 @@ +import localByDefault = require("postcss-modules-local-by-default"); +import { Transformer } from "postcss"; + +const ap1: Transformer = localByDefault(); + +const ap2: Transformer = localByDefault({ + mode: "global", + rewriteUrl: (global, url) => { + url = url.trim(); + + if (!url.replace(/\s/g, "").length) { + return url; + } + + if (global) { + return url + "?request"; + } + + return url; + } +}); diff --git a/types/postcss-modules-local-by-default/tsconfig.json b/types/postcss-modules-local-by-default/tsconfig.json new file mode 100644 index 0000000000..6634c36375 --- /dev/null +++ b/types/postcss-modules-local-by-default/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", + "postcss-modules-local-by-default-tests.ts" + ] +} diff --git a/types/postcss-modules-local-by-default/tslint.json b/types/postcss-modules-local-by-default/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-local-by-default/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-resolve-imports/index.d.ts b/types/postcss-modules-resolve-imports/index.d.ts new file mode 100644 index 0000000000..698ce430ff --- /dev/null +++ b/types/postcss-modules-resolve-imports/index.d.ts @@ -0,0 +1,27 @@ +// Type definitions for postcss-modules-resolve-imports 1.3 +// Project: https://github.com/css-modules/postcss-modules-resolve-imports +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace resolveImports { + interface Resolve { + alias?: { [alias: string]: string }; + extensions?: string[]; + modules?: string[]; + mainFile?: string; + preserveSymlinks?: boolean; + } + + interface Options { + icssExports?: boolean; + resolve?: Resolve; + } + + type ResolveImports = Plugin; +} + +declare const resolveImports: resolveImports.ResolveImports; +export = resolveImports; diff --git a/types/postcss-modules-resolve-imports/package.json b/types/postcss-modules-resolve-imports/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-resolve-imports/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts new file mode 100644 index 0000000000..cb46a28ddc --- /dev/null +++ b/types/postcss-modules-resolve-imports/postcss-modules-resolve-imports-tests.ts @@ -0,0 +1,20 @@ +/// + +import path = require("path"); +import resolveImports = require("postcss-modules-resolve-imports"); +import { Transformer } from "postcss"; + +const ap1: Transformer = resolveImports(); + +const ap2: Transformer = resolveImports({ + icssExports: false, + resolve: { + alias: { + lib: path.resolve(__dirname, "lib"), + }, + extensions: [".css"], + modules: [path.resolve(__dirname, "lib")], + mainFile: "index.css", + preserveSymlinks: false + } +}); diff --git a/types/postcss-modules-resolve-imports/tsconfig.json b/types/postcss-modules-resolve-imports/tsconfig.json new file mode 100644 index 0000000000..a1b942ae1c --- /dev/null +++ b/types/postcss-modules-resolve-imports/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", + "postcss-modules-resolve-imports-tests.ts" + ] +} diff --git a/types/postcss-modules-resolve-imports/tslint.json b/types/postcss-modules-resolve-imports/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-resolve-imports/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-modules-scope/index.d.ts b/types/postcss-modules-scope/index.d.ts new file mode 100644 index 0000000000..b5f9e2c231 --- /dev/null +++ b/types/postcss-modules-scope/index.d.ts @@ -0,0 +1,18 @@ +// Type definitions for postcss-modules-scope 1.1 +// Project: https://github.com/css-modules/postcss-modules-scope +// Definitions by: Jeow Li Huan +// Definitions: https://github.com/huan086/postcss-plugins-typings +// TypeScript Version: 2.2 + +import { Plugin } from "postcss"; + +declare namespace scope { + interface Options { + generateScopedName?: (exportedName: string, path: string, css: string) => string; + } + + type Scope = Plugin; +} + +declare const scope: scope.Scope; +export = scope; diff --git a/types/postcss-modules-scope/package.json b/types/postcss-modules-scope/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-modules-scope/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-modules-scope/postcss-modules-scope-tests.ts b/types/postcss-modules-scope/postcss-modules-scope-tests.ts new file mode 100644 index 0000000000..b77fa74ab9 --- /dev/null +++ b/types/postcss-modules-scope/postcss-modules-scope-tests.ts @@ -0,0 +1,15 @@ +import scope = require("postcss-modules-scope"); +import { Transformer } from "postcss"; + +const ap1: Transformer = scope(); + +const ap2: Transformer = scope({ + generateScopedName(exportedName, path, css) { + if (css.substring(0, 7) === "@ignore") { + return exportedName; + } + + const sanitisedPath = path.replace(/\.[^\.\/\\]+$/, "").replace(/[\W_]+/g, "_").replace(/^_|_$/g, ""); +return `_${sanitisedPath}__${exportedName}`; + } +}); diff --git a/types/postcss-modules-scope/tsconfig.json b/types/postcss-modules-scope/tsconfig.json new file mode 100644 index 0000000000..b90423a698 --- /dev/null +++ b/types/postcss-modules-scope/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", + "postcss-modules-scope-tests.ts" + ] +} diff --git a/types/postcss-modules-scope/tslint.json b/types/postcss-modules-scope/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-modules-scope/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/postcss-url/index.d.ts b/types/postcss-url/index.d.ts new file mode 100644 index 0000000000..361b69f1c7 --- /dev/null +++ b/types/postcss-url/index.d.ts @@ -0,0 +1,148 @@ +// Type definitions for postcss-url 8.0 +// Project: https://github.com/postcss/postcss-url +// Definitions by: Silas Rech +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { Plugin } from 'postcss'; + +declare namespace url { + type CustomTransformFunction = ( + asset: { + /** + * Original URL. + */ + url: string; + + /** + * URL pathname. + */ + pathname?: string; + + /** + * Absolute path to asset. + */ + absolutePath?: string; + + /** + * Current relative path to asset. + */ + relativePath?: string; + + /** + * Querystring from URL. + */ + search?: string; + + /** + * Hash from URL. + */ + hash?: string; + }, + dir: { + /** + * PostCSS from option. + */ + from?: string; + + /** + * PostCSS to option. + */ + to?: string; + + /** + * File path. + */ + file?: string; + }, + ) => string; + type CustomHashFunction = (file: Buffer) => string; + type CustomFilterFunction = (file: string) => boolean; + + interface Options { + /** + * URL rewriting mechanism. + * + * @default 'rebase' + */ + url?: 'copy' | 'inline' | 'rebase' | CustomTransformFunction; + + /** + * Specify the maximum file size to inline (in kilobytes). + */ + maxSize?: number; + + /** + * Do not warn when an SVG URL with a fragment is inlined. + * PostCSS-URL does not support partial inlining. + * The entire SVG file will be inlined. + * By default a warning will be issued when this occurs. + * + * @default false + */ + ignoreFragmentWarning?: boolean; + + /** + * Determine wether a file should be inlined. + */ + filter?: RegExp | CustomFilterFunction | string; + + /** + * Specifies whether the URL's fragment identifer value, if present, will be added to the inlined data URI. + * + * @default false + */ + includeUriFragment?: boolean; + + /** + * The fallback method to use if the maximum size is exceeded or the URL contains a hash. + */ + fallback?: CustomTransformFunction; + + /** + * Specify the base path or list of base paths where to search images from. + */ + basePath?: string | string[]; + + /** + * The assets files will be copied in that destination. + * + * @default false + */ + assetsPath?: boolean | string; + + /** + * Rename the path of the files by a hash name. + * + * @default false + */ + useHash?: boolean; + + /** + * Hash options + */ + hashOptions?: { + /** + * Hashing method or custom function. + */ + method?: 'xxhash32' | 'xxhash64' | CustomHashFunction; + + /** + * Shrink hast to certain length. + */ + shrink?: number; + + /** + * Append the original filename in resulting filename. + */ + append?: boolean; + }; + } + + type Url = Plugin; +} + +declare const url: url.Url; +export = url; diff --git a/types/postcss-url/package.json b/types/postcss-url/package.json new file mode 100644 index 0000000000..1e1a719545 --- /dev/null +++ b/types/postcss-url/package.json @@ -0,0 +1,6 @@ +{ + "private": true, + "dependencies": { + "postcss": "7.x.x" + } +} diff --git a/types/postcss-url/postcss-url-tests.ts b/types/postcss-url/postcss-url-tests.ts new file mode 100644 index 0000000000..a258b49be4 --- /dev/null +++ b/types/postcss-url/postcss-url-tests.ts @@ -0,0 +1,17 @@ +import * as postcss from 'postcss'; +import * as url from 'postcss-url'; + +const standard: postcss.Transformer = url(); + +const single: postcss.Transformer = url({ url: 'copy', assetsPath: 'img', useHash: true }); + +const multiple: postcss.Transformer = url([ + { filter: '**/assets/copy/*.png', url: 'copy', assetsPath: 'img', useHash: true }, + { filter: '**/assets/inline/*.svg', url: 'inline' }, + { filter: '**/assets/**/*.gif', url: 'rebase' }, + { filter: 'cdn/**/*', url: (asset) => `https://cdn.url/${asset.url}` }, +]); + +postcss().use(standard); +postcss().use(single); +postcss().use(multiple); diff --git a/types/postcss-url/tsconfig.json b/types/postcss-url/tsconfig.json new file mode 100644 index 0000000000..c7759ba2d3 --- /dev/null +++ b/types/postcss-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", + "postcss-url-tests.ts" + ] +} diff --git a/types/postcss-url/tslint.json b/types/postcss-url/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/postcss-url/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/pouchdb-core/index.d.ts b/types/pouchdb-core/index.d.ts index 0dbf5def5b..221b5984b6 100644 --- a/types/pouchdb-core/index.d.ts +++ b/types/pouchdb-core/index.d.ts @@ -1,13 +1,21 @@ -// Type definitions for pouchdb-core 6.4 +// Type definitions for pouchdb-core 7.0 // Project: https://pouchdb.com/ // Definitions by: Simon Paulger , Jakub Navratil , // Brian Geppert , Frederico Galvão , -// Tobias Bales , Sebastián Ramírez +// Tobias Bales , Sebastián Ramírez , +// Katy Moe // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// /// +/// + +interface Blob { + readonly size: number; + readonly type: string; + slice(start?: number, end?: number, contentType?: string): Blob; +} interface Buffer extends Uint8Array { write(string: string, offset?: number, length?: number, encoding?: string): number; @@ -81,6 +89,11 @@ interface EventEmitter { eventNames(): Array; } +type Fetch = ( + url: string | Request, + opts?: RequestInit +) => Promise; + declare namespace PouchDB { namespace Core { interface Error { @@ -104,7 +117,7 @@ declare namespace PouchDB { type AttachmentData = string | Blob | Buffer; interface Options { - ajax?: Configuration.RemoteRequesterConfiguration; + fetch?: Fetch; } interface BasicResponse { @@ -562,33 +575,8 @@ declare namespace PouchDB { size?: number; } - interface RemoteRequesterConfiguration { - /** - * Time before HTTP requests time out (in ms). - */ - timeout?: number; - /** - * Appends a random string to the end of all HTTP GET requests to avoid - * them being cached on IE. Set this to true to prevent this happening. - */ - cache?: boolean; - /** - * HTTP headers to add to requests. - */ - headers?: { - [name: string]: string; - }; - - /** - * Enables transferring cookies and HTTP Authorization information. - * - * Defaults to true. - */ - withCredentials?: boolean; - } - interface RemoteDatabaseConfiguration extends CommonDatabaseConfiguration { - ajax?: RemoteRequesterConfiguration; + fetch?: Fetch; auth?: { username?: string; @@ -609,6 +597,8 @@ declare namespace PouchDB { version: string; + fetch: Fetch; + on(event: 'created' | 'destroyed', listener: (dbName: string) => any): this; debug: debug.IDebug; diff --git a/types/pouchdb-core/pouchdb-core-tests.ts b/types/pouchdb-core/pouchdb-core-tests.ts index f8accd1c3a..911a21e2f7 100644 --- a/types/pouchdb-core/pouchdb-core-tests.ts +++ b/types/pouchdb-core/pouchdb-core-tests.ts @@ -50,7 +50,7 @@ function testBulkDocs() { const isError = ( result: PouchDB.Core.Response | PouchDB.Core.Error ): result is PouchDB.Core.Error => { - return !!( result).error; + return !!(result as PouchDB.Core.Error).error; }; db.bulkDocs([model, model2]).then((result) => { @@ -233,12 +233,8 @@ function testChanges() { function testRemoteOptions() { const db = new PouchDB('http://example.com/dbname', { - ajax: { - cache: false, - timeout: 10000, - headers: { - 'X-Some-Special-Header': 'foo' - }, + fetch(url, opts) { + return PouchDB.fetch(url, opts); }, auth: { username: 'mysecretusername', diff --git a/types/pouchdb-upsert/index.d.ts b/types/pouchdb-upsert/index.d.ts index d044e9f2a4..7646f55f01 100644 --- a/types/pouchdb-upsert/index.d.ts +++ b/types/pouchdb-upsert/index.d.ts @@ -59,7 +59,10 @@ declare namespace PouchDB { } type CancelUpsert = '' | 0 | false | null | undefined; // falsey values - type UpsertDiffCallback = (doc: Core.Document | {}) => Content & Partial | CancelUpsert; + // `Partial>` seems more useful than + // `{} | Core.Document` since there isn't an easy way to narrow + // `{} | Core.Document` to `Core.Document`. + type UpsertDiffCallback = (doc: Partial>) => Content & Partial | CancelUpsert; interface UpsertResponse { id: Core.DocumentId; diff --git a/types/pouchdb-upsert/pouchdb-upsert-tests.ts b/types/pouchdb-upsert/pouchdb-upsert-tests.ts index b86afedf29..0f718bb033 100644 --- a/types/pouchdb-upsert/pouchdb-upsert-tests.ts +++ b/types/pouchdb-upsert/pouchdb-upsert-tests.ts @@ -2,61 +2,64 @@ import * as pouchdbUpsert from 'pouchdb-upsert'; PouchDB.plugin(pouchdbUpsert); interface UpsertDocModel { - name: string; - readonly?: boolean; + name: string; + readonly?: boolean; } declare const docToUpsert: PouchDB.Core.Document; const db = new PouchDB(); function testUpsert_WithPromise_AndReturnDoc() { - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { // Make some updates.... - return doc; + // `doc` may be empty if the document didn't already exist, so we have to + // cast it to the type containing the required fields. If the document type + // had all optional fields, the cast would not be necessary. + return doc as UpsertDocModel; }).then((res: PouchDB.UpsertResponse) => { }); } function testUpsert_WithPromise_AndReturnFalsey() { - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { if (doc.readonly) return false; // Make some updates.... - return doc; + return doc as UpsertDocModel; }).then((res: PouchDB.UpsertResponse) => { }); } function testUpsert_WithPromise_AndReturnNewObject() { // callback return boolean - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { return {name: 'test', readonly: true}; }).then((res: PouchDB.UpsertResponse) => { }); } function testUpsert_WithCallback_AndReturnDoc() { - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { // Make some updates.... - return doc; - }, (res: PouchDB.UpsertResponse) => {}); + return doc as UpsertDocModel; + }, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } function testUpsert_WithCallback_AndReturnFalsey() { // callback return boolean - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { if (doc.readonly) return false; // Make some updates.... - return doc; - }, (res: PouchDB.UpsertResponse) => {}); + return doc as UpsertDocModel; + }, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } function testUpsert_WithCallback_AndReturnNewObject() { // callback return boolean - db.upsert(docToUpsert._id, (doc: PouchDB.Core.Document) => { + db.upsert(docToUpsert._id, (doc) => { return {name: 'test', readonly: true}; - }, (res: PouchDB.UpsertResponse) => {}); + }, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } function testPutIfNotExists_WithPromise() { @@ -64,5 +67,5 @@ function testPutIfNotExists_WithPromise() { } function testPutIfNotExists_WithCallback() { - db.putIfNotExists(docToUpsert, (res: PouchDB.UpsertResponse) => {}); + db.putIfNotExists(docToUpsert, (error: PouchDB.Core.Error, res: PouchDB.UpsertResponse) => {}); } diff --git a/types/pouchdb-upsert/tsconfig.json b/types/pouchdb-upsert/tsconfig.json index ff5dc47e0c..300103a1fa 100644 --- a/types/pouchdb-upsert/tsconfig.json +++ b/types/pouchdb-upsert/tsconfig.json @@ -8,7 +8,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/prettier/index.d.ts b/types/prettier/index.d.ts index acb6b09af6..6cef2ef27a 100644 --- a/types/prettier/index.d.ts +++ b/types/prettier/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for prettier 1.13 +// Type definitions for prettier 1.15 // Project: https://github.com/prettier/prettier // Definitions by: Ika // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -33,7 +33,11 @@ export type BuiltInParserName = | 'json-stringify' | 'graphql' | 'markdown' - | 'vue'; + | 'vue' + | 'html' + | 'angular' + | 'mdx' + | 'yaml'; export type CustomParser = (text: string, parsers: Record, options: Options) => AST; @@ -47,6 +51,10 @@ export interface RequiredOptions extends doc.printer.Options { * Use single quotes instead of double quotes. */ singleQuote: boolean; + /** + * Use single quotes in JSX. + */ + jsxSingleQuote: boolean; /** * Print trailing commas wherever possible. */ @@ -104,6 +112,14 @@ export interface RequiredOptions extends doc.printer.Options { * The plugin API is in a beta state. */ plugins: Array; + /** + * How to handle whitespaces in HTML. + */ + htmlWhitespaceSensitivity: 'css' | 'strict' | 'ignore'; + /** + * Which end of line characters to apply. + */ + endOfLine: 'auto' | 'lf' | 'crlf' | 'cr'; } export interface ParserOptions extends RequiredOptions { @@ -240,7 +256,7 @@ export function clearConfigCache(): void; export interface SupportLanguage { name: string; since?: string; - parsers: string[]; + parsers: BuiltInParserName[] | string[]; group?: string; tmScope: string; aceMode: string; 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/proj4leaflet/tsconfig.json b/types/proj4leaflet/tsconfig.json index 697b96a93a..4b2115dd9d 100644 --- a/types/proj4leaflet/tsconfig.json +++ b/types/proj4leaflet/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/project-oxford/project-oxford-tests.ts b/types/project-oxford/project-oxford-tests.ts index b4a76a78c4..8b1dbec466 100644 --- a/types/project-oxford/project-oxford-tests.ts +++ b/types/project-oxford/project-oxford-tests.ts @@ -12,7 +12,7 @@ const {describe, it, before, after, beforeEach, afterEach} = null as any as { var client = new oxford.Client(process.env.OXFORD_KEY); // Store variables, no point in calling the api too often -var billFaces = []; +var billFaces = [] as string[]; var personGroupId = "uuid.v4()"; var personGroupId2 = "uuid.v4()"; var billPersonId: string; @@ -85,7 +85,7 @@ describe('Project Oxford Face API Test', function () { describe('#similar()', function () { it('detects similar faces', function (done) { - var detects = []; + var detects = []; this.timeout(10000); @@ -113,7 +113,7 @@ describe('Project Oxford Face API Test', function () { describe('#grouping()', function () { it('detects groups faces', function (done) { - var faceIds = []; + var faceIds = [] as string[]; this.timeout(10000); @@ -157,7 +157,7 @@ describe('Project Oxford Face API Test', function () { // delete the group then. So we clean up before we run tests - and to wait // for cleanup to finish, we're just using done(). client.face.personGroup.list().then(function (response) { - var promises = []; + var promises: _Promise[] = []; response.forEach(function (personGroup) { if (personGroup.name.indexOf('po-node-test-group') > -1) { diff --git a/types/promise-memoize/index.d.ts b/types/promise-memoize/index.d.ts new file mode 100644 index 0000000000..32b1f51aba --- /dev/null +++ b/types/promise-memoize/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for promise-memoize 1.2 +// Project: https://github.com/nodeca/promise-memoize#readme +// Definitions by: Emily Marigold Klassen +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = promiseMemoize; + +declare function promiseMemoize PromiseLike>( + fn: T, options?: promiseMemoize.Options +): T & { + clear(): void; +}; + +declare namespace promiseMemoize { + interface Options { + maxAge?: number; + maxErrorAge?: number; + resolve?: KeyResolver; + } + type KeyResolver = 'simple' | 'json' | ((args: any[]) => any) | ReadonlyArray<'json' | ((arg: any) => any)>; +} diff --git a/types/promise-memoize/promise-memoize-tests.ts b/types/promise-memoize/promise-memoize-tests.ts new file mode 100644 index 0000000000..a8cf6b57c8 --- /dev/null +++ b/types/promise-memoize/promise-memoize-tests.ts @@ -0,0 +1,14 @@ +import promiseMemoize = require('promise-memoize'); + +async function lastPosts(n: number) { + return n + 1; +} + +const cachedLastPosts = promiseMemoize(lastPosts, {maxAge: 60000}); + +// Later... +cachedLastPosts(10).then(posts => { + posts; +}); + +cachedLastPosts.clear(); diff --git a/types/promise-memoize/tsconfig.json b/types/promise-memoize/tsconfig.json new file mode 100644 index 0000000000..58058661dd --- /dev/null +++ b/types/promise-memoize/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", + "promise-memoize-tests.ts" + ] +} diff --git a/types/promise-memoize/tslint.json b/types/promise-memoize/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/promise-memoize/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/promise-polyfill/index.d.ts b/types/promise-polyfill/index.d.ts index 703f7a6a8c..83036cf4ff 100644 --- a/types/promise-polyfill/index.d.ts +++ b/types/promise-polyfill/index.d.ts @@ -1,6 +1,13 @@ -// Type definitions for promise v6.0.2 +// Type definitions for promise-polyfill 6.0 // Project: https://www.npmjs.com/package/promise-polyfill // Definitions by: Steve Jenkins +// Daniel Cassidy // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export default Promise; \ No newline at end of file +export interface PromisePolyfillConstructor extends PromiseConstructor { + _immediateFn?: (handler: (() => void) | string) => void; +} + +declare const Promise: PromisePolyfillConstructor; + +export default Promise; diff --git a/types/promise-polyfill/promise-polyfill-tests.ts b/types/promise-polyfill/promise-polyfill-tests.ts index 280a2bebdf..cfdd803126 100644 --- a/types/promise-polyfill/promise-polyfill-tests.ts +++ b/types/promise-polyfill/promise-polyfill-tests.ts @@ -1,3 +1,5 @@ +import Promise from "promise-polyfill"; + const prom1 = new Promise((resolve, reject) => { resolve(12); }); @@ -15,4 +17,6 @@ Promise.all([prom1, prom2]) .then(result => { console.log(result); }, (exception) => console.error(exception)) -.catch((ex) => console.error(ex)); \ No newline at end of file +.catch((ex) => console.error(ex)); + +Promise._immediateFn = setTimeout; diff --git a/types/promise-polyfill/tslint.json b/types/promise-polyfill/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/promise-polyfill/tslint.json +++ b/types/promise-polyfill/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/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 new file mode 100644 index 0000000000..7aa3f2ea63 --- /dev/null +++ b/types/prompts/index.d.ts @@ -0,0 +1,89 @@ +// Type definitions for prompts 1.1 +// Project: https://github.com/terkelg/prompts +// Definitions by: Berkay GURSOY +// Daniel Perez Alvarez +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export = prompts; + +declare function prompts( + questions: prompts.PromptObject | Array>, + options?: prompts.Options +): Promise>; + +declare namespace prompts { + // Circular reference from prompts + const prompt: any; + + function inject(obj: any): void; + + namespace inject { + const prototype: {}; + } + + namespace prompts { + function autocomplete(args: PromptObject): any; + + function confirm(args: PromptObject): void; + + function invisible(args: PromptObject): any; + + function list(args: PromptObject): any; + + function multiselect(args: PromptObject): any; + + function number(args: PromptObject): void; + + function password(args: PromptObject): any; + + function select(args: PromptObject): void; + + function text(args: PromptObject): void; + + function toggle(args: PromptObject): void; + } + + interface Choice { + title: string; + value: string; + } + + interface Options { + onSubmit: (prompt: PromptObject, answer: any, answers: any[]) => void; + onCancel: (prompt: PromptObject, answers: any) => void; + } + + interface PromptObject { + type: ValueOrFunc; + name: ValueOrFunc; + message?: ValueOrFunc; + initial?: string; + style?: string; + format?: PrevCaller; + validate?: PrevCaller; + onState?: PrevCaller; + min?: number; + max?: number; + float?: boolean; + round?: number; + increment?: number; + seperator?: string; + active?: string; + inactive?: string; + choices?: Choice[]; + hint?: string; + suggest?: ((prev: any, values: any, prompt: PromptObject) => void); + limit?: number; + } + + type Answers = { [id in T]: any }; + + type PrevCaller = ( + prev: any, + values: Answers, + prompt: PromptObject + ) => R; + + type ValueOrFunc = T | PrevCaller; +} diff --git a/types/prompts/prompts-tests.ts b/types/prompts/prompts-tests.ts new file mode 100644 index 0000000000..bd35868c66 --- /dev/null +++ b/types/prompts/prompts-tests.ts @@ -0,0 +1,14 @@ +import prompts = require("prompts"); + +type HasProperty = K extends keyof T ? true : false; + +(async () => { + const response = await prompts({ + type: "number", + name: "value", + message: "Input value to double:", + validate: (value: any) => (value < 0 ? `Cant be less than zero` : true) + }); + const HasPropValue: HasProperty = true; + const DoesntHavePropAsdf: HasProperty = false; +})(); diff --git a/types/prompts/tsconfig.json b/types/prompts/tsconfig.json new file mode 100644 index 0000000000..e8a46be254 --- /dev/null +++ b/types/prompts/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", + "prompts-tests.ts" + ] +} \ No newline at end of file diff --git a/types/prompts/tslint.json b/types/prompts/tslint.json new file mode 100644 index 0000000000..e60c15844f --- /dev/null +++ b/types/prompts/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/prop-types/index.d.ts b/types/prop-types/index.d.ts index 3b0a1164d6..b6918d9d44 100644 --- a/types/prop-types/index.d.ts +++ b/types/prop-types/index.d.ts @@ -41,12 +41,12 @@ 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 = - & InferPropsInner>> - & Partial>>>; + & (RequiredKeys extends undefined ? {} : InferPropsInner>>) + & (OptionalKeys extends undefined ? {} : Partial>>>); export const any: Requireable; export const array: Requireable; diff --git a/types/prosemirror-markdown/index.d.ts b/types/prosemirror-markdown/index.d.ts index 7af366c04e..91b37ea51e 100644 --- a/types/prosemirror-markdown/index.d.ts +++ b/types/prosemirror-markdown/index.d.ts @@ -7,7 +7,7 @@ // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 -import { MarkdownIt } from 'markdown-it'; +import MarkdownIt = require('markdown-it'); import { Node as ProsemirrorNode, Schema } from 'prosemirror-model'; /** diff --git a/types/prosemirror-schema-basic/tsconfig.json b/types/prosemirror-schema-basic/tsconfig.json index 44a2b36f28..ee4a9ce7fb 100644 --- a/types/prosemirror-schema-basic/tsconfig.json +++ b/types/prosemirror-schema-basic/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/prosemirror-schema-list/tsconfig.json b/types/prosemirror-schema-list/tsconfig.json index 3bc76fb24f..294d13e9a6 100644 --- a/types/prosemirror-schema-list/tsconfig.json +++ b/types/prosemirror-schema-list/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/proton-native/index.d.ts b/types/proton-native/index.d.ts index e191c00698..0177d00542 100644 --- a/types/proton-native/index.d.ts +++ b/types/proton-native/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for proton-native 1.1 // Project: https://github.com/kusti8/proton-native // Definitions by: Nguyen Xuan Khanh +// Lukas Tetzlaff // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -421,6 +422,13 @@ export interface GridChildrenProps { * What row the component resides in. */ row?: number; + /** + * How many rows/columns the component takes off. + */ + span?: { + x: number; + y: number; + }; } export interface GridProps { @@ -608,7 +616,7 @@ export interface RadioButtonsProps extends GridChildrenProps, Label, Stretchy { /** * Called when a RadioButton is selected. The number selected is passed as an argument. */ - onSelect?: (selected: boolean) => void; + onSelect?: (selected: number) => void; /** * What RadioButton is selected, zero-indexed. -1 means nothing is selected. */ diff --git a/types/proton-native/test/index.tsx b/types/proton-native/test/index.tsx index 901cf3e155..ac0aa21a28 100644 --- a/types/proton-native/test/index.tsx +++ b/types/proton-native/test/index.tsx @@ -48,7 +48,7 @@ class RadioTest extends React.Component { return ( - + selected.toFixed()} enabled={true}> Option 1 Option 2 @@ -118,6 +118,14 @@ class GridTest extends React.Component { >
          + +
          +
          diff --git a/types/protractor-helpers/index.d.ts b/types/protractor-helpers/index.d.ts index bc52455d6e..686c2442be 100644 --- a/types/protractor-helpers/index.d.ts +++ b/types/protractor-helpers/index.d.ts @@ -2,7 +2,7 @@ // Project: https://github.com/wix/protractor-helpers // Definitions by: John Cant // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 +// TypeScript Version: 2.8 import * as webdriver from "selenium-webdriver"; 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/pumpify/tsconfig.json b/types/pumpify/tsconfig.json index c616e0e309..2ecb43cc87 100644 --- a/types/pumpify/tsconfig.json +++ b/types/pumpify/tsconfig.json @@ -2,7 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es5" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, 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-core/index.d.ts b/types/puppeteer-core/index.d.ts new file mode 100644 index 0000000000..0afa8ae704 --- /dev/null +++ b/types/puppeteer-core/index.d.ts @@ -0,0 +1,7 @@ +// Type definitions for puppeteer-core 1.9 +// Project: https://github.com/GoogleChrome/puppeteer#readme +// Definitions by: Fumiaki Matsushima +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +export * from "puppeteer"; diff --git a/types/puppeteer-core/puppeteer-core-tests.ts b/types/puppeteer-core/puppeteer-core-tests.ts new file mode 100644 index 0000000000..6e5c38c98e --- /dev/null +++ b/types/puppeteer-core/puppeteer-core-tests.ts @@ -0,0 +1,12 @@ +import * as puppeteer from "puppeteer-core"; + +(async () => { + const browser = await puppeteer.connect(); + const page = await browser.newPage(); + await page.goto("https://example.com", { + referer: 'http://google.com', + }); + await page.screenshot({ path: "example.png" }); + + browser.close(); +})(); diff --git a/types/puppeteer-core/tsconfig.json b/types/puppeteer-core/tsconfig.json new file mode 100644 index 0000000000..d22fa100f6 --- /dev/null +++ b/types/puppeteer-core/tsconfig.json @@ -0,0 +1,16 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6", "dom", "es2017"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "puppeteer-core-tests.ts"] +} diff --git a/types/puppeteer-core/tslint.json b/types/puppeteer-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/puppeteer-core/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 a7faa7f569..2051603f69 100644 --- a/types/puppeteer/index.d.ts +++ b/types/puppeteer/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for puppeteer 1.8 +// Type definitions for puppeteer 1.11 // Project: https://github.com/GoogleChrome/puppeteer#readme // Definitions by: Marvin Hagemeister // Christopher Deutsch @@ -291,6 +291,8 @@ export interface TracingStartOptions { categories?: string[]; } +export type DialogType = "alert" | "beforeunload" | "confirm" | "prompt"; + /** Dialog objects are dispatched by page via the 'dialog' event. */ export interface Dialog { /** @@ -309,18 +311,35 @@ export interface Dialog { message(): string; /** The dialog type. Dialog's type, can be one of `alert`, `beforeunload`, `confirm` or `prompt`. */ - type(): "alert" | "beforeunload" | "confirm" | "prompt"; + type(): DialogType; } +export type ConsoleMessageType = "log" + | "debug" + | "info" + | "error" + | "warning" + | "dir" + | "dirxml" + | "table" + | "trace" + | "clear" + | "startGroup" + | "startGroupCollapsed" + | "endGroup" + | "assert" + | "profile" + | "profileEnd" + | "count" + | "timeEnd"; + /** ConsoleMessage objects are dispatched by page via the 'console' event. */ export interface ConsoleMessage { /** The message arguments. */ args(): JSHandle[]; /** The message text. */ text(): string; - type(): 'log' | 'debug' | 'info' | 'error' | 'warning' | 'dir' | 'dirxml' | 'table' | - 'trace' | 'clear' | 'startGroup' | 'startGroupCollapsed' | 'endGroup' | 'assert' | - 'profile' | 'profileEnd' | 'count' | 'timeEnd'; + type(): ConsoleMessageType; } export type PageEvents = @@ -365,6 +384,8 @@ export interface ClickOptions { delay?: number; } +export type SameSiteSetting = "Strict" | "Lax"; + /** Represents a browser cookie. */ export interface Cookie { /** The cookie name. */ @@ -377,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. */ @@ -384,7 +407,7 @@ export interface Cookie { /** The cookie secure flag. */ secure: boolean; /** The cookie same site definition. */ - sameSite: "Strict" | "Lax"; + sameSite: SameSiteSetting; } export interface DeleteCookie { @@ -393,7 +416,6 @@ export interface DeleteCookie { url?: string; domain?: string; path?: string; - secure?: boolean; } export interface SetCookie { @@ -416,7 +438,7 @@ export interface SetCookie { /** The cookie secure flag. */ secure?: boolean; /** The cookie same site definition. */ - sameSite?: "Strict" | "Lax"; + sameSite?: SameSiteSetting; } export interface Viewport { @@ -462,13 +484,16 @@ export type LoadEvent = | "networkidle0" | "networkidle2"; +export interface Timeoutable { + /** + * Maximum navigation time in milliseconds, pass 0 to disable timeout. + * @default 30000 + */ + timeout?: number; +} + /** The navigation options. */ -export interface NavigationOptions { - /** - * Maximum navigation time in milliseconds, pass 0 to disable timeout. - * @default 30000 - */ - timeout?: number; +export interface NavigationOptions extends Timeoutable { /** * When to consider navigation succeeded. * @default load Navigation is consider when the `load` event is fired. @@ -488,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" @@ -555,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. @@ -644,9 +671,8 @@ export interface ScriptTagOptions { type?: string; } -export interface PageFnOptions { +export interface PageFnOptions extends Timeoutable { polling?: "raf" | "mutation" | number; - timeout?: number; } export interface BoundingBox { @@ -945,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. @@ -1018,6 +1044,8 @@ export interface RemoteInfo { export interface Response { /** Promise which resolves to a buffer with response body. */ buffer(): Promise; + /** A Frame that initiated this response, or null if navigating to error pages. */ + frame(): Frame | null; /** True if the response was served from either the browser's disk cache or memory cache. */ fromCache(): boolean; /** True if the response was served by a service worker. */ @@ -1045,7 +1073,7 @@ export interface Response { url(): string; } -export interface WaitForSelectorOptions { +export interface WaitForSelectorOptions extends Timeoutable { /** * Wait for element to be present in DOM and to be visible, * i.e. to not have display: none or visibility: hidden CSS properties. @@ -1058,12 +1086,6 @@ export interface WaitForSelectorOptions { * @default false */ hidden?: boolean; - /** - * Maximum time to wait for in milliseconds. - * Pass 0 to disable timeout. - * @default 30000 (30 seconds). - */ - timeout?: number; } export interface FrameBase extends Evalable { @@ -1103,6 +1125,13 @@ export interface FrameBase extends Evalable { /** Gets the full HTML contents of the page, including the doctype. */ content(): Promise; + /** + * Navigates to a URL. + * @param url URL to navigate page to. The url should include scheme, e.g. `https://` + * @param options The navigation parameters. + */ + goto(url: string, options?: DirectNavigationOptions): Promise; + /** * Evaluates a function in the browser context. * If the function, passed to the frame.evaluate, returns a Promise, then frame.evaluate would wait for the promise to resolve and return its value. @@ -1139,11 +1168,21 @@ export interface FrameBase extends Evalable { */ hover(selector: string): Promise; + /** + * Triggers a `change` and `input` event once all the provided options have been selected. + * If there's no `` has the `multiple` attribute, + * all values are considered, otherwise only the first one is taken into account. + */ + select(selector: string, ...values: string[]): Promise; + /** * 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, @@ -1176,17 +1215,27 @@ export interface FrameBase extends Evalable { * Shortcut for waitForSelector and waitForXPath */ waitFor(selector: string, options?: WaitForSelectorOptions): Promise; + /** * Shortcut for waitForFunction. */ waitFor(selector: ((...args: any[]) => any) | string, options?: WaitForSelectorOptions, ...args: any[]): Promise; + /** + * Allows waiting for various conditions. + */ waitForFunction( fn: string | ((...args: any[]) => any), options?: PageFnOptions, ...args: any[] ): Promise; + /** + * Wait for the page navigation occur. + * @param options The navigation parameters. + */ + waitForNavigation(options?: NavigationOptions): Promise; + waitForSelector( selector: string, options?: WaitForSelectorOptions, @@ -1280,6 +1329,139 @@ export interface GeoOptions { accuracy?: number; } +export type MediaType = "screen" | "print"; + +export interface AXNode { + /** + * The role. + */ + role: string; + /** + * A human readable name for the node. + */ + name: string; + /** + * The current value of the node. + */ + value: string | number; + /** + * An additional human readable description of the node. + */ + description: string; + /** + * Keyboard shortcuts associated with this node. + */ + keyshortcuts: string; + /** + * A human readable alternative to the role. + */ + roledescription: string; + /** + * A description of the current value. + */ + valuetext: string; + /** + * Whether the node is disabled. + */ + disabled: boolean; + /** + * Whether the node is expanded or collapsed. + */ + expanded: boolean; + /** + * Whether the node is focused. + */ + focused: boolean; + /** + * Whether the node is modal. + */ + modal: boolean; + /** + * Whether the node text input supports multiline. + */ + multiline: boolean; + /** + * Whether more than one child can be selected. + */ + multiselectable: boolean; + /** + * Whether the node is read only. + */ + readonly: boolean; + /** + * Whether the node is required. + */ + required: boolean; + /** + * Whether the node is selected in its parent node. + */ + selected: boolean; + /** + * Whether the checkbox is checked, or "mixed". + */ + checked: boolean | "mixed"; + /** + * Whether the toggle button is checked, or "mixed". + */ + pressed: boolean | "mixed"; + /** + * The level of a heading. + */ + level: number; + /** + * The minimum value in a node. + */ + valuemin: number; + /** + * The maximum value in a node. + */ + valuemax: number; + /** + * What kind of autocomplete is supported by a control. + */ + autocomplete: string; + /** + * What kind of popup is currently being shown for a node. + */ + haspopup: string; + /** + * Whether and in what way this node's value is invalid. + */ + invalid: string; + /** + * Whether the node is oriented horizontally or vertically. + */ + orientation: string; + /** + * Child nodes of this node, if any. + */ + children: AXNode[]; +} + +export interface SnapshopOptions { + /** + * Prune uninteresting nodes from the tree. + * @default true + */ + interestingOnly?: boolean; +} + +/** + * The Accessibility class provides methods for inspecting Chromium's accessibility tree. + * The accessibility tree is used by assistive technology such as screen readers. + * Accessibility is a very platform-specific thing. On different platforms, + * there are different screen readers that might have wildly different output. + * Blink - Chrome's rendering engine - has a concept of "accessibility tree", + * which is than translated into different platform-specific APIs. + * Accessibility namespace gives users access to the Blink Accessibility Tree. + * Most of the accessibility tree gets filtered out when converting from Blink AX Tree to Platform-specific AX-Tree or + * by screen readers themselves. By default, Puppeteer tries to approximate this filtering, + * exposing only the "interesting" nodes of the tree. + */ +export interface Accessibility { + snapshot(options?: SnapshopOptions): Promise; +} + /** Page provides methods to interact with a single tab in Chromium. One Browser instance might have multiple Page instances. */ export interface Page extends EventEmitter, FrameBase { /** @@ -1305,6 +1487,8 @@ export interface Page extends EventEmitter, FrameBase { handler: (e: PageEventObj[K], ...args: any[]) => void ): this; + accessibility: Accessibility; + /** * Provide credentials for http authentication. * To disable authentication, pass `null`. @@ -1338,7 +1522,7 @@ export interface Page extends EventEmitter, FrameBase { emulate(options: EmulateOptions): Promise; /** Emulates the media. */ - emulateMedia(mediaType: 'screen' | 'print' | null): Promise; + emulateMedia(mediaType: MediaType | null): Promise; /** * Evaluates a function in the page context. @@ -1388,13 +1572,6 @@ export interface Page extends EventEmitter, FrameBase { */ goForward(options?: NavigationOptions): Promise; - /** - * Navigates to a URL. - * @param url URL to navigate page to. The url should include scheme, e.g. `https://` - * @param options The navigation parameters. - */ - goto(url: string, options?: DirectNavigationOptions): Promise; - /** Returns the virtual keyboard. */ keyboard: Keyboard; @@ -1437,15 +1614,6 @@ export interface Page extends EventEmitter, FrameBase { screenshot(options?: BinaryScreenShotOptions): Promise; screenshot(options?: ScreenshotOptions): Promise; - /** - * Triggers a `change` and `input` event once all the provided options have been selected. - * If there's no `` has the `multiple` attribute, - * all values are considered, otherwise only the first one is taken into account. - */ - select(selector: string, ...values: string[]): Promise; - /** * Toggles bypassing page's Content-Security-Policy. * NOTE CSP bypassing happens at the moment of CSP initialization rather then evaluation. @@ -1456,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. @@ -1536,28 +1704,26 @@ export interface Page extends EventEmitter, FrameBase { /** Gets the page viewport. */ viewport(): Viewport; - /** - * Wait for the page navigation occur. - * @param options The navigation parameters. - */ - waitForNavigation(options?: NavigationOptions): Promise; - waitForRequest( urlOrPredicate: string | ((req: Request) => boolean), - options?: { timeout?: number } + options?: Timeoutable ): Promise; waitForResponse( urlOrPredicate: string | ((res: Response) => boolean), - options?: { timeout?: number } + options?: Timeoutable ): Promise; /** This method returns all of the dedicated WebWorkers associated with the page. */ workers(): Worker[]; } +export interface TargetAwaiter { + waitForTarget(predicate: (target: Target) => boolean, options?: Timeoutable): Promise; +} + /** A Browser is created when Puppeteer connects to a Chromium instance, either through puppeteer.launch or puppeteer.connect. */ -export interface Browser extends EventEmitter { +export interface Browser extends EventEmitter, TargetAwaiter { /** * Adds the listener function to the end of the listeners array for the event named `eventName`. * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of @@ -1620,6 +1786,9 @@ export interface Browser extends EventEmitter { /** Spawned browser process. Returns `null` if the browser instance was created with `puppeteer.connect` method */ process(): ChildProcess; + /** A target associated with the browser. */ + target(): Target; + /** Promise which resolves to an array of all active targets. */ targets(): Promise; @@ -1651,29 +1820,29 @@ export interface BrowserEventObj { } export type Permission = - 'geolocation' | - 'midi' | - 'midi-sysex' | - 'notifications' | - 'push' | - 'camera' | - 'microphone' | - 'background-sync' | - 'ambient-light-sensor' | - 'accelerometer' | - 'gyroscope' | - 'magnetometer' | - 'accessibility-events' | - 'clipboard-read' | - 'clipboard-write' | - 'payment-handler'; + "geolocation" | + "midi" | + "midi-sysex" | + "notifications" | + "push" | + "camera" | + "microphone" | + "background-sync" | + "ambient-light-sensor" | + "accelerometer" | + "gyroscope" | + "magnetometer" | + "accessibility-events" | + "clipboard-read" | + "clipboard-write" | + "payment-handler"; /** * BrowserContexts provide a way to operate multiple independent browser sessions. * When a browser is launched, it has a single BrowserContext used by default. * The method `browser.newPage()` creates a page in the default browser context. */ -export interface BrowserContext extends EventEmitter { +export interface BrowserContext extends EventEmitter, TargetAwaiter { /** * Adds the listener function to the end of the listeners array for the event named `eventName`. * No checks are made to see if the listener has already been added. Multiple calls passing the same combination of @@ -1743,6 +1912,8 @@ export interface BrowserContextEventObj { targetdestroyed: Target; } +export type TargetType = "page" | "background_page" | "service_worker" | "browser" | "other"; + export interface Target { /** Get the browser the target belongs to. */ browser(): Browser; @@ -1760,33 +1931,13 @@ export interface Target { page(): Promise; /** Identifies what kind of target this is. */ - type(): "page" | "background_page" | "service_worker" | "browser" | "other"; + type(): TargetType; /** Returns the target URL. */ url(): string; } -export interface LaunchOptions { - /** - * 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 @@ -1794,10 +1945,73 @@ export interface LaunchOptions { */ 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. */ @@ -1821,7 +2035,6 @@ export interface LaunchOptions { */ isMobile?: boolean; /** - * * Specifies if viewport supports touch events. * @default false */ @@ -1831,89 +2044,28 @@ export interface LaunchOptions { * @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; - /** - * Maximum time in milliseconds to wait for the Chrome instance to start. - * Pass 0 to disable timeout. - * @default 30000 (30 seconds). - */ - timeout?: number; - /** - * 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 { @@ -1958,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 84d1c12487..e2a559d8e6 100644 --- a/types/puppeteer/puppeteer-tests.ts +++ b/types/puppeteer/puppeteer-tests.ts @@ -1,5 +1,19 @@ import * as puppeteer from "puppeteer"; import { TimeoutError } from "puppeteer/Errors"; +import * as Devices from "puppeteer/DeviceDescriptors"; + +// Accessibility + +(async () => { + const browser = await puppeteer.launch(); + const page = await browser.newPage(); + const snap = await page.accessibility.snapshot({ + interestingOnly: true, + }); + for (const child of snap.children) { + console.log(child.name); + } +}); // Basic nagivation (async () => { @@ -19,6 +33,9 @@ import { TimeoutError } from "puppeteer/Errors"; await page.goto("https://news.ycombinator.com", { waitUntil: "networkidle0" }); await page.pdf({ path: "hn.pdf", format: "A4" }); + const frame = page.frames()[0]; + await frame.goto('/'); + browser.close(); })(); @@ -102,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); @@ -184,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({ @@ -440,6 +465,11 @@ puppeteer.launch().then(async browser => { await page.waitFor((stuff: string) => !!document.querySelector(stuff), { hidden: true, }, 'asd'); + + const frame: puppeteer.Frame = page.frames()[0]; + await frame.waitFor((stuff: string) => !!document.querySelector(stuff), { + hidden: true, + }, 'asd'); })(); // Permission tests 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/puppeteer/v0/puppeteer-tests.ts b/types/puppeteer/v0/puppeteer-tests.ts index 963fb1c8c1..76717da98f 100644 --- a/types/puppeteer/v0/puppeteer-tests.ts +++ b/types/puppeteer/v0/puppeteer-tests.ts @@ -27,8 +27,8 @@ import * as puppeteer from "puppeteer"; // Get the "viewport" of the page, as reported by the page. const dimensions = await page.evaluate(() => { return { - width: document.documentElement!.clientWidth, - height: document.documentElement!.clientHeight, + width: document.documentElement!.clientWidth, // tslint:disable-line no-unnecessary-type-assertion + height: document.documentElement!.clientHeight, // tslint:disable-line no-unnecessary-type-assertion deviceScaleFactor: window.devicePixelRatio }; }); 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/qhistory/index.d.ts b/types/qhistory/index.d.ts index 84bd4e6d83..6269c25e82 100644 --- a/types/qhistory/index.d.ts +++ b/types/qhistory/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for qhistory 1.0 // Project: https://github.com/pshrmn/qhistory#readme -// Definitions by: Diogo Franco +// Definitions by: Jessica Franco // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 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/query-string/index.d.ts b/types/query-string/index.d.ts index 8a2f4a30ea..6e560f57e9 100644 --- a/types/query-string/index.d.ts +++ b/types/query-string/index.d.ts @@ -13,13 +13,21 @@ export interface ParseOptions { decode?: boolean; } +export interface InputParams { + [key: string]: any; +} + +export interface OutputParams { + [key: string]: string | string[] | undefined; +} + /** * Parse a query string into an object. * Leading ? or # are ignored, so you can pass location.search or location.hash directly. */ -export function parse(str: string, options?: ParseOptions): any; +export function parse(str: string, options?: ParseOptions): OutputParams; -export function parseUrl(str: string, options?: ParseOptions): {url: string, query: any}; +export function parseUrl(str: string, options?: ParseOptions): {url: string, query: OutputParams}; export interface StringifyOptions { strict?: boolean; @@ -30,7 +38,7 @@ export interface StringifyOptions { /** * Stringify an object into a query string, sorting the keys. */ -export function stringify(obj: object, options?: StringifyOptions): string; +export function stringify(obj: InputParams, options?: StringifyOptions): string; /** * Extract a query string from a URL that can be passed into .parse(). diff --git a/types/query-string/query-string-tests.ts b/types/query-string/query-string-tests.ts index 69c70655ed..33152ce445 100644 --- a/types/query-string/query-string-tests.ts +++ b/types/query-string/query-string-tests.ts @@ -19,20 +19,26 @@ import * as queryString from 'query-string'; result = queryString.stringify({ foo: 'bar' }, { strict: false, encode: false }); } +// For each section below, the second line ensures the real answer is of the declared +// type. You can find the real answer by running the first line of each section. + // parse { - let fooBar: { foo: 'bar' }; - fooBar = queryString.parse('?foo=bar'); - fooBar = queryString.parse('#foo=bar'); - fooBar = queryString.parse('?foo=bar%20baz', { decode: true }); + let fooBar = queryString.parse('?foo=bar'); + fooBar = {foo: "bar"}; - let fooBarBaz: { foo: ['bar', 'baz'] }; - fooBarBaz = queryString.parse('&foo=bar&foo=baz'); + let fooBarBaz1 = queryString.parse('&foo=bar&foo=baz'); + fooBarBaz1 = { foo: [ 'bar', 'baz' ] }; + + let fooBarBaz2 = queryString.parse('&foo[]=bar&foo[]=baz', {arrayFormat: 'bracket'}); + fooBarBaz2 = { foo: [ 'bar', 'baz' ] }; } // extract { - let result: string; - result = queryString.extract('http://foo.bar/?abc=def&hij=klm'); - result = queryString.extract('http://foo.bar/?foo=bar'); + let result1 = queryString.extract('http://foo.bar/?abc=def&hij=klm'); + result1 = 'abc=def&hij=klm'; + + let result2 = queryString.extract('http://foo.bar/?foo=bar'); + result2 = 'foo=bar'; } diff --git a/types/quill/index.d.ts b/types/quill/index.d.ts index 93c58da4b7..0b4de9932b 100644 --- a/types/quill/index.d.ts +++ b/types/quill/index.d.ts @@ -52,7 +52,7 @@ export interface ClipboardStatic { } export interface QuillOptionsStatic { - debug?: string; + debug?: string | boolean; modules?: StringMap; placeholder?: string; readOnly?: boolean; diff --git a/types/quill/quill-tests.ts b/types/quill/quill-tests.ts index fe4ebefaf2..b2dcfac727 100644 --- a/types/quill/quill-tests.ts +++ b/types/quill/quill-tests.ts @@ -12,6 +12,17 @@ function test_quill() { }); } +function test_quill_opts() { + const quillEditor = new Quill('#editor', { + modules: + { + toolbar: { container: "#toolbar" } + }, + theme: 'snow', + debug: true, + }); +} + function test_scroll() { const quillEditor = new Quill('#editor'); const blot: Blot = quillEditor.scroll; diff --git a/types/qunit/v1/tslint.json b/types/qunit/v1/tslint.json index a41bf5d19a..d67ffb3a73 100644 --- a/types/qunit/v1/tslint.json +++ b/types/qunit/v1/tslint.json @@ -17,6 +17,7 @@ "max-line-length": false, "member-access": false, "new-parens": false, + "no-angle-bracket-type-assertion": false, "no-any-union": false, "no-boolean-literal-compare": false, "no-conditional-assignment": 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/es/F.d.ts b/types/ramda/es/F.d.ts new file mode 100644 index 0000000000..bdc0d570d9 --- /dev/null +++ b/types/ramda/es/F.d.ts @@ -0,0 +1,2 @@ +import { F } from '../index'; +export default F; diff --git a/types/ramda/es/T.d.ts b/types/ramda/es/T.d.ts new file mode 100644 index 0000000000..634808e684 --- /dev/null +++ b/types/ramda/es/T.d.ts @@ -0,0 +1,2 @@ +import { T } from '../index'; +export default T; diff --git a/types/ramda/es/add.d.ts b/types/ramda/es/add.d.ts new file mode 100644 index 0000000000..b7b3ee887c --- /dev/null +++ b/types/ramda/es/add.d.ts @@ -0,0 +1,2 @@ +import { add } from '../index'; +export default add; diff --git a/types/ramda/es/addIndex.d.ts b/types/ramda/es/addIndex.d.ts new file mode 100644 index 0000000000..9f27967dcb --- /dev/null +++ b/types/ramda/es/addIndex.d.ts @@ -0,0 +1,2 @@ +import { addIndex } from '../index'; +export default addIndex; diff --git a/types/ramda/es/adjust.d.ts b/types/ramda/es/adjust.d.ts new file mode 100644 index 0000000000..22b65ec38e --- /dev/null +++ b/types/ramda/es/adjust.d.ts @@ -0,0 +1,2 @@ +import { adjust } from '../index'; +export default adjust; diff --git a/types/ramda/es/all.d.ts b/types/ramda/es/all.d.ts new file mode 100644 index 0000000000..a2f6d934f9 --- /dev/null +++ b/types/ramda/es/all.d.ts @@ -0,0 +1,2 @@ +import { all } from '../index'; +export default all; diff --git a/types/ramda/es/allPass.d.ts b/types/ramda/es/allPass.d.ts new file mode 100644 index 0000000000..d44ac20e9d --- /dev/null +++ b/types/ramda/es/allPass.d.ts @@ -0,0 +1,2 @@ +import { allPass } from '../index'; +export default allPass; diff --git a/types/ramda/es/always.d.ts b/types/ramda/es/always.d.ts new file mode 100644 index 0000000000..aadc94983b --- /dev/null +++ b/types/ramda/es/always.d.ts @@ -0,0 +1,2 @@ +import { always } from '../index'; +export default always; diff --git a/types/ramda/es/and.d.ts b/types/ramda/es/and.d.ts new file mode 100644 index 0000000000..3d505f6ec3 --- /dev/null +++ b/types/ramda/es/and.d.ts @@ -0,0 +1,2 @@ +import { and } from '../index'; +export default and; diff --git a/types/ramda/es/any.d.ts b/types/ramda/es/any.d.ts new file mode 100644 index 0000000000..1e77e505e9 --- /dev/null +++ b/types/ramda/es/any.d.ts @@ -0,0 +1,2 @@ +import { any } from '../index'; +export default any; diff --git a/types/ramda/es/anyPass.d.ts b/types/ramda/es/anyPass.d.ts new file mode 100644 index 0000000000..d8e7fc8f0d --- /dev/null +++ b/types/ramda/es/anyPass.d.ts @@ -0,0 +1,2 @@ +import { anyPass } from '../index'; +export default anyPass; diff --git a/types/ramda/es/ap.d.ts b/types/ramda/es/ap.d.ts new file mode 100644 index 0000000000..5bf98d7fbd --- /dev/null +++ b/types/ramda/es/ap.d.ts @@ -0,0 +1,2 @@ +import { ap } from '../index'; +export default ap; diff --git a/types/ramda/es/aperture.d.ts b/types/ramda/es/aperture.d.ts new file mode 100644 index 0000000000..7536b091b8 --- /dev/null +++ b/types/ramda/es/aperture.d.ts @@ -0,0 +1,2 @@ +import { aperture } from '../index'; +export default aperture; diff --git a/types/ramda/es/append.d.ts b/types/ramda/es/append.d.ts new file mode 100644 index 0000000000..88a4e7cde2 --- /dev/null +++ b/types/ramda/es/append.d.ts @@ -0,0 +1,2 @@ +import { append } from '../index'; +export default append; diff --git a/types/ramda/es/apply.d.ts b/types/ramda/es/apply.d.ts new file mode 100644 index 0000000000..53d90689ed --- /dev/null +++ b/types/ramda/es/apply.d.ts @@ -0,0 +1,2 @@ +import { apply } from '../index'; +export default apply; diff --git a/types/ramda/es/applySpec.d.ts b/types/ramda/es/applySpec.d.ts new file mode 100644 index 0000000000..57e5b8018c --- /dev/null +++ b/types/ramda/es/applySpec.d.ts @@ -0,0 +1,2 @@ +import { applySpec } from '../index'; +export default applySpec; diff --git a/types/ramda/es/applyTo.d.ts b/types/ramda/es/applyTo.d.ts new file mode 100644 index 0000000000..30869542db --- /dev/null +++ b/types/ramda/es/applyTo.d.ts @@ -0,0 +1,2 @@ +import { applyTo } from '../index'; +export default applyTo; diff --git a/types/ramda/es/ascend.d.ts b/types/ramda/es/ascend.d.ts new file mode 100644 index 0000000000..e4c4e1199b --- /dev/null +++ b/types/ramda/es/ascend.d.ts @@ -0,0 +1,2 @@ +import { ascend } from '../index'; +export default ascend; diff --git a/types/ramda/es/assoc.d.ts b/types/ramda/es/assoc.d.ts new file mode 100644 index 0000000000..5acc97a0aa --- /dev/null +++ b/types/ramda/es/assoc.d.ts @@ -0,0 +1,2 @@ +import { assoc } from '../index'; +export default assoc; diff --git a/types/ramda/es/assocPath.d.ts b/types/ramda/es/assocPath.d.ts new file mode 100644 index 0000000000..040671bf38 --- /dev/null +++ b/types/ramda/es/assocPath.d.ts @@ -0,0 +1,2 @@ +import { assocPath } from '../index'; +export default assocPath; diff --git a/types/ramda/es/binary.d.ts b/types/ramda/es/binary.d.ts new file mode 100644 index 0000000000..259cb96e82 --- /dev/null +++ b/types/ramda/es/binary.d.ts @@ -0,0 +1,2 @@ +import { binary } from '../index'; +export default binary; diff --git a/types/ramda/es/bind.d.ts b/types/ramda/es/bind.d.ts new file mode 100644 index 0000000000..fe108f09a7 --- /dev/null +++ b/types/ramda/es/bind.d.ts @@ -0,0 +1,2 @@ +import { bind } from '../index'; +export default bind; diff --git a/types/ramda/es/both.d.ts b/types/ramda/es/both.d.ts new file mode 100644 index 0000000000..8061154cdd --- /dev/null +++ b/types/ramda/es/both.d.ts @@ -0,0 +1,2 @@ +import { both } from '../index'; +export default both; diff --git a/types/ramda/es/call.d.ts b/types/ramda/es/call.d.ts new file mode 100644 index 0000000000..35b6fda88c --- /dev/null +++ b/types/ramda/es/call.d.ts @@ -0,0 +1,2 @@ +import { call } from '../index'; +export default call; diff --git a/types/ramda/es/chain.d.ts b/types/ramda/es/chain.d.ts new file mode 100644 index 0000000000..53aafe210a --- /dev/null +++ b/types/ramda/es/chain.d.ts @@ -0,0 +1,2 @@ +import { chain } from '../index'; +export default chain; diff --git a/types/ramda/es/clamp.d.ts b/types/ramda/es/clamp.d.ts new file mode 100644 index 0000000000..1376643cbf --- /dev/null +++ b/types/ramda/es/clamp.d.ts @@ -0,0 +1,2 @@ +import { clamp } from '../index'; +export default clamp; diff --git a/types/ramda/es/clone.d.ts b/types/ramda/es/clone.d.ts new file mode 100644 index 0000000000..b95f842554 --- /dev/null +++ b/types/ramda/es/clone.d.ts @@ -0,0 +1,2 @@ +import { clone } from '../index'; +export default clone; diff --git a/types/ramda/es/comparator.d.ts b/types/ramda/es/comparator.d.ts new file mode 100644 index 0000000000..34023dea00 --- /dev/null +++ b/types/ramda/es/comparator.d.ts @@ -0,0 +1,2 @@ +import { comparator } from '../index'; +export default comparator; diff --git a/types/ramda/es/complement.d.ts b/types/ramda/es/complement.d.ts new file mode 100644 index 0000000000..b5d31fee50 --- /dev/null +++ b/types/ramda/es/complement.d.ts @@ -0,0 +1,2 @@ +import { complement } from '../index'; +export default complement; diff --git a/types/ramda/es/compose.d.ts b/types/ramda/es/compose.d.ts new file mode 100644 index 0000000000..dca4578840 --- /dev/null +++ b/types/ramda/es/compose.d.ts @@ -0,0 +1,2 @@ +import { compose } from '../index'; +export default compose; diff --git a/types/ramda/es/composeK.d.ts b/types/ramda/es/composeK.d.ts new file mode 100644 index 0000000000..646005a0b6 --- /dev/null +++ b/types/ramda/es/composeK.d.ts @@ -0,0 +1,2 @@ +import { composeK } from '../index'; +export default composeK; diff --git a/types/ramda/es/composeP.d.ts b/types/ramda/es/composeP.d.ts new file mode 100644 index 0000000000..ca0a96fb25 --- /dev/null +++ b/types/ramda/es/composeP.d.ts @@ -0,0 +1,2 @@ +import { composeP } from '../index'; +export default composeP; diff --git a/types/ramda/es/concat.d.ts b/types/ramda/es/concat.d.ts new file mode 100644 index 0000000000..9ae333cf95 --- /dev/null +++ b/types/ramda/es/concat.d.ts @@ -0,0 +1,2 @@ +import { concat } from '../index'; +export default concat; diff --git a/types/ramda/es/cond.d.ts b/types/ramda/es/cond.d.ts new file mode 100644 index 0000000000..0ab4930b0e --- /dev/null +++ b/types/ramda/es/cond.d.ts @@ -0,0 +1,2 @@ +import { cond } from '../index'; +export default cond; diff --git a/types/ramda/es/construct.d.ts b/types/ramda/es/construct.d.ts new file mode 100644 index 0000000000..736871cb61 --- /dev/null +++ b/types/ramda/es/construct.d.ts @@ -0,0 +1,2 @@ +import { construct } from '../index'; +export default construct; diff --git a/types/ramda/es/constructN.d.ts b/types/ramda/es/constructN.d.ts new file mode 100644 index 0000000000..d9efc76cf3 --- /dev/null +++ b/types/ramda/es/constructN.d.ts @@ -0,0 +1,2 @@ +import { constructN } from '../index'; +export default constructN; diff --git a/types/ramda/es/contains.d.ts b/types/ramda/es/contains.d.ts new file mode 100644 index 0000000000..d193bc6109 --- /dev/null +++ b/types/ramda/es/contains.d.ts @@ -0,0 +1,2 @@ +import { contains } from '../index'; +export default contains; diff --git a/types/ramda/es/converge.d.ts b/types/ramda/es/converge.d.ts new file mode 100644 index 0000000000..181c0bd7e9 --- /dev/null +++ b/types/ramda/es/converge.d.ts @@ -0,0 +1,2 @@ +import { converge } from '../index'; +export default converge; diff --git a/types/ramda/es/countBy.d.ts b/types/ramda/es/countBy.d.ts new file mode 100644 index 0000000000..03d46e23f0 --- /dev/null +++ b/types/ramda/es/countBy.d.ts @@ -0,0 +1,2 @@ +import { countBy } from '../index'; +export default countBy; diff --git a/types/ramda/es/curry.d.ts b/types/ramda/es/curry.d.ts new file mode 100644 index 0000000000..0d94abf560 --- /dev/null +++ b/types/ramda/es/curry.d.ts @@ -0,0 +1,2 @@ +import { curry } from '../index'; +export default curry; diff --git a/types/ramda/es/curryN.d.ts b/types/ramda/es/curryN.d.ts new file mode 100644 index 0000000000..dca634c3b8 --- /dev/null +++ b/types/ramda/es/curryN.d.ts @@ -0,0 +1,2 @@ +import { curryN } from '../index'; +export default curryN; diff --git a/types/ramda/es/dec.d.ts b/types/ramda/es/dec.d.ts new file mode 100644 index 0000000000..605681f0d8 --- /dev/null +++ b/types/ramda/es/dec.d.ts @@ -0,0 +1,2 @@ +import { dec } from '../index'; +export default dec; diff --git a/types/ramda/es/defaultTo.d.ts b/types/ramda/es/defaultTo.d.ts new file mode 100644 index 0000000000..9c61199544 --- /dev/null +++ b/types/ramda/es/defaultTo.d.ts @@ -0,0 +1,2 @@ +import { defaultTo } from '../index'; +export default defaultTo; diff --git a/types/ramda/es/descend.d.ts b/types/ramda/es/descend.d.ts new file mode 100644 index 0000000000..d0ff2b6d54 --- /dev/null +++ b/types/ramda/es/descend.d.ts @@ -0,0 +1,2 @@ +import { descend } from '../index'; +export default descend; diff --git a/types/ramda/es/difference.d.ts b/types/ramda/es/difference.d.ts new file mode 100644 index 0000000000..1ef0096735 --- /dev/null +++ b/types/ramda/es/difference.d.ts @@ -0,0 +1,2 @@ +import { difference } from '../index'; +export default difference; diff --git a/types/ramda/es/differenceWith.d.ts b/types/ramda/es/differenceWith.d.ts new file mode 100644 index 0000000000..5a2366f6e0 --- /dev/null +++ b/types/ramda/es/differenceWith.d.ts @@ -0,0 +1,2 @@ +import { differenceWith } from '../index'; +export default differenceWith; diff --git a/types/ramda/es/dissoc.d.ts b/types/ramda/es/dissoc.d.ts new file mode 100644 index 0000000000..0ed3e2def9 --- /dev/null +++ b/types/ramda/es/dissoc.d.ts @@ -0,0 +1,2 @@ +import { dissoc } from '../index'; +export default dissoc; diff --git a/types/ramda/es/dissocPath.d.ts b/types/ramda/es/dissocPath.d.ts new file mode 100644 index 0000000000..83c705d80f --- /dev/null +++ b/types/ramda/es/dissocPath.d.ts @@ -0,0 +1,2 @@ +import { dissocPath } from '../index'; +export default dissocPath; diff --git a/types/ramda/es/divide.d.ts b/types/ramda/es/divide.d.ts new file mode 100644 index 0000000000..45c27a4d21 --- /dev/null +++ b/types/ramda/es/divide.d.ts @@ -0,0 +1,2 @@ +import { divide } from '../index'; +export default divide; diff --git a/types/ramda/es/drop.d.ts b/types/ramda/es/drop.d.ts new file mode 100644 index 0000000000..fb89bef7f0 --- /dev/null +++ b/types/ramda/es/drop.d.ts @@ -0,0 +1,2 @@ +import { drop } from '../index'; +export default drop; diff --git a/types/ramda/es/dropLast.d.ts b/types/ramda/es/dropLast.d.ts new file mode 100644 index 0000000000..2402f890f1 --- /dev/null +++ b/types/ramda/es/dropLast.d.ts @@ -0,0 +1,2 @@ +import { dropLast } from '../index'; +export default dropLast; diff --git a/types/ramda/es/dropLastWhile.d.ts b/types/ramda/es/dropLastWhile.d.ts new file mode 100644 index 0000000000..82950dd98b --- /dev/null +++ b/types/ramda/es/dropLastWhile.d.ts @@ -0,0 +1,2 @@ +import { dropLastWhile } from '../index'; +export default dropLastWhile; diff --git a/types/ramda/es/either.d.ts b/types/ramda/es/either.d.ts new file mode 100644 index 0000000000..130f0c4e7f --- /dev/null +++ b/types/ramda/es/either.d.ts @@ -0,0 +1,2 @@ +import { either } from '../index'; +export default either; diff --git a/types/ramda/es/empty.d.ts b/types/ramda/es/empty.d.ts new file mode 100644 index 0000000000..2cb6e8fade --- /dev/null +++ b/types/ramda/es/empty.d.ts @@ -0,0 +1,2 @@ +import { empty } from '../index'; +export default empty; diff --git a/types/ramda/es/endsWith.d.ts b/types/ramda/es/endsWith.d.ts new file mode 100644 index 0000000000..f23a961bbc --- /dev/null +++ b/types/ramda/es/endsWith.d.ts @@ -0,0 +1,2 @@ +import { endsWith } from '../index'; +export default endsWith; diff --git a/types/ramda/es/eqBy.d.ts b/types/ramda/es/eqBy.d.ts new file mode 100644 index 0000000000..3ed508587a --- /dev/null +++ b/types/ramda/es/eqBy.d.ts @@ -0,0 +1,2 @@ +import { eqBy } from '../index'; +export default eqBy; diff --git a/types/ramda/es/eqProps.d.ts b/types/ramda/es/eqProps.d.ts new file mode 100644 index 0000000000..e33b163311 --- /dev/null +++ b/types/ramda/es/eqProps.d.ts @@ -0,0 +1,2 @@ +import { eqProps } from '../index'; +export default eqProps; diff --git a/types/ramda/es/equals.d.ts b/types/ramda/es/equals.d.ts new file mode 100644 index 0000000000..6d4c8050e1 --- /dev/null +++ b/types/ramda/es/equals.d.ts @@ -0,0 +1,2 @@ +import { equals } from '../index'; +export default equals; diff --git a/types/ramda/es/evolve.d.ts b/types/ramda/es/evolve.d.ts new file mode 100644 index 0000000000..21ec9896a3 --- /dev/null +++ b/types/ramda/es/evolve.d.ts @@ -0,0 +1,2 @@ +import { evolve } from '../index'; +export default evolve; diff --git a/types/ramda/es/filter.d.ts b/types/ramda/es/filter.d.ts new file mode 100644 index 0000000000..a4f7133638 --- /dev/null +++ b/types/ramda/es/filter.d.ts @@ -0,0 +1,2 @@ +import { filter } from '../index'; +export default filter; diff --git a/types/ramda/es/find.d.ts b/types/ramda/es/find.d.ts new file mode 100644 index 0000000000..a8c2905bed --- /dev/null +++ b/types/ramda/es/find.d.ts @@ -0,0 +1,2 @@ +import { find } from '../index'; +export default find; diff --git a/types/ramda/es/findIndex.d.ts b/types/ramda/es/findIndex.d.ts new file mode 100644 index 0000000000..88c14e28fc --- /dev/null +++ b/types/ramda/es/findIndex.d.ts @@ -0,0 +1,2 @@ +import { findIndex } from '../index'; +export default findIndex; diff --git a/types/ramda/es/findLast.d.ts b/types/ramda/es/findLast.d.ts new file mode 100644 index 0000000000..3d8ad5c7fa --- /dev/null +++ b/types/ramda/es/findLast.d.ts @@ -0,0 +1,2 @@ +import { findLast } from '../index'; +export default findLast; diff --git a/types/ramda/es/findLastIndex.d.ts b/types/ramda/es/findLastIndex.d.ts new file mode 100644 index 0000000000..ae1edaeb14 --- /dev/null +++ b/types/ramda/es/findLastIndex.d.ts @@ -0,0 +1,2 @@ +import { findLastIndex } from '../index'; +export default findLastIndex; diff --git a/types/ramda/es/flatten.d.ts b/types/ramda/es/flatten.d.ts new file mode 100644 index 0000000000..75a19402dc --- /dev/null +++ b/types/ramda/es/flatten.d.ts @@ -0,0 +1,2 @@ +import { flatten } from '../index'; +export default flatten; diff --git a/types/ramda/es/flip.d.ts b/types/ramda/es/flip.d.ts new file mode 100644 index 0000000000..164e607f33 --- /dev/null +++ b/types/ramda/es/flip.d.ts @@ -0,0 +1,2 @@ +import { flip } from '../index'; +export default flip; diff --git a/types/ramda/es/forEach.d.ts b/types/ramda/es/forEach.d.ts new file mode 100644 index 0000000000..c5f7a57837 --- /dev/null +++ b/types/ramda/es/forEach.d.ts @@ -0,0 +1,2 @@ +import { forEach } from '../index'; +export default forEach; diff --git a/types/ramda/es/forEachObjIndexed.d.ts b/types/ramda/es/forEachObjIndexed.d.ts new file mode 100644 index 0000000000..a098026381 --- /dev/null +++ b/types/ramda/es/forEachObjIndexed.d.ts @@ -0,0 +1,2 @@ +import { forEachObjIndexed } from '../index'; +export default forEachObjIndexed; diff --git a/types/ramda/es/fromPairs.d.ts b/types/ramda/es/fromPairs.d.ts new file mode 100644 index 0000000000..0cb1778350 --- /dev/null +++ b/types/ramda/es/fromPairs.d.ts @@ -0,0 +1,2 @@ +import { fromPairs } from '../index'; +export default fromPairs; diff --git a/types/ramda/es/groupBy.d.ts b/types/ramda/es/groupBy.d.ts new file mode 100644 index 0000000000..af2b32083b --- /dev/null +++ b/types/ramda/es/groupBy.d.ts @@ -0,0 +1,2 @@ +import { groupBy } from '../index'; +export default groupBy; diff --git a/types/ramda/es/groupWith.d.ts b/types/ramda/es/groupWith.d.ts new file mode 100644 index 0000000000..f9dca6c16b --- /dev/null +++ b/types/ramda/es/groupWith.d.ts @@ -0,0 +1,2 @@ +import { groupWith } from '../index'; +export default groupWith; diff --git a/types/ramda/es/gt.d.ts b/types/ramda/es/gt.d.ts new file mode 100644 index 0000000000..4cdb70d336 --- /dev/null +++ b/types/ramda/es/gt.d.ts @@ -0,0 +1,2 @@ +import { gt } from '../index'; +export default gt; diff --git a/types/ramda/es/gte.d.ts b/types/ramda/es/gte.d.ts new file mode 100644 index 0000000000..2b878eabc6 --- /dev/null +++ b/types/ramda/es/gte.d.ts @@ -0,0 +1,2 @@ +import { gte } from '../index'; +export default gte; diff --git a/types/ramda/es/has.d.ts b/types/ramda/es/has.d.ts new file mode 100644 index 0000000000..88c79bfdb0 --- /dev/null +++ b/types/ramda/es/has.d.ts @@ -0,0 +1,2 @@ +import { has } from '../index'; +export default has; diff --git a/types/ramda/es/hasIn.d.ts b/types/ramda/es/hasIn.d.ts new file mode 100644 index 0000000000..4cad709e64 --- /dev/null +++ b/types/ramda/es/hasIn.d.ts @@ -0,0 +1,2 @@ +import { hasIn } from '../index'; +export default hasIn; diff --git a/types/ramda/es/head.d.ts b/types/ramda/es/head.d.ts new file mode 100644 index 0000000000..bb1f3dd7b9 --- /dev/null +++ b/types/ramda/es/head.d.ts @@ -0,0 +1,2 @@ +import { head } from '../index'; +export default head; diff --git a/types/ramda/es/identical.d.ts b/types/ramda/es/identical.d.ts new file mode 100644 index 0000000000..6f2ccf4f94 --- /dev/null +++ b/types/ramda/es/identical.d.ts @@ -0,0 +1,2 @@ +import { identical } from '../index'; +export default identical; diff --git a/types/ramda/es/identity.d.ts b/types/ramda/es/identity.d.ts new file mode 100644 index 0000000000..ba0936116e --- /dev/null +++ b/types/ramda/es/identity.d.ts @@ -0,0 +1,2 @@ +import { identity } from '../index'; +export default identity; diff --git a/types/ramda/es/ifElse.d.ts b/types/ramda/es/ifElse.d.ts new file mode 100644 index 0000000000..46674829d7 --- /dev/null +++ b/types/ramda/es/ifElse.d.ts @@ -0,0 +1,2 @@ +import { ifElse } from '../index'; +export default ifElse; diff --git a/types/ramda/es/inc.d.ts b/types/ramda/es/inc.d.ts new file mode 100644 index 0000000000..c173b2dd8e --- /dev/null +++ b/types/ramda/es/inc.d.ts @@ -0,0 +1,2 @@ +import { inc } from '../index'; +export default inc; diff --git a/types/ramda/es/indexBy.d.ts b/types/ramda/es/indexBy.d.ts new file mode 100644 index 0000000000..93b29ec7cd --- /dev/null +++ b/types/ramda/es/indexBy.d.ts @@ -0,0 +1,2 @@ +import { indexBy } from '../index'; +export default indexBy; diff --git a/types/ramda/es/indexOf.d.ts b/types/ramda/es/indexOf.d.ts new file mode 100644 index 0000000000..22aa4b44db --- /dev/null +++ b/types/ramda/es/indexOf.d.ts @@ -0,0 +1,2 @@ +import { indexOf } from '../index'; +export default indexOf; diff --git a/types/ramda/es/init.d.ts b/types/ramda/es/init.d.ts new file mode 100644 index 0000000000..03849db7b0 --- /dev/null +++ b/types/ramda/es/init.d.ts @@ -0,0 +1,2 @@ +import { init } from '../index'; +export default init; diff --git a/types/ramda/es/insert.d.ts b/types/ramda/es/insert.d.ts new file mode 100644 index 0000000000..3fdde857fa --- /dev/null +++ b/types/ramda/es/insert.d.ts @@ -0,0 +1,2 @@ +import { insert } from '../index'; +export default insert; diff --git a/types/ramda/es/insertAll.d.ts b/types/ramda/es/insertAll.d.ts new file mode 100644 index 0000000000..a9fd784995 --- /dev/null +++ b/types/ramda/es/insertAll.d.ts @@ -0,0 +1,2 @@ +import { insertAll } from '../index'; +export default insertAll; diff --git a/types/ramda/es/intersection.d.ts b/types/ramda/es/intersection.d.ts new file mode 100644 index 0000000000..1ec1aadbe4 --- /dev/null +++ b/types/ramda/es/intersection.d.ts @@ -0,0 +1,2 @@ +import { intersection } from '../index'; +export default intersection; diff --git a/types/ramda/es/intersectionWith.d.ts b/types/ramda/es/intersectionWith.d.ts new file mode 100644 index 0000000000..773c36acbe --- /dev/null +++ b/types/ramda/es/intersectionWith.d.ts @@ -0,0 +1,2 @@ +import { intersectionWith } from '../index'; +export default intersectionWith; diff --git a/types/ramda/es/intersperse.d.ts b/types/ramda/es/intersperse.d.ts new file mode 100644 index 0000000000..b4420de34a --- /dev/null +++ b/types/ramda/es/intersperse.d.ts @@ -0,0 +1,2 @@ +import { intersperse } from '../index'; +export default intersperse; diff --git a/types/ramda/es/into.d.ts b/types/ramda/es/into.d.ts new file mode 100644 index 0000000000..3daa53afdd --- /dev/null +++ b/types/ramda/es/into.d.ts @@ -0,0 +1,2 @@ +import { into } from '../index'; +export default into; diff --git a/types/ramda/es/invert.d.ts b/types/ramda/es/invert.d.ts new file mode 100644 index 0000000000..825773f5dc --- /dev/null +++ b/types/ramda/es/invert.d.ts @@ -0,0 +1,2 @@ +import { invert } from '../index'; +export default invert; diff --git a/types/ramda/es/invertObj.d.ts b/types/ramda/es/invertObj.d.ts new file mode 100644 index 0000000000..8fd0f1fe7d --- /dev/null +++ b/types/ramda/es/invertObj.d.ts @@ -0,0 +1,2 @@ +import { invertObj } from '../index'; +export default invertObj; diff --git a/types/ramda/es/invoker.d.ts b/types/ramda/es/invoker.d.ts new file mode 100644 index 0000000000..1930a78917 --- /dev/null +++ b/types/ramda/es/invoker.d.ts @@ -0,0 +1,2 @@ +import { invoker } from '../index'; +export default invoker; diff --git a/types/ramda/es/is.d.ts b/types/ramda/es/is.d.ts new file mode 100644 index 0000000000..262d14160d --- /dev/null +++ b/types/ramda/es/is.d.ts @@ -0,0 +1,2 @@ +import { is } from '../index'; +export default is; diff --git a/types/ramda/es/isArrayLike.d.ts b/types/ramda/es/isArrayLike.d.ts new file mode 100644 index 0000000000..04aa464805 --- /dev/null +++ b/types/ramda/es/isArrayLike.d.ts @@ -0,0 +1,2 @@ +import { isArrayLike } from '../index'; +export default isArrayLike; diff --git a/types/ramda/es/isEmpty.d.ts b/types/ramda/es/isEmpty.d.ts new file mode 100644 index 0000000000..bea7bb8d08 --- /dev/null +++ b/types/ramda/es/isEmpty.d.ts @@ -0,0 +1,2 @@ +import { isEmpty } from '../index'; +export default isEmpty; diff --git a/types/ramda/es/isNaN.d.ts b/types/ramda/es/isNaN.d.ts new file mode 100644 index 0000000000..5dbe28177a --- /dev/null +++ b/types/ramda/es/isNaN.d.ts @@ -0,0 +1,2 @@ +import { isNaN } from '../index'; +export default isNaN; diff --git a/types/ramda/es/isNil.d.ts b/types/ramda/es/isNil.d.ts new file mode 100644 index 0000000000..bce78e7c70 --- /dev/null +++ b/types/ramda/es/isNil.d.ts @@ -0,0 +1,2 @@ +import { isNil } from '../index'; +export default isNil; diff --git a/types/ramda/es/join.d.ts b/types/ramda/es/join.d.ts new file mode 100644 index 0000000000..7505b7e769 --- /dev/null +++ b/types/ramda/es/join.d.ts @@ -0,0 +1,2 @@ +import { join } from '../index'; +export default join; diff --git a/types/ramda/es/juxt.d.ts b/types/ramda/es/juxt.d.ts new file mode 100644 index 0000000000..23e342f53d --- /dev/null +++ b/types/ramda/es/juxt.d.ts @@ -0,0 +1,2 @@ +import { juxt } from '../index'; +export default juxt; diff --git a/types/ramda/es/keys.d.ts b/types/ramda/es/keys.d.ts new file mode 100644 index 0000000000..b44e894b7a --- /dev/null +++ b/types/ramda/es/keys.d.ts @@ -0,0 +1,2 @@ +import { keys } from '../index'; +export default keys; diff --git a/types/ramda/es/keysIn.d.ts b/types/ramda/es/keysIn.d.ts new file mode 100644 index 0000000000..a54fb92a6d --- /dev/null +++ b/types/ramda/es/keysIn.d.ts @@ -0,0 +1,2 @@ +import { keysIn } from '../index'; +export default keysIn; diff --git a/types/ramda/es/last.d.ts b/types/ramda/es/last.d.ts new file mode 100644 index 0000000000..f8ea740735 --- /dev/null +++ b/types/ramda/es/last.d.ts @@ -0,0 +1,2 @@ +import { last } from '../index'; +export default last; diff --git a/types/ramda/es/lastIndexOf.d.ts b/types/ramda/es/lastIndexOf.d.ts new file mode 100644 index 0000000000..c34fe55a03 --- /dev/null +++ b/types/ramda/es/lastIndexOf.d.ts @@ -0,0 +1,2 @@ +import { lastIndexOf } from '../index'; +export default lastIndexOf; diff --git a/types/ramda/es/length.d.ts b/types/ramda/es/length.d.ts new file mode 100644 index 0000000000..7ef1d90dd5 --- /dev/null +++ b/types/ramda/es/length.d.ts @@ -0,0 +1,2 @@ +import { length } from '../index'; +export default length; diff --git a/types/ramda/es/lens.d.ts b/types/ramda/es/lens.d.ts new file mode 100644 index 0000000000..03688e0c4f --- /dev/null +++ b/types/ramda/es/lens.d.ts @@ -0,0 +1,2 @@ +import { lens } from '../index'; +export default lens; diff --git a/types/ramda/es/lensIndex.d.ts b/types/ramda/es/lensIndex.d.ts new file mode 100644 index 0000000000..d85cd88c2f --- /dev/null +++ b/types/ramda/es/lensIndex.d.ts @@ -0,0 +1,2 @@ +import { lensIndex } from '../index'; +export default lensIndex; diff --git a/types/ramda/es/lensPath.d.ts b/types/ramda/es/lensPath.d.ts new file mode 100644 index 0000000000..67b60fbf3c --- /dev/null +++ b/types/ramda/es/lensPath.d.ts @@ -0,0 +1,2 @@ +import { lensPath } from '../index'; +export default lensPath; diff --git a/types/ramda/es/lensProp.d.ts b/types/ramda/es/lensProp.d.ts new file mode 100644 index 0000000000..fc8db9e32d --- /dev/null +++ b/types/ramda/es/lensProp.d.ts @@ -0,0 +1,2 @@ +import { lensProp } from '../index'; +export default lensProp; diff --git a/types/ramda/es/lift.d.ts b/types/ramda/es/lift.d.ts new file mode 100644 index 0000000000..73e4cba184 --- /dev/null +++ b/types/ramda/es/lift.d.ts @@ -0,0 +1,2 @@ +import { lift } from '../index'; +export default lift; diff --git a/types/ramda/es/lt.d.ts b/types/ramda/es/lt.d.ts new file mode 100644 index 0000000000..71360d1c43 --- /dev/null +++ b/types/ramda/es/lt.d.ts @@ -0,0 +1,2 @@ +import { lt } from '../index'; +export default lt; diff --git a/types/ramda/es/lte.d.ts b/types/ramda/es/lte.d.ts new file mode 100644 index 0000000000..980ef22037 --- /dev/null +++ b/types/ramda/es/lte.d.ts @@ -0,0 +1,2 @@ +import { lte } from '../index'; +export default lte; diff --git a/types/ramda/es/map.d.ts b/types/ramda/es/map.d.ts new file mode 100644 index 0000000000..6883cb62f6 --- /dev/null +++ b/types/ramda/es/map.d.ts @@ -0,0 +1,2 @@ +import { map } from '../index'; +export default map; diff --git a/types/ramda/es/mapAccum.d.ts b/types/ramda/es/mapAccum.d.ts new file mode 100644 index 0000000000..356c715787 --- /dev/null +++ b/types/ramda/es/mapAccum.d.ts @@ -0,0 +1,2 @@ +import { mapAccum } from '../index'; +export default mapAccum; diff --git a/types/ramda/es/mapAccumRight.d.ts b/types/ramda/es/mapAccumRight.d.ts new file mode 100644 index 0000000000..817e73bb97 --- /dev/null +++ b/types/ramda/es/mapAccumRight.d.ts @@ -0,0 +1,2 @@ +import { mapAccumRight } from '../index'; +export default mapAccumRight; diff --git a/types/ramda/es/mapObjIndexed.d.ts b/types/ramda/es/mapObjIndexed.d.ts new file mode 100644 index 0000000000..3ef1eca52d --- /dev/null +++ b/types/ramda/es/mapObjIndexed.d.ts @@ -0,0 +1,2 @@ +import { mapObjIndexed } from '../index'; +export default mapObjIndexed; diff --git a/types/ramda/es/match.d.ts b/types/ramda/es/match.d.ts new file mode 100644 index 0000000000..a24f0bd6d0 --- /dev/null +++ b/types/ramda/es/match.d.ts @@ -0,0 +1,2 @@ +import { match } from '../index'; +export default match; diff --git a/types/ramda/es/mathMod.d.ts b/types/ramda/es/mathMod.d.ts new file mode 100644 index 0000000000..0b0205c822 --- /dev/null +++ b/types/ramda/es/mathMod.d.ts @@ -0,0 +1,2 @@ +import { mathMod } from '../index'; +export default mathMod; diff --git a/types/ramda/es/max.d.ts b/types/ramda/es/max.d.ts new file mode 100644 index 0000000000..fcb09338c0 --- /dev/null +++ b/types/ramda/es/max.d.ts @@ -0,0 +1,2 @@ +import { max } from '../index'; +export default max; diff --git a/types/ramda/es/maxBy.d.ts b/types/ramda/es/maxBy.d.ts new file mode 100644 index 0000000000..4d00e7e572 --- /dev/null +++ b/types/ramda/es/maxBy.d.ts @@ -0,0 +1,2 @@ +import { maxBy } from '../index'; +export default maxBy; diff --git a/types/ramda/es/mean.d.ts b/types/ramda/es/mean.d.ts new file mode 100644 index 0000000000..8babcc3374 --- /dev/null +++ b/types/ramda/es/mean.d.ts @@ -0,0 +1,2 @@ +import { mean } from '../index'; +export default mean; diff --git a/types/ramda/es/median.d.ts b/types/ramda/es/median.d.ts new file mode 100644 index 0000000000..f7386692ff --- /dev/null +++ b/types/ramda/es/median.d.ts @@ -0,0 +1,2 @@ +import { median } from '../index'; +export default median; diff --git a/types/ramda/es/memoize.d.ts b/types/ramda/es/memoize.d.ts new file mode 100644 index 0000000000..a32d4d0016 --- /dev/null +++ b/types/ramda/es/memoize.d.ts @@ -0,0 +1,2 @@ +import { memoize } from '../index'; +export default memoize; diff --git a/types/ramda/es/memoizeWith.d.ts b/types/ramda/es/memoizeWith.d.ts new file mode 100644 index 0000000000..8eb2abd416 --- /dev/null +++ b/types/ramda/es/memoizeWith.d.ts @@ -0,0 +1,2 @@ +import { memoizeWith } from '../index'; +export default memoizeWith; diff --git a/types/ramda/es/merge.d.ts b/types/ramda/es/merge.d.ts new file mode 100644 index 0000000000..9786c2b611 --- /dev/null +++ b/types/ramda/es/merge.d.ts @@ -0,0 +1,2 @@ +import { merge } from '../index'; +export default merge; diff --git a/types/ramda/es/mergeAll.d.ts b/types/ramda/es/mergeAll.d.ts new file mode 100644 index 0000000000..8bb141f82f --- /dev/null +++ b/types/ramda/es/mergeAll.d.ts @@ -0,0 +1,2 @@ +import { mergeAll } from '../index'; +export default mergeAll; diff --git a/types/ramda/es/mergeDeepLeft.d.ts b/types/ramda/es/mergeDeepLeft.d.ts new file mode 100644 index 0000000000..332df578d3 --- /dev/null +++ b/types/ramda/es/mergeDeepLeft.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepLeft } from '../index'; +export default mergeDeepLeft; diff --git a/types/ramda/es/mergeDeepRight.d.ts b/types/ramda/es/mergeDeepRight.d.ts new file mode 100644 index 0000000000..c589924ca5 --- /dev/null +++ b/types/ramda/es/mergeDeepRight.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepRight } from '../index'; +export default mergeDeepRight; diff --git a/types/ramda/es/mergeDeepWith.d.ts b/types/ramda/es/mergeDeepWith.d.ts new file mode 100644 index 0000000000..cd5523b224 --- /dev/null +++ b/types/ramda/es/mergeDeepWith.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepWith } from '../index'; +export default mergeDeepWith; diff --git a/types/ramda/es/mergeDeepWithKey.d.ts b/types/ramda/es/mergeDeepWithKey.d.ts new file mode 100644 index 0000000000..70f6ace1db --- /dev/null +++ b/types/ramda/es/mergeDeepWithKey.d.ts @@ -0,0 +1,2 @@ +import { mergeDeepWithKey } from '../index'; +export default mergeDeepWithKey; diff --git a/types/ramda/es/mergeWith.d.ts b/types/ramda/es/mergeWith.d.ts new file mode 100644 index 0000000000..0270c71977 --- /dev/null +++ b/types/ramda/es/mergeWith.d.ts @@ -0,0 +1,2 @@ +import { mergeWith } from '../index'; +export default mergeWith; diff --git a/types/ramda/es/mergeWithKey.d.ts b/types/ramda/es/mergeWithKey.d.ts new file mode 100644 index 0000000000..b32e625cfc --- /dev/null +++ b/types/ramda/es/mergeWithKey.d.ts @@ -0,0 +1,2 @@ +import { mergeWithKey } from '../index'; +export default mergeWithKey; diff --git a/types/ramda/es/min.d.ts b/types/ramda/es/min.d.ts new file mode 100644 index 0000000000..af0dca8faa --- /dev/null +++ b/types/ramda/es/min.d.ts @@ -0,0 +1,2 @@ +import { min } from '../index'; +export default min; diff --git a/types/ramda/es/minBy.d.ts b/types/ramda/es/minBy.d.ts new file mode 100644 index 0000000000..14377eea93 --- /dev/null +++ b/types/ramda/es/minBy.d.ts @@ -0,0 +1,2 @@ +import { minBy } from '../index'; +export default minBy; diff --git a/types/ramda/es/modulo.d.ts b/types/ramda/es/modulo.d.ts new file mode 100644 index 0000000000..4c32f3ce8f --- /dev/null +++ b/types/ramda/es/modulo.d.ts @@ -0,0 +1,2 @@ +import { modulo } from '../index'; +export default modulo; diff --git a/types/ramda/es/multiply.d.ts b/types/ramda/es/multiply.d.ts new file mode 100644 index 0000000000..56d3a59380 --- /dev/null +++ b/types/ramda/es/multiply.d.ts @@ -0,0 +1,2 @@ +import { multiply } from '../index'; +export default multiply; diff --git a/types/ramda/es/nAry.d.ts b/types/ramda/es/nAry.d.ts new file mode 100644 index 0000000000..a9bce85047 --- /dev/null +++ b/types/ramda/es/nAry.d.ts @@ -0,0 +1,2 @@ +import { nAry } from '../index'; +export default nAry; diff --git a/types/ramda/es/negate.d.ts b/types/ramda/es/negate.d.ts new file mode 100644 index 0000000000..8410d94a22 --- /dev/null +++ b/types/ramda/es/negate.d.ts @@ -0,0 +1,2 @@ +import { negate } from '../index'; +export default negate; diff --git a/types/ramda/es/none.d.ts b/types/ramda/es/none.d.ts new file mode 100644 index 0000000000..6c545e7261 --- /dev/null +++ b/types/ramda/es/none.d.ts @@ -0,0 +1,2 @@ +import { none } from '../index'; +export default none; diff --git a/types/ramda/es/not.d.ts b/types/ramda/es/not.d.ts new file mode 100644 index 0000000000..10c4c56cfc --- /dev/null +++ b/types/ramda/es/not.d.ts @@ -0,0 +1,2 @@ +import { not } from '../index'; +export default not; diff --git a/types/ramda/es/nth.d.ts b/types/ramda/es/nth.d.ts new file mode 100644 index 0000000000..b5cef1993a --- /dev/null +++ b/types/ramda/es/nth.d.ts @@ -0,0 +1,2 @@ +import { nth } from '../index'; +export default nth; diff --git a/types/ramda/es/nthArg.d.ts b/types/ramda/es/nthArg.d.ts new file mode 100644 index 0000000000..5d61bb24f6 --- /dev/null +++ b/types/ramda/es/nthArg.d.ts @@ -0,0 +1,2 @@ +import { nthArg } from '../index'; +export default nthArg; diff --git a/types/ramda/es/objOf.d.ts b/types/ramda/es/objOf.d.ts new file mode 100644 index 0000000000..0a2b7c3075 --- /dev/null +++ b/types/ramda/es/objOf.d.ts @@ -0,0 +1,2 @@ +import { objOf } from '../index'; +export default objOf; diff --git a/types/ramda/es/of.d.ts b/types/ramda/es/of.d.ts new file mode 100644 index 0000000000..252569b5e6 --- /dev/null +++ b/types/ramda/es/of.d.ts @@ -0,0 +1,2 @@ +import { of } from '../index'; +export default of; diff --git a/types/ramda/es/omit.d.ts b/types/ramda/es/omit.d.ts new file mode 100644 index 0000000000..e7e9f796e9 --- /dev/null +++ b/types/ramda/es/omit.d.ts @@ -0,0 +1,2 @@ +import { omit } from '../index'; +export default omit; diff --git a/types/ramda/es/once.d.ts b/types/ramda/es/once.d.ts new file mode 100644 index 0000000000..f49febf008 --- /dev/null +++ b/types/ramda/es/once.d.ts @@ -0,0 +1,2 @@ +import { once } from '../index'; +export default once; diff --git a/types/ramda/es/or.d.ts b/types/ramda/es/or.d.ts new file mode 100644 index 0000000000..933ca7b2d2 --- /dev/null +++ b/types/ramda/es/or.d.ts @@ -0,0 +1,2 @@ +import { or } from '../index'; +export default or; diff --git a/types/ramda/es/over.d.ts b/types/ramda/es/over.d.ts new file mode 100644 index 0000000000..deee3577da --- /dev/null +++ b/types/ramda/es/over.d.ts @@ -0,0 +1,2 @@ +import { over } from '../index'; +export default over; diff --git a/types/ramda/es/pair.d.ts b/types/ramda/es/pair.d.ts new file mode 100644 index 0000000000..2a1cea9de0 --- /dev/null +++ b/types/ramda/es/pair.d.ts @@ -0,0 +1,2 @@ +import { pair } from '../index'; +export default pair; diff --git a/types/ramda/es/partial.d.ts b/types/ramda/es/partial.d.ts new file mode 100644 index 0000000000..acbb16bac3 --- /dev/null +++ b/types/ramda/es/partial.d.ts @@ -0,0 +1,2 @@ +import { partial } from '../index'; +export default partial; diff --git a/types/ramda/es/partialRight.d.ts b/types/ramda/es/partialRight.d.ts new file mode 100644 index 0000000000..5b3bb4b0fa --- /dev/null +++ b/types/ramda/es/partialRight.d.ts @@ -0,0 +1,2 @@ +import { partialRight } from '../index'; +export default partialRight; diff --git a/types/ramda/es/partition.d.ts b/types/ramda/es/partition.d.ts new file mode 100644 index 0000000000..28086418d7 --- /dev/null +++ b/types/ramda/es/partition.d.ts @@ -0,0 +1,2 @@ +import { partition } from '../index'; +export default partition; diff --git a/types/ramda/es/path.d.ts b/types/ramda/es/path.d.ts new file mode 100644 index 0000000000..edf4fa57b0 --- /dev/null +++ b/types/ramda/es/path.d.ts @@ -0,0 +1,2 @@ +import { path } from '../index'; +export default path; diff --git a/types/ramda/es/pathEq.d.ts b/types/ramda/es/pathEq.d.ts new file mode 100644 index 0000000000..27856ca3bc --- /dev/null +++ b/types/ramda/es/pathEq.d.ts @@ -0,0 +1,2 @@ +import { pathEq } from '../index'; +export default pathEq; diff --git a/types/ramda/es/pathOr.d.ts b/types/ramda/es/pathOr.d.ts new file mode 100644 index 0000000000..1af55adc0c --- /dev/null +++ b/types/ramda/es/pathOr.d.ts @@ -0,0 +1,2 @@ +import { pathOr } from '../index'; +export default pathOr; diff --git a/types/ramda/es/pathSatisfies.d.ts b/types/ramda/es/pathSatisfies.d.ts new file mode 100644 index 0000000000..e2493400a2 --- /dev/null +++ b/types/ramda/es/pathSatisfies.d.ts @@ -0,0 +1,2 @@ +import { pathSatisfies } from '../index'; +export default pathSatisfies; diff --git a/types/ramda/es/pick.d.ts b/types/ramda/es/pick.d.ts new file mode 100644 index 0000000000..67b2477a48 --- /dev/null +++ b/types/ramda/es/pick.d.ts @@ -0,0 +1,2 @@ +import { pick } from '../index'; +export default pick; diff --git a/types/ramda/es/pickAll.d.ts b/types/ramda/es/pickAll.d.ts new file mode 100644 index 0000000000..d7e7719077 --- /dev/null +++ b/types/ramda/es/pickAll.d.ts @@ -0,0 +1,2 @@ +import { pickAll } from '../index'; +export default pickAll; diff --git a/types/ramda/es/pickBy.d.ts b/types/ramda/es/pickBy.d.ts new file mode 100644 index 0000000000..4a047dc4ab --- /dev/null +++ b/types/ramda/es/pickBy.d.ts @@ -0,0 +1,2 @@ +import { pickBy } from '../index'; +export default pickBy; diff --git a/types/ramda/es/pipe.d.ts b/types/ramda/es/pipe.d.ts new file mode 100644 index 0000000000..ef1d61098b --- /dev/null +++ b/types/ramda/es/pipe.d.ts @@ -0,0 +1,2 @@ +import { pipe } from '../index'; +export default pipe; diff --git a/types/ramda/es/pipeK.d.ts b/types/ramda/es/pipeK.d.ts new file mode 100644 index 0000000000..bca50e6fff --- /dev/null +++ b/types/ramda/es/pipeK.d.ts @@ -0,0 +1,2 @@ +import { pipeK } from '../index'; +export default pipeK; diff --git a/types/ramda/es/pipeP.d.ts b/types/ramda/es/pipeP.d.ts new file mode 100644 index 0000000000..c69b96d23c --- /dev/null +++ b/types/ramda/es/pipeP.d.ts @@ -0,0 +1,2 @@ +import { pipeP } from '../index'; +export default pipeP; diff --git a/types/ramda/es/pluck.d.ts b/types/ramda/es/pluck.d.ts new file mode 100644 index 0000000000..8bdb4ccbe4 --- /dev/null +++ b/types/ramda/es/pluck.d.ts @@ -0,0 +1,2 @@ +import { pluck } from '../index'; +export default pluck; diff --git a/types/ramda/es/prepend.d.ts b/types/ramda/es/prepend.d.ts new file mode 100644 index 0000000000..9d3fde51b4 --- /dev/null +++ b/types/ramda/es/prepend.d.ts @@ -0,0 +1,2 @@ +import { prepend } from '../index'; +export default prepend; diff --git a/types/ramda/es/product.d.ts b/types/ramda/es/product.d.ts new file mode 100644 index 0000000000..32aed3c0ee --- /dev/null +++ b/types/ramda/es/product.d.ts @@ -0,0 +1,2 @@ +import { product } from '../index'; +export default product; diff --git a/types/ramda/es/project.d.ts b/types/ramda/es/project.d.ts new file mode 100644 index 0000000000..4c1b11c6ed --- /dev/null +++ b/types/ramda/es/project.d.ts @@ -0,0 +1,2 @@ +import { project } from '../index'; +export default project; diff --git a/types/ramda/es/prop.d.ts b/types/ramda/es/prop.d.ts new file mode 100644 index 0000000000..c990b9aca5 --- /dev/null +++ b/types/ramda/es/prop.d.ts @@ -0,0 +1,2 @@ +import { prop } from '../index'; +export default prop; diff --git a/types/ramda/es/propEq.d.ts b/types/ramda/es/propEq.d.ts new file mode 100644 index 0000000000..1e04cb564c --- /dev/null +++ b/types/ramda/es/propEq.d.ts @@ -0,0 +1,2 @@ +import { propEq } from '../index'; +export default propEq; diff --git a/types/ramda/es/propIs.d.ts b/types/ramda/es/propIs.d.ts new file mode 100644 index 0000000000..1be4e6bd04 --- /dev/null +++ b/types/ramda/es/propIs.d.ts @@ -0,0 +1,2 @@ +import { propIs } from '../index'; +export default propIs; diff --git a/types/ramda/es/propOr.d.ts b/types/ramda/es/propOr.d.ts new file mode 100644 index 0000000000..2935d077be --- /dev/null +++ b/types/ramda/es/propOr.d.ts @@ -0,0 +1,2 @@ +import { propOr } from '../index'; +export default propOr; diff --git a/types/ramda/es/propSatisfies.d.ts b/types/ramda/es/propSatisfies.d.ts new file mode 100644 index 0000000000..1b4ff52788 --- /dev/null +++ b/types/ramda/es/propSatisfies.d.ts @@ -0,0 +1,2 @@ +import { propSatisfies } from '../index'; +export default propSatisfies; diff --git a/types/ramda/es/props.d.ts b/types/ramda/es/props.d.ts new file mode 100644 index 0000000000..b856c60b00 --- /dev/null +++ b/types/ramda/es/props.d.ts @@ -0,0 +1,2 @@ +import { props } from '../index'; +export default props; diff --git a/types/ramda/es/range.d.ts b/types/ramda/es/range.d.ts new file mode 100644 index 0000000000..a507ebe4a9 --- /dev/null +++ b/types/ramda/es/range.d.ts @@ -0,0 +1,2 @@ +import { range } from '../index'; +export default range; diff --git a/types/ramda/es/reduce.d.ts b/types/ramda/es/reduce.d.ts new file mode 100644 index 0000000000..eb3b427d00 --- /dev/null +++ b/types/ramda/es/reduce.d.ts @@ -0,0 +1,2 @@ +import { reduce } from '../index'; +export default reduce; diff --git a/types/ramda/es/reduceBy.d.ts b/types/ramda/es/reduceBy.d.ts new file mode 100644 index 0000000000..655c96ef18 --- /dev/null +++ b/types/ramda/es/reduceBy.d.ts @@ -0,0 +1,2 @@ +import { reduceBy } from '../index'; +export default reduceBy; diff --git a/types/ramda/es/reduceRight.d.ts b/types/ramda/es/reduceRight.d.ts new file mode 100644 index 0000000000..3e72f7c309 --- /dev/null +++ b/types/ramda/es/reduceRight.d.ts @@ -0,0 +1,2 @@ +import { reduceRight } from '../index'; +export default reduceRight; diff --git a/types/ramda/es/reduceWhile.d.ts b/types/ramda/es/reduceWhile.d.ts new file mode 100644 index 0000000000..aaa836d38d --- /dev/null +++ b/types/ramda/es/reduceWhile.d.ts @@ -0,0 +1,2 @@ +import { reduceWhile } from '../index'; +export default reduceWhile; diff --git a/types/ramda/es/reduced.d.ts b/types/ramda/es/reduced.d.ts new file mode 100644 index 0000000000..f36739bbe2 --- /dev/null +++ b/types/ramda/es/reduced.d.ts @@ -0,0 +1,2 @@ +import { reduced } from '../index'; +export default reduced; diff --git a/types/ramda/es/reject.d.ts b/types/ramda/es/reject.d.ts new file mode 100644 index 0000000000..600c706f68 --- /dev/null +++ b/types/ramda/es/reject.d.ts @@ -0,0 +1,2 @@ +import { reject } from '../index'; +export default reject; diff --git a/types/ramda/es/remove.d.ts b/types/ramda/es/remove.d.ts new file mode 100644 index 0000000000..023edada47 --- /dev/null +++ b/types/ramda/es/remove.d.ts @@ -0,0 +1,2 @@ +import { remove } from '../index'; +export default remove; diff --git a/types/ramda/es/repeat.d.ts b/types/ramda/es/repeat.d.ts new file mode 100644 index 0000000000..3d8218a1a4 --- /dev/null +++ b/types/ramda/es/repeat.d.ts @@ -0,0 +1,2 @@ +import { repeat } from '../index'; +export default repeat; diff --git a/types/ramda/es/replace.d.ts b/types/ramda/es/replace.d.ts new file mode 100644 index 0000000000..dc735ab2cf --- /dev/null +++ b/types/ramda/es/replace.d.ts @@ -0,0 +1,2 @@ +import { replace } from '../index'; +export default replace; diff --git a/types/ramda/es/reverse.d.ts b/types/ramda/es/reverse.d.ts new file mode 100644 index 0000000000..2d1b2d9390 --- /dev/null +++ b/types/ramda/es/reverse.d.ts @@ -0,0 +1,2 @@ +import { reverse } from '../index'; +export default reverse; diff --git a/types/ramda/es/scan.d.ts b/types/ramda/es/scan.d.ts new file mode 100644 index 0000000000..8971cff9b7 --- /dev/null +++ b/types/ramda/es/scan.d.ts @@ -0,0 +1,2 @@ +import { scan } from '../index'; +export default scan; diff --git a/types/ramda/es/set.d.ts b/types/ramda/es/set.d.ts new file mode 100644 index 0000000000..5023a0b854 --- /dev/null +++ b/types/ramda/es/set.d.ts @@ -0,0 +1,2 @@ +import { set } from '../index'; +export default set; diff --git a/types/ramda/es/slice.d.ts b/types/ramda/es/slice.d.ts new file mode 100644 index 0000000000..6fdc54e59b --- /dev/null +++ b/types/ramda/es/slice.d.ts @@ -0,0 +1,2 @@ +import { slice } from '../index'; +export default slice; diff --git a/types/ramda/es/sort.d.ts b/types/ramda/es/sort.d.ts new file mode 100644 index 0000000000..9f4977e5c5 --- /dev/null +++ b/types/ramda/es/sort.d.ts @@ -0,0 +1,2 @@ +import { sort } from '../index'; +export default sort; diff --git a/types/ramda/es/sortBy.d.ts b/types/ramda/es/sortBy.d.ts new file mode 100644 index 0000000000..ff4eec72f4 --- /dev/null +++ b/types/ramda/es/sortBy.d.ts @@ -0,0 +1,2 @@ +import { sortBy } from '../index'; +export default sortBy; diff --git a/types/ramda/es/sortWith.d.ts b/types/ramda/es/sortWith.d.ts new file mode 100644 index 0000000000..e8e386a2fd --- /dev/null +++ b/types/ramda/es/sortWith.d.ts @@ -0,0 +1,2 @@ +import { sortWith } from '../index'; +export default sortWith; diff --git a/types/ramda/es/split.d.ts b/types/ramda/es/split.d.ts new file mode 100644 index 0000000000..c89a30372b --- /dev/null +++ b/types/ramda/es/split.d.ts @@ -0,0 +1,2 @@ +import { split } from '../index'; +export default split; diff --git a/types/ramda/es/splitAt.d.ts b/types/ramda/es/splitAt.d.ts new file mode 100644 index 0000000000..2f505a21e3 --- /dev/null +++ b/types/ramda/es/splitAt.d.ts @@ -0,0 +1,2 @@ +import { splitAt } from '../index'; +export default splitAt; diff --git a/types/ramda/es/splitEvery.d.ts b/types/ramda/es/splitEvery.d.ts new file mode 100644 index 0000000000..21329e9593 --- /dev/null +++ b/types/ramda/es/splitEvery.d.ts @@ -0,0 +1,2 @@ +import { splitEvery } from '../index'; +export default splitEvery; diff --git a/types/ramda/es/splitWhen.d.ts b/types/ramda/es/splitWhen.d.ts new file mode 100644 index 0000000000..fad94d5bfa --- /dev/null +++ b/types/ramda/es/splitWhen.d.ts @@ -0,0 +1,2 @@ +import { splitWhen } from '../index'; +export default splitWhen; diff --git a/types/ramda/es/startsWith.d.ts b/types/ramda/es/startsWith.d.ts new file mode 100644 index 0000000000..88811ae146 --- /dev/null +++ b/types/ramda/es/startsWith.d.ts @@ -0,0 +1,2 @@ +import { startsWith } from '../index'; +export default startsWith; diff --git a/types/ramda/es/subtract.d.ts b/types/ramda/es/subtract.d.ts new file mode 100644 index 0000000000..2bac6a6c9f --- /dev/null +++ b/types/ramda/es/subtract.d.ts @@ -0,0 +1,2 @@ +import { subtract } from '../index'; +export default subtract; diff --git a/types/ramda/es/sum.d.ts b/types/ramda/es/sum.d.ts new file mode 100644 index 0000000000..5aad66d4e2 --- /dev/null +++ b/types/ramda/es/sum.d.ts @@ -0,0 +1,2 @@ +import { sum } from '../index'; +export default sum; diff --git a/types/ramda/es/symmetricDifference.d.ts b/types/ramda/es/symmetricDifference.d.ts new file mode 100644 index 0000000000..d11802d977 --- /dev/null +++ b/types/ramda/es/symmetricDifference.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifference } from '../index'; +export default symmetricDifference; diff --git a/types/ramda/es/symmetricDifferenceWith.d.ts b/types/ramda/es/symmetricDifferenceWith.d.ts new file mode 100644 index 0000000000..9ee8a2b855 --- /dev/null +++ b/types/ramda/es/symmetricDifferenceWith.d.ts @@ -0,0 +1,2 @@ +import { symmetricDifferenceWith } from '../index'; +export default symmetricDifferenceWith; diff --git a/types/ramda/es/tail.d.ts b/types/ramda/es/tail.d.ts new file mode 100644 index 0000000000..5a949add56 --- /dev/null +++ b/types/ramda/es/tail.d.ts @@ -0,0 +1,2 @@ +import { tail } from '../index'; +export default tail; diff --git a/types/ramda/es/take.d.ts b/types/ramda/es/take.d.ts new file mode 100644 index 0000000000..35806f3171 --- /dev/null +++ b/types/ramda/es/take.d.ts @@ -0,0 +1,2 @@ +import { take } from '../index'; +export default take; diff --git a/types/ramda/es/takeLast.d.ts b/types/ramda/es/takeLast.d.ts new file mode 100644 index 0000000000..145934b186 --- /dev/null +++ b/types/ramda/es/takeLast.d.ts @@ -0,0 +1,2 @@ +import { takeLast } from '../index'; +export default takeLast; diff --git a/types/ramda/es/takeLastWhile.d.ts b/types/ramda/es/takeLastWhile.d.ts new file mode 100644 index 0000000000..0d6f344445 --- /dev/null +++ b/types/ramda/es/takeLastWhile.d.ts @@ -0,0 +1,2 @@ +import { takeLastWhile } from '../index'; +export default takeLastWhile; diff --git a/types/ramda/es/takeWhile.d.ts b/types/ramda/es/takeWhile.d.ts new file mode 100644 index 0000000000..c3f71dd0fd --- /dev/null +++ b/types/ramda/es/takeWhile.d.ts @@ -0,0 +1,2 @@ +import { takeWhile } from '../index'; +export default takeWhile; diff --git a/types/ramda/es/tap.d.ts b/types/ramda/es/tap.d.ts new file mode 100644 index 0000000000..329108173e --- /dev/null +++ b/types/ramda/es/tap.d.ts @@ -0,0 +1,2 @@ +import { tap } from '../index'; +export default tap; diff --git a/types/ramda/es/test.d.ts b/types/ramda/es/test.d.ts new file mode 100644 index 0000000000..64a6289599 --- /dev/null +++ b/types/ramda/es/test.d.ts @@ -0,0 +1,2 @@ +import { test } from '../index'; +export default test; diff --git a/types/ramda/es/times.d.ts b/types/ramda/es/times.d.ts new file mode 100644 index 0000000000..141c101e23 --- /dev/null +++ b/types/ramda/es/times.d.ts @@ -0,0 +1,2 @@ +import { times } from '../index'; +export default times; diff --git a/types/ramda/es/toLower.d.ts b/types/ramda/es/toLower.d.ts new file mode 100644 index 0000000000..4086a90f75 --- /dev/null +++ b/types/ramda/es/toLower.d.ts @@ -0,0 +1,2 @@ +import { toLower } from '../index'; +export default toLower; diff --git a/types/ramda/es/toPairs.d.ts b/types/ramda/es/toPairs.d.ts new file mode 100644 index 0000000000..5a6d3b24c2 --- /dev/null +++ b/types/ramda/es/toPairs.d.ts @@ -0,0 +1,2 @@ +import { toPairs } from '../index'; +export default toPairs; diff --git a/types/ramda/es/toPairsIn.d.ts b/types/ramda/es/toPairsIn.d.ts new file mode 100644 index 0000000000..70a879e200 --- /dev/null +++ b/types/ramda/es/toPairsIn.d.ts @@ -0,0 +1,2 @@ +import { toPairsIn } from '../index'; +export default toPairsIn; diff --git a/types/ramda/es/toString.d.ts b/types/ramda/es/toString.d.ts new file mode 100644 index 0000000000..c731b264be --- /dev/null +++ b/types/ramda/es/toString.d.ts @@ -0,0 +1,2 @@ +import { toString } from '../index'; +export default toString; diff --git a/types/ramda/es/toUpper.d.ts b/types/ramda/es/toUpper.d.ts new file mode 100644 index 0000000000..0a91bccfed --- /dev/null +++ b/types/ramda/es/toUpper.d.ts @@ -0,0 +1,2 @@ +import { toUpper } from '../index'; +export default toUpper; diff --git a/types/ramda/es/transduce.d.ts b/types/ramda/es/transduce.d.ts new file mode 100644 index 0000000000..de33a7380c --- /dev/null +++ b/types/ramda/es/transduce.d.ts @@ -0,0 +1,2 @@ +import { transduce } from '../index'; +export default transduce; diff --git a/types/ramda/es/transpose.d.ts b/types/ramda/es/transpose.d.ts new file mode 100644 index 0000000000..8ed6535fb2 --- /dev/null +++ b/types/ramda/es/transpose.d.ts @@ -0,0 +1,2 @@ +import { transpose } from '../index'; +export default transpose; diff --git a/types/ramda/es/traverse.d.ts b/types/ramda/es/traverse.d.ts new file mode 100644 index 0000000000..cb4fdc0b1e --- /dev/null +++ b/types/ramda/es/traverse.d.ts @@ -0,0 +1,2 @@ +import { traverse } from '../index'; +export default traverse; diff --git a/types/ramda/es/trim.d.ts b/types/ramda/es/trim.d.ts new file mode 100644 index 0000000000..f0000b80bb --- /dev/null +++ b/types/ramda/es/trim.d.ts @@ -0,0 +1,2 @@ +import { trim } from '../index'; +export default trim; diff --git a/types/ramda/es/tryCatch.d.ts b/types/ramda/es/tryCatch.d.ts new file mode 100644 index 0000000000..3c9edd9f79 --- /dev/null +++ b/types/ramda/es/tryCatch.d.ts @@ -0,0 +1,2 @@ +import { tryCatch } from '../index'; +export default tryCatch; diff --git a/types/ramda/es/type.d.ts b/types/ramda/es/type.d.ts new file mode 100644 index 0000000000..de115bb279 --- /dev/null +++ b/types/ramda/es/type.d.ts @@ -0,0 +1,2 @@ +import { type } from '../index'; +export default type; diff --git a/types/ramda/es/unapply.d.ts b/types/ramda/es/unapply.d.ts new file mode 100644 index 0000000000..7ad4b767e0 --- /dev/null +++ b/types/ramda/es/unapply.d.ts @@ -0,0 +1,2 @@ +import { unapply } from '../index'; +export default unapply; diff --git a/types/ramda/es/unary.d.ts b/types/ramda/es/unary.d.ts new file mode 100644 index 0000000000..c022aec354 --- /dev/null +++ b/types/ramda/es/unary.d.ts @@ -0,0 +1,2 @@ +import { unary } from '../index'; +export default unary; diff --git a/types/ramda/es/uncurryN.d.ts b/types/ramda/es/uncurryN.d.ts new file mode 100644 index 0000000000..b6962cc979 --- /dev/null +++ b/types/ramda/es/uncurryN.d.ts @@ -0,0 +1,2 @@ +import { uncurryN } from '../index'; +export default uncurryN; diff --git a/types/ramda/es/unfold.d.ts b/types/ramda/es/unfold.d.ts new file mode 100644 index 0000000000..2ebaff6fe5 --- /dev/null +++ b/types/ramda/es/unfold.d.ts @@ -0,0 +1,2 @@ +import { unfold } from '../index'; +export default unfold; diff --git a/types/ramda/es/union.d.ts b/types/ramda/es/union.d.ts new file mode 100644 index 0000000000..9fac243b43 --- /dev/null +++ b/types/ramda/es/union.d.ts @@ -0,0 +1,2 @@ +import { union } from '../index'; +export default union; diff --git a/types/ramda/es/unionWith.d.ts b/types/ramda/es/unionWith.d.ts new file mode 100644 index 0000000000..8bf20a51b7 --- /dev/null +++ b/types/ramda/es/unionWith.d.ts @@ -0,0 +1,2 @@ +import { unionWith } from '../index'; +export default unionWith; diff --git a/types/ramda/es/uniq.d.ts b/types/ramda/es/uniq.d.ts new file mode 100644 index 0000000000..be0a00aef0 --- /dev/null +++ b/types/ramda/es/uniq.d.ts @@ -0,0 +1,2 @@ +import { uniq } from '../index'; +export default uniq; diff --git a/types/ramda/es/uniqBy.d.ts b/types/ramda/es/uniqBy.d.ts new file mode 100644 index 0000000000..f85de9e4e0 --- /dev/null +++ b/types/ramda/es/uniqBy.d.ts @@ -0,0 +1,2 @@ +import { uniqBy } from '../index'; +export default uniqBy; diff --git a/types/ramda/es/uniqWith.d.ts b/types/ramda/es/uniqWith.d.ts new file mode 100644 index 0000000000..42442bffc3 --- /dev/null +++ b/types/ramda/es/uniqWith.d.ts @@ -0,0 +1,2 @@ +import { uniqWith } from '../index'; +export default uniqWith; diff --git a/types/ramda/es/unless.d.ts b/types/ramda/es/unless.d.ts new file mode 100644 index 0000000000..3727700625 --- /dev/null +++ b/types/ramda/es/unless.d.ts @@ -0,0 +1,2 @@ +import { unless } from '../index'; +export default unless; diff --git a/types/ramda/es/unnest.d.ts b/types/ramda/es/unnest.d.ts new file mode 100644 index 0000000000..ccbb4be0e8 --- /dev/null +++ b/types/ramda/es/unnest.d.ts @@ -0,0 +1,2 @@ +import { unnest } from '../index'; +export default unnest; diff --git a/types/ramda/es/until.d.ts b/types/ramda/es/until.d.ts new file mode 100644 index 0000000000..ab26247fea --- /dev/null +++ b/types/ramda/es/until.d.ts @@ -0,0 +1,2 @@ +import { until } from '../index'; +export default until; diff --git a/types/ramda/es/update.d.ts b/types/ramda/es/update.d.ts new file mode 100644 index 0000000000..c3eba99c72 --- /dev/null +++ b/types/ramda/es/update.d.ts @@ -0,0 +1,2 @@ +import { update } from '../index'; +export default update; diff --git a/types/ramda/es/useWith.d.ts b/types/ramda/es/useWith.d.ts new file mode 100644 index 0000000000..0d1f54e80f --- /dev/null +++ b/types/ramda/es/useWith.d.ts @@ -0,0 +1,2 @@ +import { useWith } from '../index'; +export default useWith; diff --git a/types/ramda/es/values.d.ts b/types/ramda/es/values.d.ts new file mode 100644 index 0000000000..8664d8cc67 --- /dev/null +++ b/types/ramda/es/values.d.ts @@ -0,0 +1,2 @@ +import { values } from '../index'; +export default values; diff --git a/types/ramda/es/valuesIn.d.ts b/types/ramda/es/valuesIn.d.ts new file mode 100644 index 0000000000..d80b32fc67 --- /dev/null +++ b/types/ramda/es/valuesIn.d.ts @@ -0,0 +1,2 @@ +import { valuesIn } from '../index'; +export default valuesIn; diff --git a/types/ramda/es/view.d.ts b/types/ramda/es/view.d.ts new file mode 100644 index 0000000000..3c11fa0ae9 --- /dev/null +++ b/types/ramda/es/view.d.ts @@ -0,0 +1,2 @@ +import { view } from '../index'; +export default view; diff --git a/types/ramda/es/when.d.ts b/types/ramda/es/when.d.ts new file mode 100644 index 0000000000..57de7e19a7 --- /dev/null +++ b/types/ramda/es/when.d.ts @@ -0,0 +1,2 @@ +import { when } from '../index'; +export default when; diff --git a/types/ramda/es/where.d.ts b/types/ramda/es/where.d.ts new file mode 100644 index 0000000000..4c49c2dc25 --- /dev/null +++ b/types/ramda/es/where.d.ts @@ -0,0 +1,2 @@ +import { where } from '../index'; +export default where; diff --git a/types/ramda/es/whereEq.d.ts b/types/ramda/es/whereEq.d.ts new file mode 100644 index 0000000000..4bdffa1d24 --- /dev/null +++ b/types/ramda/es/whereEq.d.ts @@ -0,0 +1,2 @@ +import { whereEq } from '../index'; +export default whereEq; diff --git a/types/ramda/es/without.d.ts b/types/ramda/es/without.d.ts new file mode 100644 index 0000000000..be9b8584ed --- /dev/null +++ b/types/ramda/es/without.d.ts @@ -0,0 +1,2 @@ +import { without } from '../index'; +export default without; diff --git a/types/ramda/es/wrap.d.ts b/types/ramda/es/wrap.d.ts new file mode 100644 index 0000000000..a855106989 --- /dev/null +++ b/types/ramda/es/wrap.d.ts @@ -0,0 +1,2 @@ +import { wrap } from '../index'; +export default wrap; diff --git a/types/ramda/es/xprod.d.ts b/types/ramda/es/xprod.d.ts new file mode 100644 index 0000000000..2e3fd865ea --- /dev/null +++ b/types/ramda/es/xprod.d.ts @@ -0,0 +1,2 @@ +import { xprod } from '../index'; +export default xprod; diff --git a/types/ramda/es/zip.d.ts b/types/ramda/es/zip.d.ts new file mode 100644 index 0000000000..609fe7bb29 --- /dev/null +++ b/types/ramda/es/zip.d.ts @@ -0,0 +1,2 @@ +import { zip } from '../index'; +export default zip; diff --git a/types/ramda/es/zipObj.d.ts b/types/ramda/es/zipObj.d.ts new file mode 100644 index 0000000000..dcc28311bc --- /dev/null +++ b/types/ramda/es/zipObj.d.ts @@ -0,0 +1,2 @@ +import { zipObj } from '../index'; +export default zipObj; diff --git a/types/ramda/es/zipWith.d.ts b/types/ramda/es/zipWith.d.ts new file mode 100644 index 0000000000..df6890c369 --- /dev/null +++ b/types/ramda/es/zipWith.d.ts @@ -0,0 +1,2 @@ +import { zipWith } from '../index'; +export default zipWith; diff --git a/types/ramda/index.d.ts b/types/ramda/index.d.ts index 9623aa8865..48888c6ee5 100644 --- a/types/ramda/index.d.ts +++ b/types/ramda/index.d.ts @@ -23,9 +23,253 @@ // Marcin Biernat // Rayhaneh Banyassady // Ryan McCuaig +// Drew Wyatt // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + declare let R: R.Static; declare namespace R { @@ -187,12 +431,20 @@ declare namespace R { (t1: T1, t2: T2, t3: T3, t4: T4, t5: T5, t6: T6): R; } + interface Placeholder { __isRamdaPlaceholder__: true; } + interface Reduced { '@@transducer/value': T; '@@transducer/reduced': true; } interface Static { + /** + * Placeholder. When used with functions like curry, or op, the second argument is applied to the second + * position, and it returns a function waiting for its first argument. + */ + __: Placeholder; /* This is used in examples throughout the docs, but I it only seems to be directly explained here: https://ramdajs.com/0.9/docs/#op */ + /** * Adds two numbers (or strings). Equivalent to a + b but curried. */ @@ -312,8 +564,8 @@ declare namespace R { * Makes a shallow clone of an object, setting or overriding the specified property with the given value. */ assoc(prop: K, val: T, obj: U): Record & U; - assoc(prop: K): (val: T, obj: U) => Record & U; assoc(prop: K, val: T): (obj: U) => Record & U; + assoc(prop: K): (val: T, obj: U) => Record & U; /** * Makes a shallow clone of an object, setting or overriding the nodes required to create the given path, and @@ -511,6 +763,8 @@ declare namespace R { * Returns a new list consisting of the elements of the first list followed by the elements * of the second. */ + concat(placeholder: Placeholder): (list2: ReadonlyArray, list1: ReadonlyArray) => T[]; + concat(placeholder: Placeholder, list2: ReadonlyArray): (list1: ReadonlyArray) => T[]; concat(list1: ReadonlyArray, list2: ReadonlyArray): T[]; concat(list1: ReadonlyArray): (list2: ReadonlyArray) => T[]; concat(list1: string, list2: string): string; @@ -523,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. @@ -539,6 +794,10 @@ declare namespace R { * Returns `true` if the specified item is somewhere in the list, `false` otherwise. * Equivalent to `indexOf(a)(list) > -1`. Uses strict (`===`) equality checking. */ + contains(__: Placeholder, list: string): (a: string) => boolean; + contains(__: Placeholder, list: T[]): (a: T) => boolean; + contains(__: Placeholder): (list: string, a: string) => boolean; + contains(__: Placeholder): (list: T[], a: T) => boolean; contains(a: string, list: string): boolean; contains(a: T, list: ReadonlyArray): boolean; contains(a: string): (list: string) => boolean; @@ -633,6 +892,8 @@ declare namespace R { /** * Divides two numbers. Equivalent to a / b. */ + divide(__: Placeholder, b: number): (a: number) => number; + divide(__: Placeholder): (b: number, a: number) => number; divide(a: number, b: number): number; divide(a: number): (b: number) => number; @@ -810,18 +1071,24 @@ declare namespace R { /** * Returns true if the first parameter is greater than the second. */ + gt(__: Placeholder, b: number): (a: number) => boolean; + gt(__: Placeholder): (b: number, a: number) => boolean; gt(a: number, b: number): boolean; gt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is greater than or equal to the second. */ + gte(__: Placeholder, b: number): (a: number) => boolean; + gte(__: Placeholder): (b: number, a: number) => boolean; gte(a: number, b: number): boolean; gte(a: number): (b: number) => boolean; /** * Returns whether or not an object has an own property with the specified name. */ + has(__: Placeholder, obj: T): (s: string) => boolean; + has(__: Placeholder): (obj: T, s: string) => boolean; has(s: string, obj: T): boolean; has(s: string): (obj: T) => boolean; @@ -1057,12 +1324,16 @@ declare namespace R { /** * Returns true if the first parameter is less than the second. */ + lt(__: Placeholder, b: number): (a: number) => boolean; + lt(__: Placeholder): (b: number, a: number) => boolean; lt(a: number, b: number): boolean; lt(a: number): (b: number) => boolean; /** * Returns true if the first parameter is less than or equal to the second. */ + lte(__: Placeholder, b: number): (a: number) => boolean; + lte(__: Placeholder): (b: number, a: number) => boolean; lte(a: number, b: number): boolean; lte(a: number): (b: number) => boolean; @@ -1118,6 +1389,8 @@ declare namespace R { * mathMod(-17, 5) is 3. mathMod requires Integer arguments, and returns NaN * when the modulus is zero or negative. */ + mathMod(__: Placeholder, b: number): (a: number) => number; + mathMod(__: Placeholder): (b: number, a: number) => number; mathMod(a: number, b: number): number; mathMod(a: number): (b: number) => number; @@ -1166,6 +1439,8 @@ declare namespace R { * merged with the own properties of object b. * This function will *not* mutate passed-in objects. */ + merge(__: Placeholder, b: T2): (a: T1) => T1 & T2; + merge(__: Placeholder): (b: T2, a: T1) => T1 & T2; merge(a: T1, b: T2): T1 & T2; merge(a: T1): (b: T2) => T1 & T2; @@ -1253,6 +1528,8 @@ declare namespace R { * Note that this functions preserves the JavaScript-style behavior for * modulo. For mathematical modulo see `mathMod` */ + modulo(__: Placeholder, b: number): (a: number) => number; + modulo(__: Placeholder): (b: number, a: number) => number; modulo(a: number, b: number): number; modulo(a: number): (b: number) => number; @@ -2039,6 +2316,8 @@ declare namespace R { /** * Subtracts two numbers. Equivalent to `a - b` but curried. */ + subtract(__: Placeholder, b: number): (a: number) => number; + subtract(__: Placeholder): (b: number, a: number) => number; subtract(a: number, b: number): number; subtract(a: number): (b: number) => number; diff --git a/types/ramda/ramda-tests.ts b/types/ramda/ramda-tests.ts index 951c11ba02..2bd9a55d2f 100644 --- a/types/ramda/ramda-tests.ts +++ b/types/ramda/ramda-tests.ts @@ -124,6 +124,45 @@ class F2 { } }; +/** R.__ */ +() => { + R.concat(R.__, [4, 5, 6])([1, 2, 3]); // [1, 2, 3, 4, 5, 6] + R.concat(R.__)([4, 5, 6], [1, 2, 3]); // [1, 2, 3, 4, 5, 6] + + R.contains(R.__, [1, 2, 3])(3); // true + R.contains(R.__)([1, 2, 3], 3); // true + + R.divide(R.__)(2, 42); // 21 + R.divide(R.__, 2)(42); // 21 + + R.gt(R.__, 2)(10); // true + R.gt(R.__)(2, 10); // true + + R.gte(R.__, 6)(2); // false + R.gte(R.__)(6, 2); // false + + R.has(R.__, {x: 0, y: 0})('x'); // true; + R.has(R.__)({x: 0, y: 0}, 'x'); // true; + + R.lt(R.__, 5)(10); // false + R.lt(R.__)(5, 10); // false + + R.lte(R.__, 2)(1); // true + R.lte(R.__)(2, 1); // true + + R.mathMod(R.__, 12)(15); // 3 + R.mathMod(R.__)(12, 15); // 3 + + R.modulo(R.__, 2)(42); // 0 + R.modulo(R.__)(2, 42); // 0 + + R.merge(R.__, {x: 0})({x: 5, y: 2}); // {x: 0, y: 2} + R.merge(R.__)({x: 0}, {x: 5, y: 2}); // {x: 0, y: 2} + + R.subtract(R.__, 5)(17); // 12 + R.subtract(R.__)(5, 17); // 12 +}; + () => { const addFour = (a: number) => (b: number) => (c: number) => (d: number) => a + b + c + d; const uncurriedAddFour = R.uncurryN(4, addFour); @@ -1267,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, ""); }; () => { @@ -1449,6 +1495,11 @@ type Pair = KeyValuePair; const c: ABC = R.assoc("c", 3)({a: 1, b: 2}); // => {a: 1, b: 2, c: 3} }; +() => { + type ABC = Record; + const b: ABC = R.compose(R.assoc, R.toString)(3)("c", {1: "a", 2: "b"}); // => {1: "a", 2: "b", 3: "c"} +}; + () => { const a1 = R.dissoc<{ a: number, c: number }>("b", {a: 1, b: 2, c: 3}); // => {a: 1, c: 3} const a2 = R.dissoc("b", {a: 1, b: 2, c: 3}); // => {a: 1, c: 3} 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-key/index.d.ts b/types/random-obj-key/index.d.ts new file mode 100644 index 0000000000..dfe12ca6f6 --- /dev/null +++ b/types/random-obj-key/index.d.ts @@ -0,0 +1,9 @@ +// Type definitions for random-obj-key 1.0 +// Project: https://github.com/sindresorhus/random-obj-key +// Definitions by: BendingBender +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 + +export = randomObjKey; + +declare function randomObjKey(input: TObj): keyof TObj; diff --git a/types/random-obj-key/random-obj-key-tests.ts b/types/random-obj-key/random-obj-key-tests.ts new file mode 100644 index 0000000000..b12cf282ea --- /dev/null +++ b/types/random-obj-key/random-obj-key-tests.ts @@ -0,0 +1,4 @@ +import randomObjKey = require('random-obj-key'); + +// $ExpectType "foo" | "bar" +randomObjKey({ foo: true, bar: true }); diff --git a/types/random-obj-key/tsconfig.json b/types/random-obj-key/tsconfig.json new file mode 100644 index 0000000000..aaaf33ba98 --- /dev/null +++ b/types/random-obj-key/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-key-tests.ts" + ] +} diff --git a/types/random-obj-key/tslint.json b/types/random-obj-key/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/random-obj-key/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/raven-for-redux/tsconfig.json b/types/raven-for-redux/tsconfig.json index acd330dac5..87b3d6d78c 100644 --- a/types/raven-for-redux/tsconfig.json +++ b/types/raven-for-redux/tsconfig.json @@ -2,7 +2,8 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6" + "es6", + "dom" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/raygun/index.d.ts b/types/raygun/index.d.ts new file mode 100644 index 0000000000..9315161a33 --- /dev/null +++ b/types/raygun/index.d.ts @@ -0,0 +1,146 @@ +// Type definitions for raygun 0.10 +// Project: https://github.com/MindscapeHQ/raygun4node +// Definitions by: Taylor Lodge +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 + +declare namespace raygun { + interface KeyValueObject { + [key: string]: string | number | boolean | KeyValueObject; + } + interface StackFrame { + lineNumber: number; + className: string; + fileName: string; + methodName: string; + columnNumber?: number; + } + interface RaygunErrorObject { + message: string; + className: string; + stackTrace: StackFrame[]; + innerError?: RaygunErrorObject; + } + interface RaygunRequest { + hostname?: string; + host?: string; + path?: string; + method?: string; + ip?: string; + queryString?: KeyValueObject; + headers?: KeyValueObject; + form?: KeyValueObject; + } + interface RaygunUser { + identifier: string; + email?: string; + fullName?: string; + firstName?: string; + uuid?: string; + } + interface RaygunPayload { + occurredOn: Date; + details: { + client: { + name: "raygun-node"; + version: string; + }; + groupingKey?: string; + error: RaygunErrorObject; + environment: { + osVersion: string; + architecture: string; + totalPhysicalMemory: number; + availablePhysicalMemory: number; + utcOffset: number; + processorCount?: number; + cpu: { + model: string; + speed: number; + times: { + user: number; + nice: number; + sys: number; + idle: number; + irq: number; + }; + }; + }; + machineName: string; + userCustomData?: KeyValueObject; + tags: string[]; + request?: RaygunRequest; + user?: RaygunUser | { identifier: string }; + version?: string; + }; + } + + interface RaygunOfflineStorageProvider< + TTransportItem = RaygunPayload, + TStorageItem = string + > { + init(options: any): RaygunOfflineStorageProvider; + save(item: TTransportItem, callback: (error?: Error) => void): void; + retrieve( + callback: ( + error: Error, + storageItems: ReadonlyArray + ) => void + ): void; + send( + callback: ( + error: Error, + sendItems: ReadonlyArray + ) => void + ): void; + } + + type OnBeforeSend = ( + payload: RaygunPayload, + exception: Error, + customData: KeyValueObject, + request: RaygunRequest, + tags: ReadonlyArray + ) => boolean | RaygunPayload; + interface RaygunOptions { + apiKey: string; + filters?: ReadonlyArray; + port?: number; + host?: string; + useSSL?: boolean; + onBeforeSend?: OnBeforeSend; + offlineStorage?: RaygunOfflineStorageProvider; + offlineStorageOptions?: any; + isOffline?: boolean; + groupingKey?: string; + tags?: ReadonlyArray; + userHumanStringForObject?: boolean; + reportColumnNumbers?: boolean; + innerErrorFieldName?: string; + } +} + +declare class Client { + init(options: raygun.RaygunOptions): Client; + setUser(user: raygun.RaygunUser): Client; + setVersion(version: string): Client; + onBeforeSend(callback: raygun.OnBeforeSend): Client; + groupingKey(groupingKey: string): Client; + offline(): Client; + online(): Client; + send( + exception: Error | string | object, + customData?: raygun.KeyValueObject, + offlineStorageCallback?: (error?: Error) => void, + request?: raygun.RaygunRequest, + tags?: ReadonlyArray + ): raygun.RaygunPayload; + expressHandler( + error: Error, + request: raygun.RaygunRequest, + res: any, + next: any + ): void; +} + +export = Client; diff --git a/types/raygun/raygun-tests.ts b/types/raygun/raygun-tests.ts new file mode 100644 index 0000000000..76328b01c5 --- /dev/null +++ b/types/raygun/raygun-tests.ts @@ -0,0 +1,59 @@ +import Client = require('raygun'); + +const client = new Client(); // $ExpectType Client +client.init({apiKey: '1'}); // $ExpectType Client + +client.init(); // $ExpectError +client.init({}); // $ExpectError +client.init({apiKey: 123}); // $ExpectError +// +// $ExpectType Client +client.setUser({ + identifier: '123' +}); +// $ExpectType Client +client.setUser({ + identifier: '123', + email: '123', + fullName: '123', + firstName: '123', + uuid: '123' +}); + +client.setUser(); // $ExpectError +client.setUser({}); // $ExpectError +client.setUser({identifier: 1}); // $ExpectError + +client.setVersion('123'); // $ExpectType Client + +client.setVersion(); // $ExpectError +client.setVersion({}); // $ExpectError + +client.onBeforeSend(payload => payload); // $ExpectType Client +// $ExpectType Client +client.onBeforeSend(payload => { + payload.details; + + return payload; +}); + +client.onBeforeSend(); // $ExpectError + +client.groupingKey('123'); // $ExpectType Client + +client.groupingKey(); // $ExpectError +client.groupingKey({}); // $ExpectError + +client.offline(); // $ExpectType Client + +client.online(); // $ExpectType Client + +client.send(new Error()); // $ExpectType RaygunPayload +client.send({foo: 'bar'}); // $ExpectType RaygunPayload +client.send('error message'); // $ExpectType RaygunPayload +client.send(new Error(), {foo: 'bar'}); // $ExpectType RaygunPayload +client.send(new Error(), {}, undefined, undefined, ['1', '2']); // $ExpectType RaygunPayload + +client.send(); // $ExpectError +client.send(null); // $ExpectError +client.send(undefined); // $ExpectError diff --git a/types/raygun/tsconfig.json b/types/raygun/tsconfig.json new file mode 100644 index 0000000000..f85de6fb88 --- /dev/null +++ b/types/raygun/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", + "raygun-tests.ts" + ] +} diff --git a/types/raygun/tslint.json b/types/raygun/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/raygun/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/raygun4js/index.d.ts b/types/raygun4js/index.d.ts index 66a7ce8ee9..d5faa0028b 100644 --- a/types/raygun4js/index.d.ts +++ b/types/raygun4js/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for raygun4js 2.6.0 +// Type definitions for raygun4js 2.13 // Project: https://github.com/MindscapeHQ/raygun4js -// Definitions by: Brian Surowiec , Benjamin Harding +// Definitions by: Brian Surowiec , Benjamin Harding , Taylor Lodge // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.4 interface TracekitStackTrace { message: string; @@ -20,7 +21,6 @@ interface TracekitStack { url: string; } - interface RaygunStackTrace { LineNumber: number; ColumnNumber: number; @@ -61,14 +61,17 @@ interface RaygunOptions { disablePulse?: boolean; /** - * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. + * Prevents errors from being sent from certain hostnames (domains) by providing an array of strings or RegExp objects (for partial matches). + * Each should match the hostname or TLD that you want to exclude. Note that protocols are not tested. */ - excludedHostnames?: (string|RegExp)[]; + excludedHostnames?: ReadonlyArray; /** - * Prevents errors from being sent from certain user agents by providing an array of strings. This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. + * Prevents errors from being sent from certain user agents by providing an array of strings. + * This is very helpful to exclude errors reported by certain browsers or test automation with CasperJS, PhantomJS or any other testing utility that sends a custom user agent. + * If a part of the client's navigator.userAgent matches one of the given strings in the array, then the client will be excluded from error reporting. */ - excludedUserAgents?: (string|RegExp)[]; + excludedUserAgents?: ReadonlyArray; /** * The maximum time a virtual page can be considered viewed, in milliseconds (defaults to 30 minutes). @@ -80,11 +83,6 @@ interface RaygunOptions { */ pulseIgnoreUrlCasing?: boolean; - /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. - */ - apiUrl?: string; - /** * If false, async callback functions triggered by setTimeout/setInterval will not be wrapped when attach() is called. Defaults to true */ @@ -95,20 +93,25 @@ interface RaygunOptions { */ debugMode?: boolean; + captureUnhandledRejections?: boolean; + setCookieAsSecure?: boolean; + /** - * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. + * Ignores any errors that have no stack trace information. This will discard any errors that occur completely within 3rd party scripts - + * if code loaded from the current domain called the 3rd party function, it will have at least one stack line and will still be sent. */ ignore3rdPartyErrors?: boolean; /** - * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. + * A string URI containing the protocol, domain and port (optional) where all payloads will be sent to. + * This can be used to proxy payloads to the Raygun API through your own server. When not set this defaults internally to the Raygun API, and for most usages you won't need to set this. */ apiEndpoint?: string; /** * String which can be optionally set "onLoad" which will then boot the RealUserMonitoring side instead of waiting for the `load` event. */ - from?: string|"onLoad"; + from?: string | "onLoad"; } interface RaygunPayload { @@ -121,16 +124,16 @@ interface RaygunPayload { }; Environment: { UtcOffset: number; - 'User-Language': string; - 'Document-Mode': number; - 'Browser-Width': number; - 'Browser-Height': number; - 'Screen-Width': number; - 'Screen-Height': number; - 'Color-Depth': number; + "User-Language": string; + "Document-Mode": number; + "Browser-Width": number; + "Browser-Height": number; + "Screen-Width": number; + "Screen-Height": number; + "Color-Depth": number; Browser: string; - 'Browser-Name': string; - 'Browser-Version': string; + "Browser-Name": string; + "Browser-Version": string; Platform: string; }; Client: { @@ -143,7 +146,7 @@ interface RaygunPayload { Url: string; QueryString: string; Headers: { - 'User-Agent': string; + "User-Agent": string; Referer: string; Host: string; }; @@ -162,7 +165,6 @@ interface RaygunPayload { } interface RaygunStatic { - /** * Prevents Raygun from overwriting anything bound to `window.Raygun`. */ @@ -176,7 +178,11 @@ interface RaygunStatic { /** * Configures the Raygun provider. */ - init(apiKey: string, options?: RaygunOptions, customdata?: any): RaygunStatic; + init( + apiKey: string, + options?: RaygunOptions, + customdata?: any + ): RaygunStatic; /** * Attaches custom data to any errors sent to Raygun. @@ -206,7 +212,14 @@ interface RaygunStatic { /** * Provides additional information about the current user. */ - setUser(user: string, isAnonymous?: boolean, email?: string, fullName?: string, firstName?: string, uuid?: string): RaygunStatic; + setUser( + user: string, + isAnonymous?: boolean, + email?: string, + fullName?: string, + firstName?: string, + uuid?: string + ): RaygunStatic; /** * Resets the information about the current user. @@ -226,12 +239,14 @@ interface RaygunStatic { /** * Blacklist keys to prevent their values from being sent to Raygun. */ - filterSensitiveData(filteredKeys: (string|RegExp)[]): RaygunStatic; + filterSensitiveData( + filteredKeys: ReadonlyArray + ): RaygunStatic; /** * Change the scope at which filters are applied. Defaults to `customData` by default. */ - setFilterScope(scope: "all"|"customData"): RaygunStatic; + setFilterScope(scope: "all" | "customData"): RaygunStatic; /** * Whitelist damains which should transmit errors to Raygun. @@ -241,12 +256,20 @@ interface RaygunStatic { /** * Executed before the payload is sent. If a truthy object is returned, Raygun will attempt to use that as the payload. Raygun will abort the send if `false` is returned. */ - onBeforeSend(callback: (payload: RaygunPayload) => RaygunPayload|boolean): RaygunStatic; + onBeforeSend( + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): RaygunStatic; /** * Overrides the default automatic grouping and instead group errors together by the string returned by the callback. */ - groupingKey(callback: (payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void): RaygunStatic; + groupingKey( + callback: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): RaygunStatic; onBeforeXHR(callback: (xhr: XMLHttpRequest) => void): RaygunStatic; onAfterSend(callback: (response: XMLHttpRequest) => void): RaygunStatic; endSession(): void; @@ -259,22 +282,29 @@ interface RaygunStatic { /** * Records a manual breadcrumb with the given message and metadata passed. */ - recordBreadcrumb(message:string,metadata?:any): void; + recordBreadcrumb(message: string, metadata?: any): void; /** * Enables all breadcrumbs level or a type can be passed which will enable only that passed one. */ - enableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + enableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Disables all breadcrumbs or a type can be passed to disable only that one. */ - disableAutoBreadcrumbs(type?:"XHR"|"Clicks"|"Console"|"Navigation"): void; + disableAutoBreadcrumbs( + type?: "XHR" | "Clicks" | "Console" | "Navigation" + ): void; /** * Pass "breadcrumbsLevel" alongside a valid breadcrumbs level to set the current level. Passing options other than "breadcrumbsLevel" will set xhr hosts to ignore being */ - setBreadcrumbOption(option?:string|"breadcrumbsLevel", value?:string|"debug"|"info"|"warning"|"error"): void; + setBreadcrumbOption( + option?: string | "breadcrumbsLevel", + value?: string | "debug" | "info" | "warning" | "error" + ): void; } interface RaygunV2UserDetails { @@ -286,7 +316,7 @@ interface RaygunV2UserDetails { /** * Indicates whether the user is anonymous or has a user account. Even if this is set to true, you should still give the user a unique identifier of some kind. */ - isAnonymous?: string; + isAnonymous?: boolean; /** * The user's email address. @@ -309,42 +339,79 @@ interface RaygunV2UserDetails { uuid?: string; } - +type BreadcrumbLevel = "debug" | "error" | "warning" | "info"; interface RaygunV2 { - (key: "options", value:RaygunOptions):void; - (key: "setUser", value: RaygunV2UserDetails):void; - (key: "onBeforeSend", callback: (payload: RaygunPayload) => RaygunPayload|boolean):void; - (key: "onBeforeXHR"|"onAfterSend", callback: (xhr: XMLHttpRequest) => void): void; - (key: "groupingKey", value:(payload: RaygunPayload, stackTrace: TracekitStackTrace, options: any) => string|void):void; - (key: "trackEvent", value: { type: string, path: string }): void; - (key: "apiKey"|"setVersion"|"setFilterScope", value:string):void; - (key: "attach"|"enableCrashReporting"|"enablePulse"|"noConflict"|"saveIfOffline", value: boolean):void; - (key: "filterSensitiveData"|"whitelistCrossOriginDomains"|"withTags", values: string[]): void; - (key: "send"|"withCustomData", value: any): void; - (key: "getRaygunInstance"):RaygunStatic; - (key: "detach"): void; - (key: "disableAutoBreadcrumbs"): void; - (key: "enableAutoBreadcrumbs"): void; - (key: "disableAutoBreadcrumbsConsole"): void; - (key: "enableAutoBreadcrumbsConsole"): void; - (key: "disableAutoBreadcrumbsNavigation"): void; - (key: "enableAutoBreadcrumbsNavigation"): void; - (key: "disableAutoBreadcrumbsClicks"): void; - (key: "enableAutoBreadcrumbsClicks"): void; - (key: "disableAutoBreadcrumbsXHR"): void; - (key: "enableAutoBreadcrumbsXHR"): void; - (key: "setAutoBreadcrumbsXHRIgnoredHosts"): void; - (key: "setBreadcrumbLevel"): void; - (key: "recordBreadcrumb", message:string|{message:string,metadata:any,level:string|"debug"|"info"|"warning"|"error",location:string}, metadata:any): void; - (key: string):void; + (key: "options", value: RaygunOptions): void; + (key: "setUser", value: RaygunV2UserDetails): void; + ( + key: "onBeforeSend", + callback: (payload: RaygunPayload) => RaygunPayload | boolean + ): void; + ( + key: "onBeforeXHR" | "onAfterSend", + callback: (xhr: XMLHttpRequest) => void + ): void; + ( + key: "groupingKey", + value: ( + payload: RaygunPayload, + stackTrace: TracekitStackTrace, + options: any + ) => string | void + ): void; + (key: "trackEvent", value: { type: string; path: string }): void; + (key: "apiKey" | "setVersion" | "setFilterScope", value: string): void; + ( + key: + | "attach" + | "enableCrashReporting" + | "enablePulse" + | "noConflict" + | "saveIfOffline", + value: boolean + ): void; + ( + key: "filterSensitiveData" | "whitelistCrossOriginDomains" | "withTags", + values: string[] + ): void; + (key: "send" | "withCustomData", value: any): void; + (key: "getRaygunInstance"): RaygunStatic; + ( + key: + | "detach" + | "disableAutoBreadcrumbs" + | "enableAutoBreadcrumbs" + | "disableAutoBreadcrumbsConsole" + | "enableAutoBreadcrumbsConsole" + | "disableAutoBreadcrumbsNavigation" + | "enableAutoBreadcrumbsNavigation" + | "disableAutoBreadcrumbsClicks" + | "enableAutoBreadcrumbsClicks" + | "disableAutoBreadcrumbsXHR" + | "enableAutoBreadcrumbsXHR" + | "setAutoBreadcrumbsXHRIgnoredHosts" + ): void; + (key: "setBreadcrumbLevel", level: BreadcrumbLevel): void; + ( + key: "recordBreadcrumb", + message: + | string + | { + message: string; + metadata: any; + level: BreadcrumbLevel; + location: string; + }, + metadata: object + ): void; } +declare const rg4js: RaygunV2; + interface Window { Raygun: RaygunStatic; } -declare var Raygun: RaygunStatic; +export { RaygunStatic, RaygunV2 }; -declare module 'raygun4js' { - export = Raygun; -} +export default rg4js; diff --git a/types/raygun4js/raygun4js-tests.ts b/types/raygun4js/raygun4js-tests.ts index 7fe6fc6496..388c960276 100644 --- a/types/raygun4js/raygun4js-tests.ts +++ b/types/raygun4js/raygun4js-tests.ts @@ -1,8 +1,7 @@ // V2 Api +// Used in CommonJS-like environments -// To use the V2 api you will need to declare a `rg4js` variable -// This is because `rg4js` name is configurable by users -declare var rg4js: RaygunV2; +import rg4js, { RaygunStatic } from 'raygun4js'; rg4js("apiKey", "api-key"); rg4js("enableCrashReporting", true); @@ -13,16 +12,25 @@ rg4js('setUser', { fullName: "Robert Raygun" }); +try { + throw new Error('oops'); +} catch (e) { + rg4js('send', e); +} + // V1 Api -var client: RaygunStatic = Raygun.noConflict(); -var newClient: RaygunStatic = client.constructNewRaygun(); +// Used in non CommonJS enviroments +declare const Raygun: RaygunStatic; + +const client: RaygunStatic = Raygun.noConflict(); +const newClient: RaygunStatic = client.constructNewRaygun(); client.init('api-key'); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }); client.init('api-key', { allowInsecureSubmissions: true, disablePulse: false }, { some: 'data' }); client.withCustomData({ some: 'data' }); -client.withCustomData(function() { +client.withCustomData(() => { return { some: 'data' }; }); @@ -36,8 +44,7 @@ client.send(new Error('a error'), { some: 'data' }, ['tag1', 'tag2']); try { throw new Error('oops'); -} -catch (e) { +} catch (e) { client.send(e); } @@ -57,7 +64,7 @@ client.setFilterScope('all'); client.whitelistCrossOriginDomains(['domain1', 'domain2']); -client.onBeforeSend(payload=> { +client.onBeforeSend(payload => { payload.OccurredOn = new Date(); return payload; }); diff --git a/types/raygun4js/tslint.json b/types/raygun4js/tslint.json index a41bf5d19a..f93cf8562a 100644 --- a/types/raygun4js/tslint.json +++ b/types/raygun4js/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/rc-progress/README.md b/types/rc-progress/README.md new file mode 100644 index 0000000000..a28d0e1a3b --- /dev/null +++ b/types/rc-progress/README.md @@ -0,0 +1,18 @@ +# Installation + +``` +npm install --save @types/rc-progress` +``` + +# Summary + +This package contains type definitions for [rc-progress](https://github.com/react-component/progress). + +Additional Details + * Last updated: Thu, 15 Nov 2018 + * Dependencies: react + * Global values: none + +# Credits + +These definitions were written by Jussi Kinnula diff --git a/types/rc-progress/index.d.ts b/types/rc-progress/index.d.ts new file mode 100644 index 0000000000..11385813fa --- /dev/null +++ b/types/rc-progress/index.d.ts @@ -0,0 +1,42 @@ +// Type definitions for rc-progress 2.2 +// Project: https://github.com/react-component/progress +// Definitions by: Jussi Kinnula +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface CommonProps { + className?: string; + percent?: number | string; + prefixCls?: string; + strokeColor?: string; + strokeLinecap?: 'butt' | 'square' | 'round'; + strokeWidth?: number | string; + style?: React.CSSProperties[] | React.CSSProperties; + trailColor?: string; + trailWidth?: number | string; +} + +export interface CircleProps extends CommonProps { + gapDegree?: number; + gapPosition?: 'top' | 'bottom' | 'left' | 'right'; +} + +export class Circle extends React.Component { + prevTimeStamp?: number; + + getPathStyles(): { + pathString: string; + trailPathStyle: React.CSSProperties[] | React.CSSProperties; + strokePathStyle: React.CSSProperties[] | React.CSSProperties; + }; +} + +export interface LineProps extends CommonProps { + prevTimeStamp?: number; +} + +export class Line extends React.Component { + path?: SVGPathElement; +} diff --git a/types/rc-progress/rc-progress-tests.tsx b/types/rc-progress/rc-progress-tests.tsx new file mode 100644 index 0000000000..e1eabfae2f --- /dev/null +++ b/types/rc-progress/rc-progress-tests.tsx @@ -0,0 +1,14 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Line, Circle } from 'rc-progress'; + +const App = () => ( +
          + + +
          +); + +const element = document.createElement('div'); +document.body.appendChild(element); +ReactDOM.render(, element); diff --git a/types/mali/tsconfig.json b/types/rc-progress/tsconfig.json similarity index 58% rename from types/mali/tsconfig.json rename to types/rc-progress/tsconfig.json index 1a4f86d02c..e7ef670b66 100644 --- a/types/mali/tsconfig.json +++ b/types/rc-progress/tsconfig.json @@ -1,19 +1,25 @@ { + "files": [ + "index.d.ts", + "rc-progress-tests.tsx" + ], "compilerOptions": { "module": "commonjs", - "lib": ["es6"], + "lib": [ + "es6", + "dom" + ], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": ["../"], + "typeRoots": [ + "../" + ], "types": [], "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mali-tests.ts" - ] + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + } } diff --git a/types/rc-progress/tslint.json b/types/rc-progress/tslint.json new file mode 100644 index 0000000000..b4b47a0378 --- /dev/null +++ b/types/rc-progress/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/rc-time-picker/index.d.ts b/types/rc-time-picker/index.d.ts new file mode 100644 index 0000000000..62f6a7711a --- /dev/null +++ b/types/rc-time-picker/index.d.ts @@ -0,0 +1,54 @@ +// Type definitions for rc-time-picker 3.4 +// Project: http://github.com/react-component/time-picker +// Definitions by: Frithjof Winkelmann +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as moment from "moment"; +import * as React from 'react'; + +interface TimePickerProps { + prefixCls: string; + clearText: string; + disabled: boolean; + allowEmpty: boolean; + open: boolean; + defaultValue: moment.Moment; + defaultOpenValue: moment.Moment; + value: moment.Moment; + placeholder: string; + className: string; + id: string; + popupClassName: string; + showHour: boolean; + showMinute: boolean; + showSecond: boolean; + format: string; + disabledHours: () => number[]; + disabledMinutes: (hour: number) => number[]; + disabledSeconds: (hour: number, minute: number) => number[]; + use12Hours: boolean; + hideDisabledOptions: boolean; + onChange: (value: moment.Moment) => void; + addon: (timepicker: TimePicker) => JSX.Element; + placement: string; + transitionName: string; + onOpen: (state: { open: boolean }) => void; + onClose: (state: { open: boolean }) => void; + hourStep: number; + minuteStep: number; + secondStep: number; + focusOnOpen: boolean; + inputReadOnly: boolean; + inputIcon: React.ReactNode; + clearIcon: React.ReactNode; +} + +declare class TimePicker extends React.Component> { + constructor(props: Readonly>) + + close(): void; + isAM(): boolean; +} + +export = TimePicker; diff --git a/types/rc-time-picker/rc-time-picker-tests.tsx b/types/rc-time-picker/rc-time-picker-tests.tsx new file mode 100644 index 0000000000..7f0ea63e9c --- /dev/null +++ b/types/rc-time-picker/rc-time-picker-tests.tsx @@ -0,0 +1,10 @@ +import TimePicker from 'rc-time-picker'; +import * as React from 'react'; +import moment from 'moment'; + + {}} + placeholder={'Input time'} + showSecond={false} + onOpen={({open}: { open: boolean }) => {}}/>; diff --git a/types/rc-time-picker/tsconfig.json b/types/rc-time-picker/tsconfig.json new file mode 100644 index 0000000000..adda4c82bb --- /dev/null +++ b/types/rc-time-picker/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, + "jsx": "react", + "esModuleInterop": true + }, + "files": [ + "index.d.ts", + "rc-time-picker-tests.tsx" + ] +} diff --git a/types/rc-time-picker/tslint.json b/types/rc-time-picker/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/rc-time-picker/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/rc-tooltip/index.d.ts b/types/rc-tooltip/index.d.ts index e752404f21..78a1fb63fb 100644 --- a/types/rc-tooltip/index.d.ts +++ b/types/rc-tooltip/index.d.ts @@ -1,7 +1,8 @@ -// Type definitions for rc-tooltip v3.4.2 +// Type definitions for rc-tooltip 3.7 // Project: https://github.com/react-component/tooltip -// Definitions by: rhysd -// ahstro +// Definitions by: rhysd +// ahstro +// vsaarinen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -24,6 +25,7 @@ declare namespace RCTooltip { prefixCls?: string; transitionName?: string; onVisibleChange?: (visible?: boolean) => void; + afterVisibleChange?: (visible?: boolean) => void; visible?: boolean; defaultVisible?: boolean; placement?: Placement | Object; @@ -33,6 +35,7 @@ declare namespace RCTooltip { arrowContent?: React.ReactNode; getTooltipContainer?: () => Element; destroyTooltipOnHide?: boolean; + id?: string; } } diff --git a/types/rc-tooltip/rc-tooltip-tests.tsx b/types/rc-tooltip/rc-tooltip-tests.tsx index 06b230a55b..7219d8579b 100644 --- a/types/rc-tooltip/rc-tooltip-tests.tsx +++ b/types/rc-tooltip/rc-tooltip-tests.tsx @@ -28,12 +28,14 @@ ReactDOM.render( prefixCls="my-" transitionName="cool-transition" onVisibleChange={() => console.log('visible changed')} + afterVisibleChange={() => console.log('after visible changed')} visible defaultVisible onPopupAlign={(popup, align) => console.log('aligned:', popup, align)} arrowContent={
          } getTooltipContainer={() => document.querySelector('.foo')} destroyTooltipOnHide + id="tooltip-id" > hover , diff --git a/types/rc-tooltip/tslint.json b/types/rc-tooltip/tslint.json index a41bf5d19a..a0357daa61 100644 --- a/types/rc-tooltip/tslint.json +++ b/types/rc-tooltip/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/rdf-data-model/index.d.ts b/types/rdf-data-model/index.d.ts index 9c15063eee..ea82a0e8f7 100644 --- a/types/rdf-data-model/index.d.ts +++ b/types/rdf-data-model/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/rdf-ext/rdf-data-model // Definitions by: Ruben Taelman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 import * as RDF from "rdf-js"; diff --git a/types/rdf-data-model/tslint.json b/types/rdf-data-model/tslint.json index 3db14f85ea..1c36270d47 100644 --- a/types/rdf-data-model/tslint.json +++ b/types/rdf-data-model/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/rdf-js/index.d.ts b/types/rdf-js/index.d.ts index 9911043b48..964f042134 100644 --- a/types/rdf-js/index.d.ts +++ b/types/rdf-js/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for the RDFJS specification 1.0 +// Type definitions for the RDFJS specification 2.0 // Project: https://github.com/rdfjs/representation-task-force // Definitions by: Ruben Taelman +// Laurens Rietveld // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 /// @@ -12,32 +14,19 @@ import { EventEmitter } from "events"; /* https://github.com/rdfjs/representation-task-force/blob/master/interface-spec.md#data-interfaces */ /** - * Abstract interface for RDF terms (subject, predicate, object or graph). + * Contains an Iri, RDF blank Node, RDF literal, variable name, or a default graph + * @see NamedNode + * @see BlankNode + * @see Literal + * @see Variable + * @see DefaultGraph */ -export interface Term { - /** - * Contains a value that identifies the concrete interface of the term, - * since Term itself is not directly instantiated. - * - * Possible values include "NamedNode", "BlankNode", "Literal", "Variable" and "DefaultGraph". - */ - termType: "NamedNode" | "BlankNode" | "Literal" | "Variable" | "DefaultGraph"; - /** - * Refined by each interface which extends Term - */ - value: string; - - /** - * @param other The term to compare with. - * @return If the termType is equal and the contents are equal (as defined by concrete subclasses). - */ - equals(other: Term): boolean; -} +export type Term = NamedNode | BlankNode | Literal | Variable | DefaultGraph; /** * Contains an IRI. */ -export interface NamedNode extends Term { +export interface NamedNode { /** * Contains the constant "NamedNode". */ @@ -57,7 +46,7 @@ export interface NamedNode extends Term { /** * Contains an RDF blank node. */ -export interface BlankNode extends Term { +export interface BlankNode { /** * Contains the constant "BlankNode". */ @@ -80,7 +69,7 @@ export interface BlankNode extends Term { /** * An RDF literal, containing a string with an optional language tag and/or datatype. */ -export interface Literal extends Term { +export interface Literal { /** * Contains the constant "Literal". */ @@ -111,7 +100,7 @@ export interface Literal extends Term { /** * A variable name. */ -export interface Variable extends Term { +export interface Variable { /** * Contains the constant "Variable". */ @@ -132,7 +121,7 @@ export interface Variable extends Term { * An instance of DefaultGraph represents the default graph. * It's only allowed to assign a DefaultGraph to the .graph property of a Quad. */ -export interface DefaultGraph extends Term { +export interface DefaultGraph { /** * Contains the constant "DefaultGraph". */ @@ -149,45 +138,101 @@ export interface DefaultGraph extends Term { equals(other: Term): boolean; } +/** + * The subject, which is a NamedNode, BlankNode or Variable. + * @see NamedNode + * @see BlankNode + * @see Variable + */ +export type Quad_Subject = NamedNode | BlankNode | Variable; + +/** + * The predicate, which is a NamedNode or Variable. + * @see NamedNode + * @see Variable + */ +export type Quad_Predicate = NamedNode | Variable; + +/** + * The object, which is a NamedNode, Literal, BlankNode or Variable. + * @see NamedNode + * @see Literal + * @see BlankNode + * @see Variable + */ +export type Quad_Object = NamedNode | Literal | BlankNode | Variable; + +/** + * The named graph, which is a DefaultGraph, NamedNode, BlankNode or Variable. + * @see DefaultGraph + * @see NamedNode + * @see BlankNode + * @see Variable + */ +export type Quad_Graph = DefaultGraph | NamedNode | BlankNode | Variable; + +/** + * An RDF quad, taking any Term in its positions, containing the subject, predicate, object and graph terms. + */ +export interface BaseQuad { + /** + * The subject. + * @see Quad_Subject + */ + subject: Term; + /** + * The predicate. + * @see Quad_Predicate + */ + predicate: Term; + /** + * The object. + * @see Quad_Object + */ + object: Term; + /** + * The named graph. + * @see Quad_Graph + */ + graph: Term; + + /** + * @param other The term to compare with. + * @return True if and only if the argument is a) of the same type b) has all components equal. + */ + equals(other: BaseQuad): boolean; +} + /** * An RDF quad, containing the subject, predicate, object and graph terms. */ -export interface Quad { +export interface Quad extends BaseQuad { /** - * The subject, which is a NamedNode, BlankNode or Variable. - * @see NamedNode - * @see BlankNode - * @see Variable + * The subject. + * @see Quad_Subject */ - subject: Term; + subject: Quad_Subject; /** - * The predicate, which is a NamedNode or Variable. - * @see NamedNode - * @see Variable + * The predicate. + * @see Quad_Predicate */ - predicate: Term; + predicate: Quad_Predicate; /** - * The object, which is a NamedNode, Literal, BlankNode or Variable. - * @see NamedNode - * @see Literal - * @see BlankNode - * @see Variable + * The object. + * @see Quad_Object */ - object: Term; + object: Quad_Object; /** - * The named graph, which is a DefaultGraph, NamedNode, BlankNode or Variable. - * @see DefaultGraph - * @see NamedNode - * @see BlankNode - * @see Variable + * The named graph. + * @see Quad_Graph */ - graph: Term; + graph: Quad_Graph; /** * @param other The term to compare with. * @return True if and only if the argument is a) of the same type b) has all components equal. */ - equals(other: Quad): boolean; + equals(other: BaseQuad): boolean; } /** @@ -252,7 +297,7 @@ export interface DataFactory { * @see Triple * @see DefaultGraph */ - triple(subject: Term, predicate: Term, object: Term): Quad; + triple(subject: Q['subject'], predicate: Q['predicate'], object: Q['object']): Q; /** * @param subject The quad subject term. @@ -262,7 +307,7 @@ export interface DataFactory { * @return A new instance of Quad. * @see Quad */ - quad(subject: Term, predicate: Term, object: Term, graph?: Term): Quad; + quad(subject: Q['subject'], predicate: Q['predicate'], object: Q['object'], graph?: Q['graph']): Q; } /* Stream Interfaces */ @@ -281,14 +326,14 @@ export interface DataFactory { * Optional events: * * prefix(prefix: string, iri: RDF.NamedNode): This event is emitted every time a prefix is mapped to some IRI. */ -export interface Stream extends EventEmitter { +export interface Stream extends EventEmitter { /** * This method pulls a quad out of the internal buffer and returns it. * If there is no quad available, then it will return null. * * @return A quad from the internal buffer, or null if none is available. */ - read(): Quad; + read(): Q; } /** @@ -298,7 +343,7 @@ export interface Stream extends EventEmitter { * * For example, parsers and transformations which generate quads can implement the Source interface. */ -export interface Source { +export interface Source { /** * Returns a stream that processes all quads matching the pattern. * @@ -308,8 +353,7 @@ export interface Source { * @param graph The optional exact graph or graph regex to match. * @return The resulting quad stream. */ - match(subject?: Term | RegExp, predicate?: Term | RegExp, object?: Term | RegExp, graph?: Term | RegExp) - : Stream; + match(subject?: Term | RegExp, predicate?: Term | RegExp, object?: Term | RegExp, graph?: Term | RegExp): Stream; } /** @@ -319,7 +363,7 @@ export interface Source { * * For example parsers, serializers, transformations and stores can implement the Sink interface. */ -export interface Sink { +export interface Sink { /** * Consumes the given stream. * @@ -330,7 +374,7 @@ export interface Sink { * @param stream The stream that will be consumed. * @return The resulting event emitter. */ - import(stream: Stream): EventEmitter; + import(stream: Stream): EventEmitter; } /** @@ -341,7 +385,7 @@ export interface Sink { * * Access to stores LDP or SPARQL endpoints can be implemented with a Store inteface. */ -export interface Store extends Source, Sink { +export interface Store extends Source, Sink { /** * Removes all streamed quads. * @@ -351,7 +395,7 @@ export interface Store extends Source, Sink { * @param stream The stream that will be consumed. * @return The resulting event emitter. */ - remove(stream: Stream): EventEmitter; + remove(stream: Stream): EventEmitter; /** * All quads matching the pattern will be removed. @@ -377,5 +421,5 @@ export interface Store extends Source, Sink { * @param graph The graph term or string to match. * @return The resulting event emitter. */ - deleteGraph(graph: Term | string): EventEmitter; + deleteGraph(graph: Q['graph'] | string): EventEmitter; } diff --git a/types/rdf-js/rdf-js-tests.ts b/types/rdf-js/rdf-js-tests.ts index 5dad2d1ce9..12b92b952d 100644 --- a/types/rdf-js/rdf-js-tests.ts +++ b/types/rdf-js/rdf-js-tests.ts @@ -1,5 +1,5 @@ -import { BlankNode, DataFactory, DefaultGraph, Literal, NamedNode, Quad, Sink, Source, Store, Stream, Triple, Term, - Variable } from "rdf-js"; +import { BlankNode, DataFactory, DefaultGraph, Literal, NamedNode, Quad, BaseQuad, Sink, Source, Store, Stream, Triple, Term, + Variable, Quad_Graph } from "rdf-js"; import { EventEmitter } from "events"; function test_terms() { @@ -7,6 +7,9 @@ function test_terms() { // so this does not have to be functional. const someTerm: Term = {}; + if (someTerm.termType === 'Literal') { + console.log(someTerm.datatype); + } const namedNode: NamedNode = {}; const termType1: string = namedNode.termType; const value1: string = namedNode.value; @@ -66,9 +69,16 @@ function test_datafactory() { const variable: Variable = dataFactory.variable ? dataFactory.variable('v1') : {}; - const term: Term = {}; + const term: NamedNode = {}; const triple: Quad = dataFactory.triple(term, term, term); - const quad: Quad = dataFactory.quad(term, term, term, term); + interface QuadBnode extends BaseQuad { + subject: Term; + predicate: Term; + object: Term; + graph: Term; + } + const quad = dataFactory.quad(literal1, blankNode1, term, term); + const hasBnode = quad.predicate.termType === "BlankNode"; } function test_stream() { @@ -88,6 +98,7 @@ function test_stream() { const matchStream9: Stream = source.match(term, term, term, /.*/); const sink: Sink = {}; + const graph: Quad_Graph = {}; const eventEmitter1: EventEmitter = sink.import(stream); const store: Store = {}; @@ -103,6 +114,6 @@ function test_stream() { const eventEmitter9: EventEmitter = store.removeMatches(term, term, /.*/); const eventEmitter10: EventEmitter = store.removeMatches(term, term, term, term); const eventEmitter11: EventEmitter = store.removeMatches(term, term, term, /.*/); - const eventEmitter12: EventEmitter = store.deleteGraph(term); + const eventEmitter12: EventEmitter = store.deleteGraph(graph); const eventEmitter13: EventEmitter = store.deleteGraph('http://example.org'); } diff --git a/types/rdf-js/tslint.json b/types/rdf-js/tslint.json index 3db14f85ea..4671311f51 100644 --- a/types/rdf-js/tslint.json +++ b/types/rdf-js/tslint.json @@ -1 +1,6 @@ -{ "extends": "dtslint/dt.json" } +{ + "extends": "dtslint/dt.json", + "rules": { + "no-angle-bracket-type-assertion": false + } +} diff --git a/types/reach__router/index.d.ts b/types/reach__router/index.d.ts index e61e9e15ad..ed3a6ff649 100644 --- a/types/reach__router/index.d.ts +++ b/types/reach__router/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for @reach/router 1.0 +// Type definitions for @reach/router 1.2 // Project: https://github.com/reach/router // Definitions by: Kingdaro // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -8,22 +8,31 @@ import * as React from "react"; import { Location as HLocation } from "history"; export type WindowLocation = Window["location"] & HLocation; +export type HistoryActionType = "PUSH" | "POP"; +export type HistoryLocation = WindowLocation & { state?: any }; +export interface HistoryListenerParameter { + location: HistoryLocation; + action: HistoryActionType; +} +export type HistoryListener = (parameter: HistoryListenerParameter) => void; +export type HistoryUnsubscribe = () => void; + export interface History { - readonly location: string; + readonly location: HistoryLocation; readonly transitioning: boolean; listen: (listener: HistoryListener) => HistoryUnsubscribe; navigate: NavigateFn; } -export type HistoryListener = () => void; -export type HistoryUnsubscribe = () => void; - -export class Router extends React.Component {} +export class Router extends React.Component< + RouterProps & React.HTMLProps +> {} export interface RouterProps { basepath?: string; primary?: boolean; location?: WindowLocation; + component?: React.ComponentType | string; } export type RouteComponentProps = Partial & { @@ -38,11 +47,11 @@ export type Omit = Pick>; export type AnchorProps = Omit< React.DetailedHTMLProps< - React.AnchorHTMLAttributes, - HTMLAnchorElement + React.AnchorHTMLAttributes, + HTMLAnchorElement >, "href" // remove href, as it's ignored by the router ->; + >; export interface LinkProps extends AnchorProps { to?: string; @@ -58,7 +67,7 @@ export interface LinkGetProps { location: WindowLocation; } -export class Link extends React.Component> {} +export class Link extends React.Component> { } export interface RedirectProps { from?: string; @@ -68,7 +77,7 @@ export interface RedirectProps { replace?: boolean; } -export class Redirect extends React.Component> {} +export class Redirect extends React.Component> { } export interface MatchProps { path: string; @@ -85,7 +94,7 @@ export interface MatchRenderProps { navigate: NavigateFn; } -export class Match extends React.Component> {} +export class Match extends React.Component> { } export type NavigateFn = (to: string, options?: NavigateOptions<{}>) => void; @@ -98,7 +107,7 @@ export interface LocationProps { children: LocationProviderRenderFn; } -export class Location extends React.Component {} +export class Location extends React.Component { } export interface LocationProviderProps { history: History; @@ -114,13 +123,13 @@ export interface LocationContext { navigate: NavigateFn; } -export class LocationProvider extends React.Component {} +export class LocationProvider extends React.Component { } export interface ServerLocationProps { url: string; } -export class ServerLocation extends React.Component {} +export class ServerLocation extends React.Component { } export const navigate: NavigateFn; @@ -146,3 +155,5 @@ export interface RedirectRequest { export function isRedirect(error: any): error is RedirectRequest; export function redirectTo(uri: string): void; + +export const globalHistory: History; diff --git a/types/reach__router/reach__router-tests.tsx b/types/reach__router/reach__router-tests.tsx index 0cada3367d..a64e1ae70d 100644 --- a/types/reach__router/reach__router-tests.tsx +++ b/types/reach__router/reach__router-tests.tsx @@ -4,9 +4,9 @@ import { RouteComponentProps, Router, Redirect -} from "@reach/router"; -import * as React from "react"; -import { render } from "react-dom"; +} from '@reach/router'; +import * as React from 'react'; +import { render } from 'react-dom'; interface DashParams { id: string; @@ -21,24 +21,30 @@ const Dash = (props: RouteComponentProps) => ( const NotFound = (props: RouteComponentProps) =>
          Route not found
          ; render( - + + + + + + + - + {context => ( <>
          hostname is {context.location.hostname}
          - )}
          , - document.getElementById("app-root") + document.getElementById('app-root') ); diff --git a/types/react-addons-test-utils/index.d.ts b/types/react-addons-test-utils/index.d.ts index 0531c5e3f6..19df32f3dc 100644 --- a/types/react-addons-test-utils/index.d.ts +++ b/types/react-addons-test-utils/index.d.ts @@ -160,11 +160,11 @@ declare namespace TestUtils { root: Component, tagName: string): Element; - export function scryRenderedComponentsWithType, C extends ComponentClass<{}>>( + export function scryRenderedComponentsWithType, C extends ComponentClass>( root: Component, type: ClassType): T[]; - export function findRenderedComponentWithType, C extends ComponentClass<{}>>( + export function findRenderedComponentWithType, C extends ComponentClass>( root: Component, type: ClassType): T; 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-alert/index.d.ts b/types/react-alert/index.d.ts index 3814b7f29f..6c94da77b0 100644 --- a/types/react-alert/index.d.ts +++ b/types/react-alert/index.d.ts @@ -1,110 +1,97 @@ -// Type definitions for react-alert 2.4 +// Type definitions for react-alert 4.0 // Project: https://github.com/schiehll/react-alert -// Definitions by: Steve Syrell +// Definitions by: Yue Yang // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import * as React from "react"; +import * as React from 'react'; -export interface AlertContainerProps { - /** - * The offset of the alert from the page border, can be any number. - * - * Default: 14. - */ - offset: number; +export type AlertPosition = + | 'top left' + | 'top right' + | 'top center' + | 'bottom left' + | 'bottom right' + | 'bottom center'; - /** - * The position of the alert. Can be [bottom left, bottom right, top left, top right]. - * - * Default: 'bottom left' - */ - position: string; +export type AlertType = 'info' | 'success' | 'error'; +export type AlertTransition = 'fade' | 'scale'; +export interface ProviderOptions { /** - * The color theme of the alert. Can be [dark, light]. + * The margin of each alert * - * Default: 'dark' + * Default value: '10px' */ - theme: string; - + offset?: string; /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure - * (applies to all alerts). + * The position of the alerts in the page * - * Default: 5000 + * Default value: 'top center' */ - time: number; - + position?: AlertPosition; /** - * The transition animation. Can be [scale, fade]. + * Timeout to alert remove itself, if set to 0 it never removes itself * - * Default: 'scale' + * Default value: 0 */ - transition: string; + timeout?: number; + /** + * The default alert type used when calling this.props.alert.show + * + * Default value: 'info' + */ + type?: AlertType; + /** + * The transition animation + * + * Default value: 'fade' + */ + transition?: AlertTransition; + /** + * The z-index of alerts + * + * Default value: 100 + */ + zIndex?: number; } -export interface AlertShowOptions { - /** - * The time in milliseconds the alert is displayed. After this - * time ellapses, the alert will close itself. Use 0 to prevent self-closure. - */ - time?: number; +export class Provider extends React.Component {} - /** - * The icon to show in the alert. - * - * Default: the icon which matches the type of alert to be shown. - */ - icon?: React.ReactNode; +export const Alert: React.Consumer; +export interface AlertCustomOptions { /** - * A callback function that will be called when the alert is closed. + * Custom timeout just for this one alert */ - onClose?: () => void; - + timeout?: number; /** - * The type of alert to show. This will only be used when calling show(). - * Can be [info, success, error]. - * - * Default: 'info' + * Callback that will be executed after this alert open */ - type?: string; + onOpen?(): undefined; + /** + * Callback that will be executed after this alert is removed + */ + onClose?(): undefined; } -export default class AlertContainer extends React.Component { - /** - * Show a success alert. - * @returns The id of the created alert. - */ - success(message: string, options?: AlertShowOptions): string; - - /** - * Show an error alert. - * @returns The id of the created alert. - */ - error(message: string, options?: AlertShowOptions): string; - - /** - * Show an info alert. - * @returns The id of the created alert. - */ - info(message: string, options?: AlertShowOptions): string; - - /** - * Show an alert. - * @returns The id of the created alert. - */ - show(message: string, options?: AlertShowOptions): string; - - /** - * Remove all alerts from the page. - */ - removeAll(): void; - - /** - * Removes the alert with the specified id from the page. - */ - remove(id: string): void; +export interface AlertCustomOptionsWithType extends AlertCustomOptions { + type?: AlertType; } + +export interface InjectedAlertProp { + show( + message?: string, + options?: AlertCustomOptionsWithType + ): InjectedAlertProp; + remove(alert: InjectedAlertProp): undefined; + success(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + error(message?: string, options?: AlertCustomOptions): InjectedAlertProp; + info(message?: string, options?: AlertCustomOptions): InjectedAlertProp; +} + +export function withAlert

          ( + c: React.ComponentType

          +): React.ComponentType>>; diff --git a/types/react-alert/react-alert-tests.tsx b/types/react-alert/react-alert-tests.tsx index 84686ea73d..c6088a52a8 100644 --- a/types/react-alert/react-alert-tests.tsx +++ b/types/react-alert/react-alert-tests.tsx @@ -1,48 +1,91 @@ -import * as React from "react"; -import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; +import * as React from 'react'; +import { + Provider as AlertProvider, + Alert, + withAlert, + AlertPosition, + AlertTransition, + ProviderOptions, + InjectedAlertProp +} from 'react-alert'; -export class ReactAlertTest extends React.Component { - private _alert: AlertContainer; +class AppWithoutAlert extends React.Component<{ alert: InjectedAlertProp }> { render() { - const props: AlertContainerProps = { - offset: 14, - position: "bottom left", - theme: "dark", - time: 5000, - transition: "scale" - }; + return ( + + ); + } +} + +const App = withAlert(AppWithoutAlert); + +class AppAlert extends React.Component { + render() { + return ( + + {alert => ( + + )} + + ); + } +} + +class AlertTemplate extends React.Component { + render() { + // the style contains only the margin given as offset + // options contains all alert given options + // message is the alert message... + // close is a function that closes the alert + const { style, options, message, close } = this.props; return ( -

          - this._alert = a as AlertContainer} {...props} /> +
          + {options.type === 'info' && '!'} + {options.type === 'success' && ':)'} + {options.type === 'error' && ':('} + {message} +
          ); } +} - private _testMethods(): void { - const options: AlertShowOptions = { - time: 5000, - type: "info", - onClose: this._onAlertClosed, - icon: - }; +const options: ProviderOptions = { + position: 'bottom center' as AlertPosition, + timeout: 5000, + offset: '30px', + transition: 'scale' as AlertTransition +}; - let alertId: string; - alertId = this._alert.show("show without options"); - alertId = this._alert.show("show with options", options); - - alertId = this._alert.error("error without options"); - alertId = this._alert.error("error with options", options); - - alertId = this._alert.info("info without options"); - alertId = this._alert.info("info with options", options); +class Root extends React.Component { + render() { + return ( + + + + ); + } +} - alertId = this._alert.success("success without options"); - alertId = this._alert.success("success with options", options); - - this._alert.remove(alertId); - this._alert.removeAll(); +class RootAlert extends React.Component { + render() { + return ( + + + + ); } - - private _onAlertClosed(): void { } } diff --git a/types/react-alert/v2/index.d.ts b/types/react-alert/v2/index.d.ts new file mode 100644 index 0000000000..3814b7f29f --- /dev/null +++ b/types/react-alert/v2/index.d.ts @@ -0,0 +1,110 @@ +// Type definitions for react-alert 2.4 +// Project: https://github.com/schiehll/react-alert +// Definitions by: Steve Syrell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface AlertContainerProps { + /** + * The offset of the alert from the page border, can be any number. + * + * Default: 14. + */ + offset: number; + + /** + * The position of the alert. Can be [bottom left, bottom right, top left, top right]. + * + * Default: 'bottom left' + */ + position: string; + + /** + * The color theme of the alert. Can be [dark, light]. + * + * Default: 'dark' + */ + theme: string; + + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure + * (applies to all alerts). + * + * Default: 5000 + */ + time: number; + + /** + * The transition animation. Can be [scale, fade]. + * + * Default: 'scale' + */ + transition: string; +} + +export interface AlertShowOptions { + /** + * The time in milliseconds the alert is displayed. After this + * time ellapses, the alert will close itself. Use 0 to prevent self-closure. + */ + time?: number; + + /** + * The icon to show in the alert. + * + * Default: the icon which matches the type of alert to be shown. + */ + icon?: React.ReactNode; + + /** + * A callback function that will be called when the alert is closed. + */ + onClose?: () => void; + + /** + * The type of alert to show. This will only be used when calling show(). + * Can be [info, success, error]. + * + * Default: 'info' + */ + type?: string; +} + +export default class AlertContainer extends React.Component { + /** + * Show a success alert. + * @returns The id of the created alert. + */ + success(message: string, options?: AlertShowOptions): string; + + /** + * Show an error alert. + * @returns The id of the created alert. + */ + error(message: string, options?: AlertShowOptions): string; + + /** + * Show an info alert. + * @returns The id of the created alert. + */ + info(message: string, options?: AlertShowOptions): string; + + /** + * Show an alert. + * @returns The id of the created alert. + */ + show(message: string, options?: AlertShowOptions): string; + + /** + * Remove all alerts from the page. + */ + removeAll(): void; + + /** + * Removes the alert with the specified id from the page. + */ + remove(id: string): void; +} diff --git a/types/react-alert/v2/react-alert-tests.tsx b/types/react-alert/v2/react-alert-tests.tsx new file mode 100644 index 0000000000..84686ea73d --- /dev/null +++ b/types/react-alert/v2/react-alert-tests.tsx @@ -0,0 +1,48 @@ +import * as React from "react"; +import AlertContainer, { AlertContainerProps, AlertShowOptions } from "react-alert"; + +export class ReactAlertTest extends React.Component { + private _alert: AlertContainer; + render() { + const props: AlertContainerProps = { + offset: 14, + position: "bottom left", + theme: "dark", + time: 5000, + transition: "scale" + }; + + return ( +
          + this._alert = a as AlertContainer} {...props} /> +
          + ); + } + + private _testMethods(): void { + const options: AlertShowOptions = { + time: 5000, + type: "info", + onClose: this._onAlertClosed, + icon: + }; + + let alertId: string; + alertId = this._alert.show("show without options"); + alertId = this._alert.show("show with options", options); + + alertId = this._alert.error("error without options"); + alertId = this._alert.error("error with options", options); + + alertId = this._alert.info("info without options"); + alertId = this._alert.info("info with options", options); + + alertId = this._alert.success("success without options"); + alertId = this._alert.success("success with options", options); + + this._alert.remove(alertId); + this._alert.removeAll(); + } + + private _onAlertClosed(): void { } +} diff --git a/types/react-alert/v2/tsconfig.json b/types/react-alert/v2/tsconfig.json new file mode 100644 index 0000000000..47de249c7e --- /dev/null +++ b/types/react-alert/v2/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../../", + "typeRoots": [ + "../../" + ], + "paths": { + "react-alert": ["react-alert/v2"] + }, + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react-alert-tests.tsx" + ] +} diff --git a/types/react-alert/v2/tslint.json b/types/react-alert/v2/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-alert/v2/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-better-password/index.d.ts b/types/react-better-password/index.d.ts new file mode 100644 index 0000000000..b07a4e840e --- /dev/null +++ b/types/react-better-password/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for react-better-password 1.0 +// Project: https://github.com/karaggeorge/react-better-password +// Definitions by: Mary Huynh +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +export interface PasswordProps { + className?: string; + mask?: '•' | string; + onChange?: (value: string) => void; + placeholder?: string; + show?: boolean; + timeout?: number; + value?: string; +} +export default class Password extends React.Component { } diff --git a/types/react-better-password/react-better-password-tests.tsx b/types/react-better-password/react-better-password-tests.tsx new file mode 100644 index 0000000000..1aea80d250 --- /dev/null +++ b/types/react-better-password/react-better-password-tests.tsx @@ -0,0 +1,29 @@ +import * as React from 'react'; +import Password from 'react-better-password'; + +interface PasswordState { + password: string; +} + +class ReactBetterPasswordTest extends React.Component<{}, PasswordState> { + state = { + password: "", + }; + + handlePw = (password: string) => { + this.setState({ password }); + } + + render() { + const { password } = this.state; + return ( + + ); + } +} +export default ReactBetterPasswordTest; diff --git a/types/react-better-password/tsconfig.json b/types/react-better-password/tsconfig.json new file mode 100644 index 0000000000..2381541694 --- /dev/null +++ b/types/react-better-password/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "strictNullChecks": true, + "strictFunctionTypes": true, + "noImplicitAny": true, + "noImplicitThis": true, + "forceConsistentCasingInFileNames": true, + "noEmit": true + }, + "files": [ + "index.d.ts", + "react-better-password-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-better-password/tslint.json b/types/react-better-password/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-better-password/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index bbfd7047ec..89e6f0eead 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -5,14 +5,23 @@ // Krzysztof Bezrąk // Sebastian Silbermann // Paul Potsides +// janb87 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Validator } from 'prop-types'; import * as React from 'react'; +export type DayPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; +export type EventPropGetter = (event: T, start: stringOrDate, end: stringOrDate, isSelected: boolean) => { className?: string, style?: React.CSSProperties }; +export type SlotPropGetter = (date: Date) => { className?: string, style?: React.CSSProperties }; export type stringOrDate = string | Date; export type ViewKey = 'MONTH' | 'WEEK' | 'WORK_WEEK' | 'DAY' | 'AGENDA'; export type View = 'month' | 'week' | 'work_week' | 'day' | 'agenda'; +export type Views = View[] | { + month: boolean | React.SFC | React.Component, + week: boolean | React.SFC | React.Component, + myweek: boolean | React.SFC | React.Component, +}; export type Navigate = 'PREV' | 'NEXT' | 'TODAY' | 'DATE'; export type Event = object; @@ -70,7 +79,7 @@ export interface Formats { /** * Toolbar header format for the Agenda view, e.g. "4/1/2015 — 5/1/2015" */ - agendaHeaderFormat?: DateFormat; + agendaHeaderFormat?: DateRangeFormatFunction; /** * A time range format for selecting time slots, e.g "8:00am — 2:00pm" @@ -105,14 +114,14 @@ export interface HeaderProps { export interface Components { event?: React.SFC | React.Component | React.ComponentClass | JSX.Element; - eventWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + eventWrapper?: React.ComponentType; dayWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; dateCellWrapper?: React.SFC | React.Component | React.ComponentClass | JSX.Element; /** * component used as a header for each column in the TimeGridHeader */ header?: React.ComponentType; - toolbar?: React.SFC | React.Component | React.ComponentClass | JSX.Element; + toolbar?: React.ComponentType; agenda?: { date?: React.SFC | React.Component | React.ComponentClass | JSX.Element; time?: React.SFC | React.Component | React.ComponentClass | JSX.Element; @@ -133,6 +142,42 @@ export interface Components { }; } +export interface ToolbarProps { + date: Date; + view: View; + views: Views; + label: string; + localizer: { messages: Messages }; + onNavigate: (navigate: Navigate, date?: Date) => void; + onView: (view: View) => void; + children?: React.ReactNode; +} + +export interface EventWrapperProps { + // https://github.com/intljusticemission/react-big-calendar/blob/27a2656b40ac8729634d24376dff8ea781a66d50/src/TimeGridEvent.js#L28 + style?: React.CSSProperties & { xOffset: number }; + className: string; + event: T; + isRtl: boolean; + getters: { + eventProp?: EventPropGetter; + slotProp?: SlotPropGetter; + dayProp?: DayPropGetter; + }; + onClick: (e: React.MouseEvent) => void; + onDoubleClick: (e: React.MouseEvent) => void; + accessors: { + title?: (event: T) => string; + tooltip?: (event: T) => string; + end?: (event: T) => Date; + start?: (event: T) => Date; + }; + selected: boolean; + label: string; + continuesEarlier: boolean; + continuesLater: boolean; +} + export interface Messages { date?: string; time?: string; @@ -171,26 +216,22 @@ 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?: View[] | { - month: boolean | React.SFC | React.Component, - week: boolean | React.SFC | React.Component, - myweek: boolean | React.SFC | React.Component, - }; + views?: Views; drilldownView?: View | null; getDrilldownView?: ((targetDate: Date, currentViewName: View, configuredViewNames: View[]) => void) | null; length?: number; @@ -202,9 +243,9 @@ export interface BigCalendarProps extends React.Props { className?: string, style?: React.CSSProperties }; - slotPropGetter?: (date: Date) => { className?: string, style?: object }; - dayPropGetter?: (date: Date) => { className?: string, style?: object }; + eventPropGetter?: EventPropGetter; + slotPropGetter?: SlotPropGetter; + dayPropGetter?: DayPropGetter; showMultiDayTimes?: boolean; min?: stringOrDate; max?: stringOrDate; @@ -213,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; @@ -237,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 e1b561901e..fd1e70f929 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import * as ReactDOM from "react-dom"; -import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer } from "react-big-calendar"; +import BigCalendar, { BigCalendarProps, Navigate, View, DateRange, DateLocalizer, ToolbarProps, EventWrapperProps } from "react-big-calendar"; // Don't want to add this as a dependency, because it is only used for tests. declare const globalize: any; @@ -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,64 +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 - } - }} - 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} /> ); } } @@ -130,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; @@ -172,3 +199,25 @@ function Event(event: any) { ); } + +class EventWrapper extends React.Component { + render() { + const { continuesEarlier, label, accessors = {}, style } = this.props; + return ( +
          +
          {continuesEarlier}-{label}-{accessors.title && event && accessors.title(event)}}
          +
          + ); + } +} + +class Toolbar extends React.Component { + render() { + const { date, label, view } = this.props; + return ( +
          +
          {date.toJSON()}-{label}-{view}}
          +
          + ); + } +} diff --git a/types/react-blessed/index.d.ts b/types/react-blessed/index.d.ts new file mode 100644 index 0000000000..33c9fe2790 --- /dev/null +++ b/types/react-blessed/index.d.ts @@ -0,0 +1,16 @@ +// Type definitions for react-blessed 0.3 +// Project: https://github.com/yomguithereal/react-blessed#readme +// Definitions by: My Self +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { Widgets, screen } from 'blessed'; +export type Callback = () => void | null | undefined; +export type renderer = ( + c: JSX.Element, s: Widgets.Screen, callback?: Callback, +) => React.Component | null; +export function render( + c: JSX.Element, s: Widgets.Screen, callback?: Callback +): React.Component | null; +export function createBlessedRenderer(bls: any): renderer; diff --git a/types/react-blessed/react-blessed-tests.tsx b/types/react-blessed/react-blessed-tests.tsx new file mode 100644 index 0000000000..5ac0ac073c --- /dev/null +++ b/types/react-blessed/react-blessed-tests.tsx @@ -0,0 +1,197 @@ +import * as React from 'react'; +import * as blessed from 'blessed'; +import { render } from 'react-blessed'; + +// Testing example from demos page +// https://github.com/Yomguithereal/react-blessed/blob/master/examples/dashboard.jsx + +const { Component } = React; + +/** + * Stylesheet + */ +const stylesheet = { + bordered: { + border: { + type: 'line' + }, + style: { + border: { + fg: 'blue' + } + } + } +}; + +/** + * Top level component. + */ +class Dashboard extends Component { + render() { + return ( + <> + + + + + + + + ); + } +} + +/** + * Log component. + */ +class Log extends Component { + render() { + return ( + + {'Hello'}, {0}, {'World'} + + ); + } +} + +/** + * Request component. + */ +class Request extends Component { + render() { + return ( + + {0} + + ); + } +} + +/** + * Response component. + */ +class Response extends Component { + render() { + return ( + + ); + } +} + +/** + * Jobs component. + */ +class Jobs extends Component { + render() { + return ( + + ); + } +} + +/** + * Progress component. + */ +class Progress extends Component { + state: { + progress: number, + color: string, + } = { + progress: 0, + color: 'blue' + }; + + constructor(props: any) { + super(props); + const interval: NodeJS.Timer = setInterval(() => { + const { progress } = this.state; + if (this.state.progress >= 100) { + clearInterval(interval); + return; + } + this.setState({ + progress: progress + 1, + }); + }, 50); + } + + render() { + const { progress, color } = this.state; + const label = `Progress - ${progress}%`; + + return ( + this.setState({ + color: 'green' + })} + class={stylesheet.bordered} + filled={progress} + top='60%' + left='60%' + width='40%' + height='10%' + style={{ + bar: { + bg: color + } + }} + /> + ); + } +} + +/** + * Stats component. + */ +class Stats extends Component { + render() { + return ( + + Some stats + + ); + } +} + +/** + * Rendering the screen. + */ +const screen = blessed.screen({ + autoPadding: true, + smartCSR: true, + title: 'react-blessed dashboard' +}); + +screen.key(['escape', 'q', 'C-c'], () => { + return process.exit(0); +}); + +render(, screen); diff --git a/types/react-blessed/react.d.ts b/types/react-blessed/react.d.ts new file mode 100644 index 0000000000..4344c2a871 --- /dev/null +++ b/types/react-blessed/react.d.ts @@ -0,0 +1,34 @@ +// relation to blessed export widgets, prepare for next version of react-blessed +declare namespace JSX { + interface IntrinsicElements { + 'blessed-box': any; + 'blessed-text': any; + 'blessed-line': any; + 'blessed-scrollablebox': any; + 'blessed-scrollabletext': any; + 'blessed-bigtext': any; + 'blessed-list': any; + 'blessed-filemanager': any; + 'blessed-listtable': any; + 'blessed-listbar': any; + 'blessed-form': any; + 'blessed-input': any; + 'blessed-textarea': any; + 'blessed-textbox': any; + 'blessed-button': any; + 'blessed-checkbox': any; + 'blessed-radioset': any; + 'blessed-radiobutton': any; + 'blessed-table': any; + 'blessed-prompt': any; + 'blessed-question': any; + 'blessed-message': any; + 'blessed-loading': any; + 'blessed-log': any; + 'blessed-progressbar': any; + 'blessed-program': any; + 'blessed-terminal': any; + 'blessed-layout': any; + 'blessed-escape': any; + } +} diff --git a/types/react-blessed/tsconfig.json b/types/react-blessed/tsconfig.json new file mode 100644 index 0000000000..6195735ac9 --- /dev/null +++ b/types/react-blessed/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, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "react.d.ts", + "react-blessed-tests.tsx" + ] +} diff --git a/types/react-blessed/tslint.json b/types/react-blessed/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-blessed/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-bootstrap/lib/Dropdown.d.ts b/types/react-bootstrap/lib/Dropdown.d.ts index 1568e6cfb5..a3f8220da7 100644 --- a/types/react-bootstrap/lib/Dropdown.d.ts +++ b/types/react-bootstrap/lib/Dropdown.d.ts @@ -1,7 +1,7 @@ import * as React from 'react'; import { SelectCallback } from 'react-bootstrap'; -import * as DropdownToggle from './DropdownToggle'; -import * as DropdownMenu from './DropdownMenu'; +import DropdownToggle = require('./DropdownToggle'); +import DropdownMenu = require('./DropdownMenu'); declare namespace Dropdown { export interface DropdownBaseProps { @@ -26,5 +26,3 @@ declare class Dropdown extends React.Component { public static Toggle: typeof DropdownToggle; } export = Dropdown; - - diff --git a/types/react-bootstrap/lib/index.d.ts b/types/react-bootstrap/lib/index.d.ts index 1b59d08457..4a3c27a59c 100644 --- a/types/react-bootstrap/lib/index.d.ts +++ b/types/react-bootstrap/lib/index.d.ts @@ -208,8 +208,6 @@ export { ButtonToolbarProps, Carousel, CarouselProps, - CarouselCaption, - CarouselCaptionProps, CarouselItem, CarouselItemProps, Checkbox, @@ -226,20 +224,12 @@ export { DropdownProps, DropdownButton, DropdownButtonProps, - DropdownMenu, - DropdownMenuProps, - DropdownToggle, - DropdownToggleProps, Fade, FadeProps, Form, FormProps, FormControl, FormControlProps, - FormControlFeedback, - FormControlFeedbackProps, - FormControlStatic, - FormControlStaticProps, FormGroup, FormGroupProps, Glyphicon, @@ -252,10 +242,6 @@ export { ImageProps, InputGroup, InputGroupProps, - InputGroupAddon, - InputGroupAddonProps, - InputGroupButton, - InputGroupButtonProps, Jumbotron, JumbotronProps, Label, @@ -266,18 +252,6 @@ export { ListGroupItemProps, Media, MediaProps, - MediaBody, - MediaBodyProps, - MediaHeading, - MediaHeadingProps, - MediaLeft, - MediaLeftProps, - MediaList, - MediaListProps, - MediaListItem, - MediaListItemProps, - MediaRight, - MediaRightProps, MenuItem, MenuItemProps, Modal, @@ -298,12 +272,6 @@ export { NavbarProps, NavbarBrand, NavbarBrandProps, - NavbarCollapse, - NavbarCollapseProps, - NavbarHeader, - NavbarHeaderProps, - NavbarToggle, - NavbarToggleProps, NavDropdown, NavDropdownProps, NavItem, @@ -318,26 +286,10 @@ export { PageItemProps, Pager, PagerProps, - PagerItem, - PagerItemProps, Pagination, PaginationProps, - PaginationItem, - PaginationItemProps, Panel, PanelProps, - PanelHeading, - PanelHeadingProps, - PanelTitle, - PanelTitleProps, - PanelToggle, - PanelToggleProps, - PanelCollapse, - PanelCollapseProps, - PanelBody, - PanelBodyProps, - PanelFooter, - PanelFooterProps, PanelGroup, PanelGroupProps, Popover, @@ -354,8 +306,6 @@ export { SafeAnchorProps, SplitButton, SplitButtonProps, - SplitToggle, - SplitToggleProps, Tab, TabProps, TabContainer, diff --git a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx index 9457cea4a2..c2f1e1e9c8 100644 --- a/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx +++ b/types/react-bootstrap/test/react-bootstrap-individual-components-tests.tsx @@ -115,6 +115,7 @@ export class ReactBootstrapIndividualComponentsTest extends React.Component { + +
          + )} + + ); + } +} diff --git a/types/react-countup/tsconfig.json b/types/react-countup/tsconfig.json new file mode 100644 index 0000000000..fb359d894c --- /dev/null +++ b/types/react-countup/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-countup-tests.tsx" + ] +} diff --git a/types/react-countup/tslint.json b/types/react-countup/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-countup/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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 23e542d322..e727155520 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.1 +// Type definitions for react-datepicker 2.0 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -7,11 +7,12 @@ // Roy Xue // 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 interface ReactDatePickerProps { @@ -20,59 +21,65 @@ export interface ReactDatePickerProps { autoComplete?: string; autoFocus?: boolean; calendarClassName?: string; + calendarContainer?(props: { children: React.ReactNode[] }): React.ReactNode; children?: React.ReactNode; className?: 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[]; + 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; 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; 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; + onInputClick?(): void; + onYearChange?(date: Date): void; + onInputError?(err: {code: number; msg: string}): 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; readOnly?: boolean; required?: boolean; scrollableMonthYearDropdown?: boolean; scrollableYearDropdown?: boolean; - selected?: moment.Moment | null; + selected?: Date | null; selectsEnd?: boolean; selectsStart?: boolean; shouldCloseOnSelect?: boolean; @@ -83,21 +90,34 @@ 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; yearDropdownItemNumber?: number; + formatWeekDay?(date: Date): string; + clearButtonTitle?: string; + previousMonthButtonLabel?: string; + nextMonthButtonLabel?: string; + 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; } declare const ReactDatePicker: React.ClassicComponentClass; export default ReactDatePicker; 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..4a3fd93cac 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -1,17 +1,16 @@ import * as React from 'react'; -import * as moment from 'moment'; import DatePicker from 'react-datepicker'; {}} - onYearChange={(date: moment.Moment) => {}} + selected={new Date()} + onChange={(date: Date | null) => {}} + onYearChange={(date: Date) => {}} popperModifiers={{ flip: { enabled: false } }} - includeTimes={[moment()]} + includeTimes={[new Date()]} >
          diff --git a/types/react-dates/index.d.ts b/types/react-dates/index.d.ts index 20739d5918..9e96538f7d 100644 --- a/types/react-dates/index.d.ts +++ b/types/react-dates/index.d.ts @@ -55,6 +55,7 @@ declare namespace ReactDates { screenReaderInputMessage?: string, showClearDates?: boolean, showDefaultInputIcon?: boolean, + inputIconPosition?: IconPositionShape, customInputIcon?: string | JSX.Element, customArrowIcon?: string | JSX.Element, customCloseIcon?: string | JSX.Element, @@ -181,6 +182,7 @@ declare namespace ReactDates { ) => string | JSX.Element, orientation?: OrientationShape, anchorDirection?: AnchorDirectionShape, + openDirection?: OpenDirectionShape, horizontalMargin?: number, withPortal?: boolean, withFullScreenPortal?: boolean, diff --git a/types/react-dom/index.d.ts b/types/react-dom/index.d.ts index c043439768..518c0c617c 100644 --- a/types/react-dom/index.d.ts +++ b/types/react-dom/index.d.ts @@ -5,7 +5,6 @@ // Microsoft // MartynasZilinskas // Josh Rutherford -// JounQin // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -17,7 +16,7 @@ import { DOMAttributes, DOMElement, ReactNode, ReactPortal } from 'react'; -export function findDOMNode(instance: ReactInstance): Element | string | null; +export function findDOMNode(instance: ReactInstance): Element | null | Text; export function unmountComponentAtNode(container: Element): boolean; export function createPortal(children: ReactNode, container: Element, key?: null | string): ReactPortal; diff --git a/types/react-dom/react-dom-tests.tsx b/types/react-dom/react-dom-tests.tsx index ff5ef5850e..c7ccb0052d 100644 --- a/types/react-dom/react-dom-tests.tsx +++ b/types/react-dom/react-dom-tests.tsx @@ -7,7 +7,7 @@ import * as ReactTestUtils from 'react-dom/test-utils'; declare function describe(desc: string, f: () => void): void; declare function it(desc: string, f: () => void): void; -class TestComponent extends React.Component { } +class TestComponent extends React.Component<{x: string}> { } describe('ReactDOM', () => { it('render', () => { diff --git a/types/react-dom/server/index.d.ts b/types/react-dom/server/index.d.ts index 53bbca7250..ef42606717 100644 --- a/types/react-dom/server/index.d.ts +++ b/types/react-dom/server/index.d.ts @@ -1,4 +1,10 @@ -/// +// forward declarations +declare global { + namespace NodeJS { + // tslint:disable-next-line:no-empty-interface + interface ReadableStream {} + } +} import { ReactElement } from 'react'; diff --git a/types/react-dom/test-utils/index.d.ts b/types/react-dom/test-utils/index.d.ts index caa5605ef5..f60d088515 100644 --- a/types/react-dom/test-utils/index.d.ts +++ b/types/react-dom/test-utils/index.d.ts @@ -59,7 +59,7 @@ export interface SyntheticEventData extends OptionalEventProperties { export type EventSimulator = (element: Element | Component, eventData?: SyntheticEventData) => void; export interface MockedComponentClass { - new (props: {}): any; + new (props: any): any; } export interface ShallowRenderer { @@ -160,8 +160,12 @@ export function renderIntoDocument( element: DOMElement): T; export function renderIntoDocument( element: SFCElement): void; -export function renderIntoDocument>( - element: CElement): T; +// If we replace `P` with `any` in this overload, then some tests fail because +// calls to `renderIntoDocument` choose the last overload on the +// subtype-relation pass and get an undesirably broad return type. Using `P` +// allows this overload to match on the subtype-relation pass. +export function renderIntoDocument>( + element: CElement): T; export function renderIntoDocument

          ( element: ReactElement

          ): Component

          | Element | void; @@ -257,7 +261,7 @@ export function findRenderedDOMComponentWithTag( /** * Finds all instances of components with type equal to `componentClass`. */ -export function scryRenderedComponentsWithType( +export function scryRenderedComponentsWithType, C extends ComponentClass>( root: Component, type: ClassType): T[]; @@ -266,7 +270,7 @@ export function scryRenderedComponentsWithType( +export function findRenderedComponentWithType, C extends ComponentClass>( root: Component, type: ClassType): T; diff --git a/types/react-dom/tsconfig.json b/types/react-dom/tsconfig.json index 0d21b07029..f63325026f 100644 --- a/types/react-dom/tsconfig.json +++ b/types/react-dom/tsconfig.json @@ -15,7 +15,7 @@ "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, - "strictFunctionTypes": false, + "strictFunctionTypes": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/react-draft-wysiwyg/index.d.ts b/types/react-draft-wysiwyg/index.d.ts new file mode 100644 index 0000000000..a5c6e07065 --- /dev/null +++ b/types/react-draft-wysiwyg/index.d.ts @@ -0,0 +1,74 @@ +// Type definitions for react-draft-wysiwyg 1.12 +// Project: https://github.com/jpuri/react-draft-wysiwyg#readme +// Definitions by: imechZhangLY +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import * as Draft from 'draft-js'; + +export type SyntheticKeyboardEvent = React.KeyboardEvent<{}>; +export type SyntheticEvent = React.SyntheticEvent<{}>; +export type RawDraftContentState = Draft.RawDraftContentState; + +export class EditorState extends Draft.EditorState {} +export class ContentState extends Draft.ContentState {} +export class ContentBlock extends Draft.ContentBlock {} +export class SelectionState extends Draft.SelectionState {} + +export interface EditorProps { + onChange?(contentState: ContentState): RawDraftContentState; + onEditorStateChange?(editorState: EditorState): void; + onContentStateChange?(contentState: ContentState): RawDraftContentState; + initialContentState?: RawDraftContentState; + defaultContentState?: RawDraftContentState; + contentState?: RawDraftContentState; + editorState?: EditorState; + defaultEditorState?: EditorState; + toolbarOnFocus?: boolean; + spellCheck?: boolean; + stripPastedStyles?: boolean; + toolbar?: object; + toolbarCustomButtons?: Array>; + toolbarClassName?: string; + toolbarHidden?: boolean; + locale?: string; + localization?: object; + editorClassName?: string; + wrapperClassName?: string; + toolbarStyle?: object; + editorStyle?: React.CSSProperties; + wrapperStyle?: React.CSSProperties; + uploadCallback?(file: object): Promise; + onFocus?(event: SyntheticEvent): void; + onBlur?(event: SyntheticEvent): void; + onTab?(event: SyntheticKeyboardEvent): void; + onEscape?(e: SyntheticKeyboardEvent): void; + onUpArrow?(e: SyntheticKeyboardEvent): void; + onDownArrow?(e: SyntheticKeyboardEvent): void; + onRightArrow?(e: SyntheticKeyboardEvent): void; + onLeftArrow?(e: SyntheticKeyboardEvent): void; + mention?: object; + hashtag?: object; + textAlignment?: string; + readonly?: boolean; + tabIndex?: number; + placeholder?: string; + ariaLabel?: string; + ariaOwneeID?: string; + ariaActiveDescendantID?: string; + ariaAutoComplete?: string; + ariaDescribedBy?: string; + ariaExpanded?: string; + ariaHasPopup?: string; + customBlockRenderFunc?(block: ContentBlock): any; + wrapperId?: number; + customDecorators?: object[]; + editorRef?(ref: object): void; + handlePastedText?(text: string, html: string, editorState: EditorState, onChange: (editorState: EditorState) => void): boolean; +} + +export class Editor extends React.Component { + constructor(props: Readonly); + focusEditor(): void; +} diff --git a/types/react-draft-wysiwyg/test/basic-content-state-tests.tsx b/types/react-draft-wysiwyg/test/basic-content-state-tests.tsx new file mode 100644 index 0000000000..5693ff2584 --- /dev/null +++ b/types/react-draft-wysiwyg/test/basic-content-state-tests.tsx @@ -0,0 +1,42 @@ +// From https://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Editor, RawDraftContentState } from 'react-draft-wysiwyg'; + +class BasicContentState extends React.Component<{}, {contentState: RawDraftContentState}> { + constructor(props: any) { + super(props); + this.state = { + contentState: JSON + .parse(`{ + "entityMap":{}, + "blocks":[{ + "key":"1ljs", + "text":"Initializing from content state", + "type":"unstyled", + "depth":0, + "inlineStyleRanges":[], + "entityRanges":[], + "data":{} + }] + }`) + }; + } + + render() { + const {contentState} = this.state; + return (
          + Content state is JSON +
          +                {'{"entityMap":{},"blocks":[{"key":"1ljs","text":"Initializing from content state","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}}]}'}
          +                
          +
          + +
          ); + } +} + +ReactDOM.render(, document.getElementById('target')); diff --git a/types/react-draft-wysiwyg/test/basic-controlled-tests.tsx b/types/react-draft-wysiwyg/test/basic-controlled-tests.tsx new file mode 100644 index 0000000000..1b5987d331 --- /dev/null +++ b/types/react-draft-wysiwyg/test/basic-controlled-tests.tsx @@ -0,0 +1,30 @@ +// From https://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Editor, EditorState } from 'react-draft-wysiwyg'; + +class BasicControlled extends React.Component<{}, {editorState: EditorState}> { + constructor(props: any) { + super(props); + this.state = { + editorState: EditorState.createEmpty() + }; + } + + render() { + const {editorState} = this.state; + return (
          + +
          ); + } + + onEditorStateChange(editorState: EditorState): void { + this.setState({editorState}); + } +} + +ReactDOM.render(, document.getElementById('target')); diff --git a/types/react-draft-wysiwyg/test/basic-tests.tsx b/types/react-draft-wysiwyg/test/basic-tests.tsx new file mode 100644 index 0000000000..30121f122a --- /dev/null +++ b/types/react-draft-wysiwyg/test/basic-tests.tsx @@ -0,0 +1,15 @@ +// From https://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Editor } from 'react-draft-wysiwyg'; + +const Basic = () => (
          + { + console.log('hey ref', ref.focusEditor.toString()); + }} + /> +
          ); + +ReactDOM.render(, document.getElementById('target')); diff --git a/types/react-draft-wysiwyg/test/custom-toolbar-tests.tsx b/types/react-draft-wysiwyg/test/custom-toolbar-tests.tsx new file mode 100644 index 0000000000..8dd5662bda --- /dev/null +++ b/types/react-draft-wysiwyg/test/custom-toolbar-tests.tsx @@ -0,0 +1,35 @@ +// From https://github.com/jpuri/react-draft-wysiwyg/blob/master/stories/ + +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Editor } from 'react-draft-wysiwyg'; +import { RichUtils } from 'draft-js'; + +class CustomOption extends React.Component { + toggleBold(): void { + const {editorState, onChange} = this.props; + const newState = RichUtils.toggleInlineStyle( + editorState, + 'BOLD', + ); + if (newState) { + onChange(newState); + } + } + + render() { + return ( +
          B
          + ); + } +} + +const CustomToolbar = () => + (
          +

          Last option marked as B is custom option for making test BOLD.

          + ]} + /> +
          ); + +ReactDOM.render(, document.getElementById('target')); diff --git a/types/react-draft-wysiwyg/test/focus-blur-callbacks-tests.tsx b/types/react-draft-wysiwyg/test/focus-blur-callbacks-tests.tsx new file mode 100644 index 0000000000..d29f7ab073 --- /dev/null +++ b/types/react-draft-wysiwyg/test/focus-blur-callbacks-tests.tsx @@ -0,0 +1,42 @@ +import * as React from 'react'; +import * as ReactDOM from 'react-dom'; +import { Editor } from 'react-draft-wysiwyg'; + +class FocusBlurCallbacks extends React.Component { + constructor(props: any) { + super(props); + + this.state = { + state: 'blurred' + }; + } + + onFocus(): void { + console.log('into onFocus'); + this.setState({ + state: 'focused', + }); + } + + onBlur(): void { + console.log('into onBlur'); + this.setState({ + state: 'blurred', + }); + } + + render() { + const { state } = this.state; + return ( +
          +

          State right now {state}

          + +
          + ); + } +} + +ReactDOM.render(, document.getElementById('target')); diff --git a/types/react-draft-wysiwyg/tsconfig.json b/types/react-draft-wysiwyg/tsconfig.json new file mode 100644 index 0000000000..35720c1979 --- /dev/null +++ b/types/react-draft-wysiwyg/tsconfig.json @@ -0,0 +1,29 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true, + "jsx": "preserve" + }, + "files": [ + "index.d.ts", + "test/basic-content-state-tests.tsx", + "test/basic-controlled-tests.tsx", + "test/basic-tests.tsx", + "test/custom-toolbar-tests.tsx", + "test/focus-blur-callbacks-tests.tsx" + ] +} diff --git a/types/react-draft-wysiwyg/tslint.json b/types/react-draft-wysiwyg/tslint.json new file mode 100644 index 0000000000..6746359dda --- /dev/null +++ b/types/react-draft-wysiwyg/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-facebook-login-component/index.d.ts b/types/react-facebook-login-component/index.d.ts new file mode 100644 index 0000000000..6de3d2e0eb --- /dev/null +++ b/types/react-facebook-login-component/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-facebook-login-component 4.1 +// Project: https://github.com/kennetpostigo/react-facebook-login-component +// Definitions by: Konstantin Lebedev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface FacebookLoginInfo { + id: string; + accessToken: string; + name?: string; + email?: string; +} + +export interface FacebookLoginProps extends React.ButtonHTMLAttributes { + socialId: string; + xfbml?: boolean; + version?: string; + fields?: string; + buttonText?: string; + responseHandler: (response: FacebookLoginInfo) => void; +} + +export class FacebookLogin extends React.Component {} diff --git a/types/react-facebook-login-component/react-facebook-login-component-tests.tsx b/types/react-facebook-login-component/react-facebook-login-component-tests.tsx new file mode 100644 index 0000000000..ee9730d6c4 --- /dev/null +++ b/types/react-facebook-login-component/react-facebook-login-component-tests.tsx @@ -0,0 +1,24 @@ +import { FacebookLogin, FacebookLoginInfo } from "react-facebook-login-component"; +import * as React from "react"; + +const handler = (response: FacebookLoginInfo) => { + console.log(response.accessToken); +}; + +const ReactFacebookLoginComponent: JSX.Element = ( + +); + +const ReactFacebookLoginComponentAllOptions: JSX.Element = ( + +); diff --git a/types/react-facebook-login-component/tsconfig.json b/types/react-facebook-login-component/tsconfig.json new file mode 100644 index 0000000000..f5c4eb981d --- /dev/null +++ b/types/react-facebook-login-component/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-facebook-login-component-tests.tsx" + ] +} diff --git a/types/react-facebook-login-component/tslint.json b/types/react-facebook-login-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-facebook-login-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-flag-icon-css/index.d.ts b/types/react-flag-icon-css/index.d.ts index 74c3e04efe..dccdd59076 100644 --- a/types/react-flag-icon-css/index.d.ts +++ b/types/react-flag-icon-css/index.d.ts @@ -55,9 +55,8 @@ export interface FlagIconProps { children?: ReactNode; } -export class FlagIcon extends PureComponent { -} +export class FlagIcon extends PureComponent {} -export default function FlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; +export default function FlagIconFactory(react: any, opts?: Readonly): typeof FlagIcon; -export function CustomFlagIconFactory(react: any, opts?: Readonly): (props: FlagIconProps) => FlagIcon; +export function CustomFlagIconFactory(react: any, opts?: Readonly): typeof FlagIcon; diff --git a/types/react-flag-icon-css/react-flag-icon-css-tests.tsx b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx index 5b656cff7b..0c939967b0 100644 --- a/types/react-flag-icon-css/react-flag-icon-css-tests.tsx +++ b/types/react-flag-icon-css/react-flag-icon-css-tests.tsx @@ -81,8 +81,6 @@ export class ChildrenFlagComponent extends React.PureComponent }; ReactDOM.render(, rootEL); 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-foundation/tslint.json b/types/react-foundation/tslint.json index 0e4acb22ee..6b376d1fe2 100644 --- a/types/react-foundation/tslint.json +++ b/types/react-foundation/tslint.json @@ -1,12 +1,14 @@ { "extends": "dtslint/dt.json", "rules": { + // All are TODOs "strict-export-declare-modifiers": false, "no-trailing-whitespace": false, "jsdoc-format": false, "no-reference-import": false, "prefer-declare-function": false, "no-duplicate-imports": false, - "no-empty-interface": false + "no-empty-interface": false, + "no-redundant-jsdoc-2": false } } diff --git a/types/react-google-login-component/index.d.ts b/types/react-google-login-component/index.d.ts new file mode 100644 index 0000000000..272b198657 --- /dev/null +++ b/types/react-google-login-component/index.d.ts @@ -0,0 +1,24 @@ +// Type definitions for react-google-login-component 0.9 +// Project: https://github.com/kennetpostigo/react-google-login-component +// Definitions by: Konstantin Lebedev +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +export interface GoogleLoginInfo { + getAuthResponse: () => { + access_token: string; + }; +} + +export interface GoogleLoginProps extends React.ButtonHTMLAttributes { + socialId: string; + scope?: string; + fetchBasicProfile?: boolean; + buttonText?: string; + prompt?: string; + responseHandler: (response: GoogleLoginInfo) => void; +} + +export class GoogleLogin extends React.Component {} diff --git a/types/react-google-login-component/react-google-login-component-tests.tsx b/types/react-google-login-component/react-google-login-component-tests.tsx new file mode 100644 index 0000000000..e4566071fa --- /dev/null +++ b/types/react-google-login-component/react-google-login-component-tests.tsx @@ -0,0 +1,24 @@ +import { GoogleLogin, GoogleLoginInfo } from "react-google-login-component"; +import * as React from "react"; + +const handler = (response: GoogleLoginInfo) => { + console.log(response.getAuthResponse().access_token); +}; + +const ReactGoogleLoginComponent: JSX.Element = ( + +); + +const ReactGoogleLoginComponentAllOptions: JSX.Element = ( + +); diff --git a/types/react-google-login-component/tsconfig.json b/types/react-google-login-component/tsconfig.json new file mode 100644 index 0000000000..506e9f7e7f --- /dev/null +++ b/types/react-google-login-component/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "target": "es6", + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-google-login-component-tests.tsx" + ] +} diff --git a/types/react-google-login-component/tslint.json b/types/react-google-login-component/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-google-login-component/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-gravatar/index.d.ts b/types/react-gravatar/index.d.ts index b2962edc8d..56e48b3b9b 100644 --- a/types/react-gravatar/index.d.ts +++ b/types/react-gravatar/index.d.ts @@ -25,7 +25,7 @@ declare namespace Gravatar { type DefaultImage = "404" | "mm" | "identicon" | "monsterid" | "wavatar" | "retro" | "blank"; type Rating = "g" | "pg" | "r" | "x"; - interface Props { + interface Props extends Partial { /** * The email address used to look up the Gravatar image. * If you wish to avoid sending an email address to the client, you can compute the md5 hash on the server and diff --git a/types/react-helmet/v4/index.d.ts b/types/react-helmet/v4/index.d.ts index 4d1b0c699e..eddd354124 100644 --- a/types/react-helmet/v4/index.d.ts +++ b/types/react-helmet/v4/index.d.ts @@ -8,7 +8,7 @@ import * as React from "react"; -declare function ReactHelmet(): ReactHelmet.HelmetComponent; +declare class ReactHelmet extends React.Component {} declare namespace ReactHelmet { function peek(): ReactHelmet.HelmetData; @@ -41,8 +41,6 @@ declare namespace ReactHelmet { toString(): string; toComponent(): React.Component; } - - class HelmetComponent extends React.Component {} } export = ReactHelmet; diff --git a/types/react-i18next/index.d.ts b/types/react-i18next/index.d.ts deleted file mode 100644 index 979c648f50..0000000000 --- a/types/react-i18next/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Type definitions for react-i18next 7.8 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Giedrius Grabauskas -// Simon Baumann -// Benedict Etzel -// Wu Haotian -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { TranslationFunction } from "i18next"; - -import { - setDefaults, - getDefaults, - setI18n, - getI18n, - ReactI18NextOptions, - reactI18nextModule -} from "./src/context"; -import I18n from "./src/I18n"; -import I18nextProvider from "./src/I18nextProvider"; -import Interpolate from "./src/interpolate"; -import loadNamespaces from "./src/loadNamespaces"; -import Trans from "./src/trans"; -import translate from "./src/translate"; - -export { - setDefaults, - getDefaults, - setI18n, - getI18n, - ReactI18NextOptions, - reactI18nextModule, - I18n, - I18nextProvider, - Interpolate, - loadNamespaces, - Trans, - translate, - TranslationFunction -}; - -export { InjectedI18nProps, InjectedTranslateProps } from "./src/props"; - -export as namespace reactI18Next; diff --git a/types/react-i18next/src/I18n.d.ts b/types/react-i18next/src/I18n.d.ts deleted file mode 100644 index 91de868caf..0000000000 --- a/types/react-i18next/src/I18n.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -import * as React from "react"; -import { i18n, TranslationFunction } from "i18next"; - -export interface Options { - i18n: i18n; - t: TranslationFunction; -} - -export interface i18nProps { - wait?: boolean; - ns?: string | string[]; - nsMode?: string; - bindI18n?: string; - bindStore?: string; - i18n?: i18n; - initialI18nStore?: any; - initialLanguage?: string; - children: (t: TranslationFunction, options: Options) => React.ReactNode; -} - -export default class I18n extends React.Component { } diff --git a/types/react-i18next/src/I18nextProvider.d.ts b/types/react-i18next/src/I18nextProvider.d.ts deleted file mode 100644 index 2db5d0361b..0000000000 --- a/types/react-i18next/src/I18nextProvider.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -// tslint:disable-next-line:interface-name -export interface I18nextProviderProps { - i18n: i18n; - initialI18nStore?: any; - initialLanguage?: string; - children: React.ReactNode; -} - -export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/src/context.d.ts b/types/react-i18next/src/context.d.ts deleted file mode 100644 index f772e8c1da..0000000000 --- a/types/react-i18next/src/context.d.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { i18n } from "i18next"; - -export interface ReactI18NextOptions { - wait?: boolean; - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: string; - nsMode?: string; -} - -export function setDefaults(options: ReactI18NextOptions): void; - -export function getDefaults(): ReactI18NextOptions; - -export function setI18n(instance: i18n): void; - -export function getI18n(): i18n; - -export interface i18NextModule { - type: string; - - init: (instance: i18n) => void; -} - -export const reactI18nextModule: i18NextModule; diff --git a/types/react-i18next/src/interpolate.d.ts b/types/react-i18next/src/interpolate.d.ts deleted file mode 100644 index d6a4e64420..0000000000 --- a/types/react-i18next/src/interpolate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n, InterpolationOptions, TranslationFunction } from "i18next"; - -export type InterpolateValue = string | JSX.Element; - -export interface InterpolatePropsBase { - parent?: string; - regexp?: RegExp; - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - options?: InterpolationOptions; - i18nKey?: string; - className?: string; - style?: React.CSSProperties; - i18n?: i18n; - t?: TranslationFunction; -} - -export interface OtherInterpolateProps { - [regexKey: string]: InterpolateValue | RegExp | InterpolationOptions | boolean | undefined; -} - -export type InterpolateProps = InterpolatePropsBase & OtherInterpolateProps; - -export default class Interpolate extends React.PureComponent { } diff --git a/types/react-i18next/src/loadNamespaces.d.ts b/types/react-i18next/src/loadNamespaces.d.ts deleted file mode 100644 index d0e0b372f5..0000000000 --- a/types/react-i18next/src/loadNamespaces.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -export interface LoadNamespacesArguments { - components: Array | React.StatelessComponent>; - i18n: i18n; -} - -export default function loadNamespaces(args: LoadNamespacesArguments): Promise; diff --git a/types/react-i18next/src/props.d.ts b/types/react-i18next/src/props.d.ts deleted file mode 100644 index 62a201049a..0000000000 --- a/types/react-i18next/src/props.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -import {i18n as I18n, TranslationFunction} from "i18next"; - -/** - * Extend your component's Prop interface with this one to get access to `this.props.t` - * - * Please note that if you use the `translateFuncName` option, you should create - * your own interface just like this one, but with your name of the translation function. - * - * interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} - * - * Then specify the name of the translate function as generic argument - * - * const translated = translate("view", { translateFuncName: "_" })(YourComponent); - */ -export interface InjectedTranslateProps { - t: TranslationFunction; -} - -/** - * Extend your component's Prop interface with this one to get access to `this.props.i18n` - */ -export interface InjectedI18nProps { - i18n: I18n -} diff --git a/types/react-i18next/src/trans.d.ts b/types/react-i18next/src/trans.d.ts deleted file mode 100644 index 2b0e8e7738..0000000000 --- a/types/react-i18next/src/trans.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n, TranslationFunction } from "i18next"; - -export interface TOptions { - [key: string]: any; -} - -export interface Values { - [key: string]: any; -} - -export interface TransProps { - i18nKey?: string; - count?: number; - parent?: React.ReactNode | (() => React.ReactNode); - i18n?: i18n; - t?: TranslationFunction; - tOptions?: TOptions; - defaults?: string; - values?: Values; - components?: React.ReactNode[]; - ns?: string; -} - -export default class Trans extends React.Component { } diff --git a/types/react-i18next/src/translate.d.ts b/types/react-i18next/src/translate.d.ts deleted file mode 100644 index 0383ee1ead..0000000000 --- a/types/react-i18next/src/translate.d.ts +++ /dev/null @@ -1,63 +0,0 @@ -import * as React from "react"; -import { i18n as I18n, TranslationFunction } from "i18next"; -import { InjectedTranslateProps, InjectedI18nProps } from "./props"; -import { setDefaults, setI18n } from "./context"; - -export interface TranslateOptions { - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: TTranslateFuncName; - wait?: boolean; - nsMode?: string; - i18n?: I18n; -} - -export interface TranslateHocProps { - i18n?: I18n; - initialI18nStore?: object; - initialLanguage?: string; -} - -// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 -type Omit = Pick; - -type InjectedProps = InjectedI18nProps & InjectedTranslateProps; - -export interface WrapperComponentClass

          extends React.ComponentClass

          { - new (props: P, context?: any): React.Component

          & { getWrappedInstance(): React.Component }; -} - -// Injects props and removes them from the prop requirements. -// Adds the new properties t (or whatever the translation function is called) and i18n if needed. -export type InferableComponentEnhancerWithProps = -

          (component: React.ComponentClass

          | React.StatelessComponent

          ) => - React.ComponentClass & TranslateHocProps>; - -export type InferableComponentEnhancerWithPropsAndRef = -

          (component: React.ComponentClass

          | React.StatelessComponent

          ) => - WrapperComponentClass, P>; - -export interface Translate { - - (namespaces?: TNamespace | TNamespace[], options?: Omit & { withRef?: false }): - InferableComponentEnhancerWithProps<"t">; - - - (namespaces?: TNamespace | TNamespace[], options?: Omit & { withRef: true }): - InferableComponentEnhancerWithPropsAndRef<"t">; - - - (namespaces?: TNamespace | TNamespace[], options?: TranslateOptions & { withRef?: false }): - InferableComponentEnhancerWithProps; - - - (namespaces?: TNamespace | TNamespace[], options?: TranslateOptions & { withRef: true }): - InferableComponentEnhancerWithPropsAndRef; - - setDefaults: typeof setDefaults; - setI18n: typeof setI18n; -} - -declare const translate: Translate; -export default translate; diff --git a/types/react-i18next/test/react-i18next-tests.tsx b/types/react-i18next/test/react-i18next-tests.tsx deleted file mode 100644 index 30b95ece24..0000000000 --- a/types/react-i18next/test/react-i18next-tests.tsx +++ /dev/null @@ -1,201 +0,0 @@ -import * as React from 'react'; -import * as i18n from 'i18next'; -import { - setDefaults, - reactI18nextModule, - translate, - I18nextProvider, - Interpolate, - InjectedTranslateProps, - TranslationFunction, - loadNamespaces, - Trans, - I18n, - ReactI18NextOptions -} from 'react-i18next'; -import { InjectedI18nProps } from 'react-i18next/src/props'; - -interface InnerAnotherComponentProps { - _: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._; - return

          {_('content.text', {/* options t options */})}

          ; - } -} - -const AnotherComponent = translate('view', {wait: true, translateFuncName: '_'})(InnerAnotherComponent); -const instanceWithoutRef = new AnotherComponent({}); -instanceWithoutRef.componentWillReceiveProps!({ - i18n, - initialI18nStore: { context: { text: "a message" } }, - initialLanguage: "en" -}, {}); - -translate.setDefaults({ wait: false }); -translate.setI18n(i18n); - -const AnotherComponentWithRef = translate("view" as Key, { translateFuncName: "_", withRef: true })(InnerAnotherComponent); -const instanceWithRef = new AnotherComponentWithRef({}); -const ref = instanceWithRef.getWrappedInstance(); -instanceWithRef.componentWillReceiveProps!({ - i18n, - initialI18nStore: { context: { text: "a message" } }, - initialLanguage: "en" -}, {}); - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t; - return

          {t('usingDefaultNS', {/* options t options */})}

          ; - } -} - -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - -const YetAnotherComponentWithRef = translate(undefined, { withRef: true })(InnerYetAnotherComponent); -new YetAnotherComponentWithRef({}).getWrappedInstance(); -class TranslatableView extends React.Component { - render() { - const t = this.props.t; - const interpolateComponent = "a interpolated component"; - const options: i18n.InterpolationOptions = {}; - return ( -
          -

          {t('common:appName')}

          - - - - - {t('nav:link1')} -
          - ); - } -} - -const TranslatedView = translate(["view", "nav"] as Key[], { wait: true })(TranslatableView); - -class App extends React.Component { - render() { - return ( -
          -
          - -
          -
          - ); - } -} - - - -; - - - 123 -; - -loadNamespaces({components: [App], i18n}).then(() => { -}).catch(error => { -}); - -; -; -; -}/>; -
          }/>; -; -; - - -; -; -placeholder - ]} - values={{ - universe: "World" - }} -/>; - -type Key = "view" | "nav"; - -class GenericsTest extends React.Component { - render() { - return null; - } -} - -const TranslatedGenericsTest = translate(["view", "nav"] as Key[])(GenericsTest); -; - -class GenericsTest2 extends React.Component { - render() { - return null; - } -} - -const TranslatedGenericsTest2 = translate("view" as Key)(GenericsTest2); -; - -class ComponentWithInjectedI18n extends React.Component { - render() { return null; } -} - -const TranslatedComponentWithInjectedI18n = translate()(ComponentWithInjectedI18n); -; - -function StatlessComponent(props: InjectedTranslateProps) { - return

          {props.t("hy")}

          ; -} - -const TranslatedStatlessComponent = translate()(StatlessComponent); -; - -interface CustomTranslateFunctionProps { - _: TranslationFunction; -} - - - { - (t, {i18n}) => ( -
          -

          {t('keyFromDefault')}

          -

          {t('anotherNamespace:key.from.another.namespace', {/* options t options */})}

          -
          - ) - } -
          ; - - - {t => '123'} -; - -const defaults: ReactI18NextOptions = { - wait: true, - withRef: true, - bindI18n: 'string', - bindStore: 'string' -}; -setDefaults(defaults); - -reactI18nextModule.init(i18n.init()); diff --git a/types/react-i18next/v1/index.d.ts b/types/react-i18next/v1/index.d.ts deleted file mode 100644 index 0296da861c..0000000000 --- a/types/react-i18next/v1/index.d.ts +++ /dev/null @@ -1,57 +0,0 @@ -// Type definitions for react-i18next 1.7.0 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Kostya Esmukov -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import * as I18next from "i18next"; -import * as React from "react"; - -export type TranslationFunction = I18next.TranslationFunction; - -// Extend your component's Prop interface with this one to get access to `this.props.t` -// -// Please note that if you use the `translateFuncName` option, you should create -// your own interface just like this one, but with your name of the translation function. -// -// interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} -export interface InjectedTranslateProps { - t?: TranslationFunction; -} - -interface I18nextProviderProps { - i18n: I18next.I18n; - children?: React.ReactElement; -} - -export class I18nextProvider extends React.Component { } - - -type InterpolateValue = string | JSX.Element; - -interface InterpolateProps { - i18nKey: string; - - parent?: string; - regexp?: RegExp; - options?: I18next.TranslationOptions; - - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - - [regexKey: string]: InterpolateValue | RegExp | I18next.TranslationOptions | boolean | undefined; -} - -export class Interpolate extends React.Component { } - -interface TranslateOptions { - withRef?: boolean; - wait?: boolean; - translateFuncName?: string; -} - -export function translate(namespaces?: string[] | string, options?: TranslateOptions): (WrappedComponent: C) => C; - -export function loadNamespaces({ components, i18n }: { components: (React.ComponentClass | React.StatelessComponent)[], i18n: I18next.I18n }): Promise; - -export as namespace ReactI18Next; diff --git a/types/react-i18next/v1/react-i18next-tests.tsx b/types/react-i18next/v1/react-i18next-tests.tsx deleted file mode 100644 index 950e29d293..0000000000 --- a/types/react-i18next/v1/react-i18next-tests.tsx +++ /dev/null @@ -1,103 +0,0 @@ -import * as ReactDOM from 'react-dom'; -import * as React from 'react'; -import * as i18n from 'i18next'; -import { translate, I18nextProvider, Interpolate, InjectedTranslateProps, TranslationFunction } from 'react-i18next'; - - -i18n - .init({ - fallbackLng: 'en', - - // have a common namespace used around the full app - ns: ['common'], - defaultNS: 'common', - - debug: true, - - interpolation: { - escapeValue: false // not needed for react!! - } - }); - - -interface InnerAnotherComponentProps { - _?: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._!; - - return

          {_('content.text', { /* options t options */ })}

          ; - } -} - -const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' })(InnerAnotherComponent); - - - -interface InnerYetAnotherComponentProps extends InjectedTranslateProps { -} - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t!; - - return

          {t('usingDefaultNS', { /* options t options */ })}

          ; - } -} -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - - -interface TranslatableViewProps extends InjectedTranslateProps { -} - -@translate(['view', 'nav'], { wait: true }) -class TranslatableView extends React.Component { - render() { - const t = this.props.t!; - - let interpolateComponent = "a interpolated component"; - - return ( -
          -

          {t('common:appName')}

          - - - - - {t('nav:link1')} -
          - ) - } -} - -class App extends React.Component { - render() { - return ( -
          -
          - -
          -
          - ); - } -} - - -ReactDOM.render( - , - document.getElementById('app') -); diff --git a/types/react-i18next/v4/I18nextProvider.d.ts b/types/react-i18next/v4/I18nextProvider.d.ts deleted file mode 100644 index 2ecb87f4a1..0000000000 --- a/types/react-i18next/v4/I18nextProvider.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -// tslint:disable-next-line:interface-name -export interface I18nextProviderProps { - i18n: i18n; - children: React.ReactElement; - initialI18nStore?: any; - initialLanguage?: string; -} - -export default class I18nextProvider extends React.Component { } diff --git a/types/react-i18next/v4/index.d.ts b/types/react-i18next/v4/index.d.ts deleted file mode 100644 index 758a00edef..0000000000 --- a/types/react-i18next/v4/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for react-i18next 4.6 -// Project: https://github.com/i18next/react-i18next -// Definitions by: Giedrius Grabauskas -// Netanel Gilad -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 - -import { TranslationFunction } from "i18next"; - -import I18nextProvider from "./I18nextProvider"; -import Interpolate from "./interpolate"; -import loadNamespaces from "./loadNamespaces"; -import Trans from "./trans"; -import translate from "./translate"; - -export { - I18nextProvider, - Interpolate, - loadNamespaces, - Trans, - translate, - // Exports for TypeScript only - TranslationFunction -}; - -/** - * Extend your component's Prop interface with this one to get access to `this.props.t` - * - * Please note that if you use the `translateFuncName` option, you should create - * your own interface just like this one, but with your name of the translation function. - * - * interface MyComponentProps extends ReactI18next.InjectedTranslateProps {} - */ -export interface InjectedTranslateProps { - t: TranslationFunction; -} - -export as namespace reactI18Next; diff --git a/types/react-i18next/v4/interpolate.d.ts b/types/react-i18next/v4/interpolate.d.ts deleted file mode 100644 index e6f07893ed..0000000000 --- a/types/react-i18next/v4/interpolate.d.ts +++ /dev/null @@ -1,23 +0,0 @@ -import * as React from "react"; -import { InterpolationOptions } from "i18next"; - -export type InterpolateValue = string | JSX.Element; - -export interface InterpolatePropsBase { - parent?: string; - regexp?: RegExp; - useDangerouslySetInnerHTML?: boolean; - dangerouslySetInnerHTMLPartElement?: string; - options?: InterpolationOptions; - i18nKey?: string; - className?: string; - style?: React.CSSProperties; -} - -export interface OtherInterpolateProps { - [regexKey: string]: InterpolateValue | RegExp | InterpolationOptions | boolean | undefined; -} - -export type InterpolateProps = InterpolatePropsBase & OtherInterpolateProps; - -export default class Interpolate extends React.Component { } diff --git a/types/react-i18next/v4/loadNamespaces.d.ts b/types/react-i18next/v4/loadNamespaces.d.ts deleted file mode 100644 index d0e0b372f5..0000000000 --- a/types/react-i18next/v4/loadNamespaces.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; - -export interface LoadNamespacesArguments { - components: Array | React.StatelessComponent>; - i18n: i18n; -} - -export default function loadNamespaces(args: LoadNamespacesArguments): Promise; diff --git a/types/react-i18next/v4/react-i18next-tests.tsx b/types/react-i18next/v4/react-i18next-tests.tsx deleted file mode 100644 index 3e57dd091b..0000000000 --- a/types/react-i18next/v4/react-i18next-tests.tsx +++ /dev/null @@ -1,95 +0,0 @@ -import * as React from 'react'; -import * as i18n from 'i18next'; -import { translate, I18nextProvider, Interpolate, InjectedTranslateProps, TranslationFunction, loadNamespaces, Trans } from 'react-i18next'; - -interface InnerAnotherComponentProps { - _?: TranslationFunction; -} - -class InnerAnotherComponent extends React.Component { - render() { - const _ = this.props._!; - return

          {_('content.text', { /* options t options */ })}

          ; - } -} - -const AnotherComponent = translate('view', { wait: true, translateFuncName: '_' })(InnerAnotherComponent); - -class InnerYetAnotherComponent extends React.Component { - render() { - const t = this.props.t; - return

          {t('usingDefaultNS', { /* options t options */ })}

          ; - } -} - -const YetAnotherComponent = translate()(InnerYetAnotherComponent); - -class TranslatableView extends React.Component { - render() { - const t = this.props.t; - const interpolateComponent = "a interpolated component"; - - return ( -
          -

          {t('common:appName')}

          - - - - - {t('nav:link1')} -
          - ); - } -} - -const WrappedTranslatableView = translate(['view', 'nav'], { wait: true })(TranslatableView); - -class App extends React.Component { - render() { - return ( -
          -
          - -
          -
          - ); - } -} - - - -; - -loadNamespaces({ components: [App], i18n }).then(() => { }).catch(error => { }); - -; -; - - -; - -type Key = "view" | "nav"; - -class GenericsTest extends React.Component { - render() { return null; } -} - -translate(['view', 'nav'])(GenericsTest); - -class GenericsTest2 extends React.Component { - render() { return null; } -} - -translate('view')(GenericsTest2); diff --git a/types/react-i18next/v4/trans.d.ts b/types/react-i18next/v4/trans.d.ts deleted file mode 100644 index 384e1605f9..0000000000 --- a/types/react-i18next/v4/trans.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -import * as React from "react"; - -export interface TransProps { - i18nKey?: string; - [name: string]: any; -} - -export default class Trans extends React.Component { } diff --git a/types/react-i18next/v4/translate.d.ts b/types/react-i18next/v4/translate.d.ts deleted file mode 100644 index 9a4fb6ddc2..0000000000 --- a/types/react-i18next/v4/translate.d.ts +++ /dev/null @@ -1,25 +0,0 @@ -import * as React from "react"; -import { i18n } from "i18next"; -import { InjectedTranslateProps } from "react-i18next"; - -export interface TranslateOptions { - withRef?: boolean; - bindI18n?: string; - bindStore?: string; - translateFuncName?: string; - wait?: boolean; - nsMode?: string; - i18n?: i18n; -} - -// Diff / Omit taken from https://github.com/Microsoft/TypeScript/issues/12215#issuecomment-311923766 -export type Omit = Pick; - -// Injects props and removes them from the prop requirements. -// Adds the new properties t (or whatever the translation function is called) and i18n if needed. -export type InferableComponentEnhancerWithProps = -

          (component: React.ComponentClass

          | React.StatelessComponent

          ) => - React.ComponentClass>; - -// tslint:disable-next-line:ban-types -export default function translate(namespaces?: TKey[] | TKey, options?: TranslateOptions): InferableComponentEnhancerWithProps<"t">; diff --git a/types/react-images/index.d.ts b/types/react-images/index.d.ts new file mode 100644 index 0000000000..4f3e1c8893 --- /dev/null +++ b/types/react-images/index.d.ts @@ -0,0 +1,157 @@ +// Type definitions for react-images 0.5 +// Project: http://jossmac.github.io/react-images +// Definitions by: Konstantin Lukaschenko +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +declare class Lightbox extends React.Component { + constructor(props: LightboxProps); +} + +export interface LightboxProps { + /** + * Array of image objects. Required. + */ + images: Image[]; + + /** + * Allow users to exit the lightbox by clicking the backdrop. Default value: false. + */ + backdropClosesModal?: boolean; + + /** + * Supports keyboard input - esc, arrow left, and arrow right. Default value: true + */ + enableKeyboardInput?: boolean; + + /** + * The index of the image to display initially. Default value: 0 + */ + currentImage?: number; + + /** + * An array of elements to display as custom controls on the top of lightbox. Default value: undefined + */ + customControls?: Array>; + + /** + * Whether or not the lightbox is displayed. Default value: false; + */ + isOpen?: boolean; + + /** + * Based on the direction the user is navigating, preload the next available image. Default value: true + */ + preloadNextImage?: boolean; + + /** + * Optionally display a close "X" button in top right corner. Default value: true + */ + showCloseButton?: boolean; + + /** + * Optionally display image index, e.g., "3 of 20". Default value: true + */ + showImageCount?: boolean; + + /** + * Maximum width of the carousel; defaults to 1024px + */ + width?: number; + + /** + * Spinner component. + */ + spinner?: () => React.ReactElement; + + /** + * Color of spinner. Default value: 'white' + */ + spinnerColor?: string; + + /** + * Size of spinner. Default value: 100 + */ + spinnerSize?: number; + + /** + * Determines whether scrolling is prevented via react-scrolllock. Default value: true + */ + preventScroll?: boolean; + + /** + * Optionally display thumbnails beneath the Lightbox + */ + showThumbnails?: boolean; + + /** + * The image count separator. Default value: ' of ' + */ + imageCountSeparator?: string; + + /** + * Customize right arrow title. Default value: ' Next (Right arrow key) ' + */ + rightArrowTitle?: string; + + /** + * Custom of left arrow title. Default value: ' Previous (Left arrow key) ' + */ + leftArrowTitle?: string; + + /** + * Custom close esc title. Default value: ' Close (Esc) ' + */ + closeButtonTitle?: string; + + /** + * Handle closing of the lightbox. Required. + */ + onClose: () => void; + + /** + * Fired on request of the previous image. + */ + onClickPrev?: () => void; + + /** + * Fired on request of the next image. + */ + onClickNext?: () => void; + + /** + * Handle click on image. + */ + onClickImage?: (e: React.MouseEvent) => void; + + /** + * Handle click on thumbnail. + */ + onClickThumbnail?: (index: number) => void; +} + +export interface Image { + /** + * The source of the image. Required. + */ + src: string; + + /** + * array of strings or string + */ + srcSet?: string | string[]; + + /** + * The image caption. + */ + caption?: string; + + /** + * The alt text for the image. + */ + alt?: string; +} + +export default Lightbox; diff --git a/types/react-images/react-images-tests.tsx b/types/react-images/react-images-tests.tsx new file mode 100644 index 0000000000..8b63d4bc8a --- /dev/null +++ b/types/react-images/react-images-tests.tsx @@ -0,0 +1,39 @@ +import * as React from 'react'; +import Lightbox, { Image } from 'react-images'; + +interface ImageGalerieState { + selectedImage: number; + showLightbox: boolean; +} + +class ImageGalerie extends React.Component { + constructor(props: undefined) { + super(props); + this.state = {selectedImage: 0, showLightbox: true}; + } + + render() { + const images: Image[] = [ + { + src: "http://localhost:8080/img1.jpg", + alt: "Image 1", + caption: "Image 1", + }, + { + src: "http://localhost:8080/img2.jpg", + alt: "Image 2", + caption: "Image 2", + }]; + + return this.setState({showLightbox: false})} + onClickImage={e => {}} + onClickNext={() => this.setState({selectedImage: (this.state.selectedImage + 1) % images.length})} + onClickPrev={() => this.setState({selectedImage: this.state.selectedImage === 0 ? images.length : this.state.selectedImage - 1})} + showThumbnails={true} + onClickThumbnail={(index) => this.setState({selectedImage: index})} + />; + } +} diff --git a/types/react-images/tsconfig.json b/types/react-images/tsconfig.json new file mode 100644 index 0000000000..3a505430d8 --- /dev/null +++ b/types/react-images/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-images-tests.tsx" + ] +} diff --git a/types/react-images/tslint.json b/types/react-images/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-images/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-imgpro/index.d.ts b/types/react-imgpro/index.d.ts new file mode 100644 index 0000000000..0f513e55cf --- /dev/null +++ b/types/react-imgpro/index.d.ts @@ -0,0 +1,88 @@ +// Type definitions for react-imgpro 1.3 +// Project: https://github.com/nitin42/react-imgpro +// Definitions by: Carlos Li +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from "react"; + +import ProcessImage = ReactImgpro.ProcessImage; +export default ProcessImage; + +declare namespace ReactImgpro { + type Mode = "neighbor" | "bilinear" | "bicubic" | "hermite" | "bezier"; + interface Shape { + width?: number; + height?: number; + mode?: Mode; + } + interface Size { + width: number; + height: number; + mode: + "horizontal_left" | + "horizontal_center" | + "horizontal_right" | + "vertical_top" | + "vertical_bottom" | + "vertical_middle"; + } + interface ProcessImageProps { + image: string; + resize?: Shape; + quality?: number; + greyscale?: boolean; + normalize?: boolean; + invert?: boolean; + opaque?: boolean; + sepia?: boolean; + dither565?: boolean; + scale?: boolean; + scaleToFitImage?: { + width: number; + height: number; + }; + flip?: { + horizontal?: boolean; + vertical?: boolean; + }; + rotate?: { + degree: number; + mode: Mode; + }; + brightness?: number; /* should be -1 to 1 */ + contrast?: number; /* should be -1 to 1 */ + fade?: number; /* should be 0 - 1 */ + opacity?: number; /* should be 0 - 1 */ + blur?: number; /* should be 0 - 100 */ + posterize?: number; /* should be 0 - 100 */ + cover?: Size; + contain?: Size; + colors?: { + lighten?: number; + brighten?: number; + darken?: number; + desaturate?: number; + saturate?: number; + greyscale?: number; + spin?: number; + mix?: { + color?: string; + amount?: number; + }, + tint?: number; + xor?: number; + shade?: number; + red?: number; + green?: number; + blue?: number; + }; + storage?: boolean; + disableWebWorker?: boolean; + disableRerender?: boolean; + customCdn?: string; + onProcessFinish: () => void; + } + + class ProcessImage extends React.Component {} +} diff --git a/types/react-imgpro/react-imgpro-tests.tsx b/types/react-imgpro/react-imgpro-tests.tsx new file mode 100644 index 0000000000..74fd1a3045 --- /dev/null +++ b/types/react-imgpro/react-imgpro-tests.tsx @@ -0,0 +1,25 @@ +import * as React from 'react'; +import ProcessImage from "react-imgpro"; + +class Test extends React.Component { + render() { + return ( + console.log("onProcessFinish")} + > +

          +
          +
          + + ); + } +} diff --git a/types/react-imgpro/tsconfig.json b/types/react-imgpro/tsconfig.json new file mode 100644 index 0000000000..e888d7e2c3 --- /dev/null +++ b/types/react-imgpro/tsconfig.json @@ -0,0 +1,25 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-imgpro-tests.tsx" + ] +} diff --git a/types/react-imgpro/tslint.json b/types/react-imgpro/tslint.json new file mode 100644 index 0000000000..f93cf8562a --- /dev/null +++ b/types/react-imgpro/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} diff --git a/types/react-infinite-calendar/index.d.ts b/types/react-infinite-calendar/index.d.ts index 2110d4dbd0..ac09df7bf4 100644 --- a/types/react-infinite-calendar/index.d.ts +++ b/types/react-infinite-calendar/index.d.ts @@ -6,16 +6,33 @@ import * as React from 'react'; +export type DateType = Date | string | number; + +export enum EVENT_TYPE { + START = 1, + HOVER, + END +} + +export interface RangedSelection { + eventType: EVENT_TYPE; + start: Date; + end: Date; +} + +export type RangedSelectFunction = (rangedDate: RangedSelection) => void; +export type DateSelectFunction = (date: Date) => void; + export interface ReactInfiniteCalendarProps { - selected?: Date | boolean; - width?: number | 'auto'; + selected?: DateType | false | { start: DateType; end: DateType }; + width?: number | 'auto' | '100%'; height?: number | 'auto'; - min?: Date; - max?: Date; - minDate?: Date; - maxDate?: Date; + min?: DateType; + max?: DateType; + minDate?: DateType; + maxDate?: DateType; disabledDays?: Array<0 | 1 | 2 | 3 | 4 | 5 | 6>; - disabledDates?: Date[]; + disabledDates?: DateType[]; display?: 'days' | 'years'; displayOptions?: { hideYearsOnSelect?: boolean; @@ -55,12 +72,22 @@ export interface ReactInfiniteCalendarProps { weekdayColor?: string; }; className?: string; - onSelect?: (date: string) => void; + onSelect?: DateSelectFunction | RangedSelectFunction; onScroll?: (scrollTop: number) => void; onScrollEnd?: (scrollTop: number) => void; rowHeight?: number; autoFocus?: boolean; tabIndex?: number; + Component?: CalendarClass; } +export class Calendar extends React.Component {} +export type CalendarClass = React.ComponentClass; + +export function withRange(component: CalendarClass): CalendarClass; +export function withDateSelection(component: CalendarClass): CalendarClass; +export function withMultipleDates(component: CalendarClass): CalendarClass; +export function withKeyboardSupport(component: CalendarClass): CalendarClass; +export function defaultMultipleDateInterpolation(component: CalendarClass): CalendarClass; + export default class ReactInfiniteCalendar extends React.Component {} diff --git a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx index ff1918d539..ba4b6a0ec7 100644 --- a/types/react-infinite-calendar/react-infinite-calendar-tests.tsx +++ b/types/react-infinite-calendar/react-infinite-calendar-tests.tsx @@ -1,5 +1,11 @@ import * as React from 'react'; -import ReactInfiniteCalendar from 'react-infinite-calendar'; +import ReactInfiniteCalendar, { + Calendar, + withRange, + withKeyboardSupport, + withMultipleDates, + withDateSelection +} from 'react-infinite-calendar'; const test: React.SFC = () => ( ( tabIndex={1} /> ); + +const testWithRange = withRange(Calendar); +const testWithDateSelection = withDateSelection(Calendar); +const testWithKeyboardSupport = withKeyboardSupport(Calendar); +const testWithMultipleDate = withMultipleDates(Calendar); diff --git a/types/react-infinite-scroll-component/index.d.ts b/types/react-infinite-scroll-component/index.d.ts index f43fc50e24..4380c2f11a 100644 --- a/types/react-infinite-scroll-component/index.d.ts +++ b/types/react-infinite-scroll-component/index.d.ts @@ -3,6 +3,7 @@ // Definitions by: Stephanie Roy // Bartosz Dotryw // David Kevork +// Joshua R. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -30,7 +31,7 @@ declare namespace InfiniteScroll { /** * This message is shown to the user when he has seen all the records which means he's at the bottom and hasMore is false */ - endMessage: React.ReactNode; + endMessage?: React.ReactNode; /** * You can send a loader component to show while the component waits for the next load of data. e.g.

          Loading...

          or any fancy loader element diff --git a/types/react-infinite-scroller/index.d.ts b/types/react-infinite-scroller/index.d.ts index 47c2166bc9..f0af24ac5e 100644 --- a/types/react-infinite-scroller/index.d.ts +++ b/types/react-infinite-scroller/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for react-infinite-scroller 1.0 +// Type definitions for react-infinite-scroller 1.2 // Project: https://github.com/CassetteRocks/react-infinite-scroller // Definitions by: Lauri Lavanti , // Piotr Srebniak +// Brett Miller +// Yipeng Zhao // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -61,8 +63,14 @@ declare namespace InfiniteScroll { * Loader component for indicating "loading more". */ loader?: React.ReactElement; + /** + * Override method to return a different scroll listener if it's not the immediate parent of InfiniteScroll. + */ + getScrollParent?(): HTMLElement | null; + } + class InfiniteScroll extends React.Component { + getParentElement(elem?: HTMLElement | null): HTMLElement | undefined | null; } - class InfiniteScroll extends React.Component { } namespace InfiniteScroll {} } diff --git a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx index 2f9009f667..eeb2214826 100644 --- a/types/react-infinite-scroller/react-infinite-scroller-tests.tsx +++ b/types/react-infinite-scroller/react-infinite-scroller-tests.tsx @@ -27,8 +27,38 @@ class Test2 extends React.Component { useCapture useWindow={false} > -
          Test 1
          +
          Test 2
          ); } } + +class Test3 extends React.Component { + inputRef = React.createRef(); + + render() { + return ( +
          + {}} + getScrollParent={() => this.inputRef.current} + > +
          Test 3
          +
          +
          + ); + } +} + +class InfiniteScrollOverride extends InfiniteScroll { + getParentElement(el: HTMLElement) { + if (document.getElementById("scroll-header")) { + return document.getElementById("scroll-header"); + } + return super.getParentElement(el); + } + + render() { + return super.render(); + } +} diff --git a/types/react-instantsearch-core/index.d.ts b/types/react-instantsearch-core/index.d.ts new file mode 100644 index 0000000000..bceb91ca85 --- /dev/null +++ b/types/react-instantsearch-core/index.d.ts @@ -0,0 +1,542 @@ +// Type definitions for react-instantsearch-core 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// David Furlong +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +/** + * Creates a specialized root InstantSearch component. It accepts + * an algolia client and a specification of the root Element. + * @param defaultAlgoliaClient - a function that builds an Algolia client + * @param root - the defininition of the root of an InstantSearch sub tree. + * @returns an InstantSearch root + */ +export function createInstantSearch( + defaultAlgoliaClient: (appId: string, apiKey: string, options: { _useRequestCache: boolean }) => object, + root: object +): React.ComponentClass; + +/** + * Creates a specialized root Index component. It accepts + * a specification of the root Element. + * @param defaultRoot - the defininition of the root of an Index sub tree. + * @return a Index root + */ +export function createIndex(defaultRoot: object): React.ComponentClass; + +export interface ConnectorDescription { + displayName: string; + propTypes?: any; + defaultProps?: any; + + /** + * This method should return the props to forward to the composed component. + * props are the props that were provided to the higher-order component. + * searchState holds the search state of all widgets. You can find the shape of all widgets search state in the corresponding guide. + * searchResults holds the search results, search errors and search loading state, with the shape + * {results: ?SearchResults, error: ?Error, searching: boolean, searchingForFacetValues: boolean}. The SearchResults type is described in the Helper’s documentation. + * meta is the list of metadata from all widgets whose connector defines a getMetadata method. + * searchForFacetValuesResults holds the search for facet values results. + */ + getProvidedProps?(...args: any[]): any; + + /** + * This method defines exactly how the refine prop of widgets affects the search state. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed + * to the refine and createURL props of stateful widgets, and returns a new state. + */ + refine?(...args: any[]): any; + + /** + * This method applies the current props and state to the provided SearchParameters, and returns a new SearchParameters. The SearchParameters + * type is described in the Helper’s documentation. + * Every time the props or state of a widget change, all the getSearchParameters methods of all the registered widgets are called in a chain + * to produce a new SearchParameters. Then, if the output SearchParameters differs from the previous one, a new search is triggered. + * As such, the getSearchParameters method allows you to describe how the state and props of a widget should affect the search parameters. + */ + getSearchParameters?(...args: any[]): any; + + /** + * This method allows the widget to register a custom metadata object for any props and state combination. + * If your widget is stateful, the corresponding URL key should be declared on the metadata object as the id property, so that the InstantSearch + * component can determine which URL keys it controls and which are foreign and should be left intact. + * The metadata object also allows you to declare any data that you would like to pass down to all other widgets. The list of metadata objects of + * all components is available as the fourth argument to the getProvidedProps method. + * The CurrentRefinements widget leverages this mechanism in order to allow any widget to declare the filters it has applied. If you want to add + * your own filter, declare a filters property on your widget’s metadata + */ + getMetadata?(...args: any[]): any; + + /** + * This method needs to be implemented if you want to have the ability to perform a search for facet values inside your widget. + * It takes in the current props of the higher-order component, the search state of all widgets, as well as all arguments passed to the searchForFacetValues + * props of stateful widgets, and returns an object of the shape: {facetName: string, query: string, maxFacetHits?: number}. The default value for the + * maxFacetHits is the one set by the API which is 10. + */ + searchForFacetValues?(...args: any[]): any; + + /** + * This method is called when a widget is about to unmount in order to clean the searchState. + * It takes in the current props of the higher-order component and the searchState of all widgets and expect a new searchState in return. + * props are the props that were provided to the higher-order component. + * searchState holds the searchState of all widgets, with the shape {[widgetId]: widgetState}. Stateful widgets describe the format of their searchState + * in their respective documentation entry. + */ + cleanUp?(...args: any[]): any; +} + +/** + * Connectors are the HOC used to transform React components + * into InstantSearch widgets. + * In order to simplify the construction of such connectors + * `createConnector` takes a description and transform it into + * a connector. + * @param connectorDesc the description of the connector + * @return a function that wraps a component into + * an instantsearch connected one. + */ +export function createConnector(connectorDesc: ConnectorDescription): (Composed: React.ComponentType) => React.ComponentClass; + +// Utils +export const HIGHLIGHT_TAGS: { + highlightPreTag: string, + highlightPostTag: string, +}; +export const version: string; +export function translatable(defaultTranslations: any): (Composed: React.ComponentType) => React.ComponentClass; + +// Widgets +/** + * Configure is a widget that lets you provide raw search parameters + * to the Algolia API. + * + * Any of the props added to this widget will be forwarded to Algolia. For more information + * on the different parameters that can be set, have a look at the + * [reference](https://www.algolia.com/doc/api-client/javascript/search#search-parameters). + * + * This widget can be used either with react-dom and react-native. It will not render anything + * on screen, only configure some parameters. + */ +export class Configure extends React.Component {} + +// Connectors +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 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 }; + southWest: { lat: number, lng: number }; +} + +export interface GeoSearchExposed { + defaultRefinement?: NESW; +} +export interface GeoSearchProvided { + /** a function to toggle the refinement */ + refine: (refinement: NESW) => void; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; + /** the records that matched the search */ + hits: THit[]; + /** true if the current refinement is set with the map bounds */ + isRefinedWithMap: boolean; + /** the refinement currently applied */ + currentRefinement: NESW; + /** the position of the search */ + position: { lat: number, lng: number }; +} +/** + * The GeoSearch connector provides the logic to build a widget that will display the results on a map. + * It also provides a way to search for results based on their position. The connector provides function to manage the + * search experience (search on map interaction). + * + * https://community.algolia.com/react-instantsearch/connectors/connectGeoSearch.html + */ +export function connectGeoSearch(stateless: React.StatelessComponent): React.ComponentClass; +export function connectGeoSearch>, THit>(ctor: React.ComponentType): ConnectedComponentClass, GeoSearchExposed>; + +export function connectHierarchicalMenu(Composed: React.ComponentType): React.ComponentClass; +export function connectHighlight(Composed: React.ComponentType): React.ComponentClass; + +/** + * connectHits connector provides the logic to create connected components that will render the results retrieved from Algolia. + * To configure the number of hits retrieved, use HitsPerPage widget, connectHitsPerPage connector or pass the hitsPerPage prop to a Configure widget. + * Warning: you will need to use the objectID property available on every hit as a key when iterating over them. This will ensure you have the best possible UI experience especially on slow networks. + * + * https://community.algolia.com/react-instantsearch/connectors/connectHits.html + */ +export function connectHits(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectHitsPerPage(Composed: React.ComponentType): React.ComponentClass; + +export interface InfiniteHitsProvided { + /** the records that matched the search */ + hits: THit[]; + /** a function to toggle the refinement */ + refine: (...args: any[]) => any; + /** indicates if there are more pages to load */ + hasMore: boolean; +} + +/** + * InfiniteHits connector provides the logic to create connected components that will render an continuous list of results retrieved from Algolia. + * This connector provides a function to load more results. + * + * https://community.algolia.com/react-instantsearch/connectors/connectInfiniteHits.html + */ +export function connectInfiniteHits(Composed: React.ComponentType): React.ComponentClass; +export function connectInfiniteHits>, THit>(ctor: React.ComponentType): ConnectedComponentClass>; + +export interface MenuProvided { + items: Array<{ count: number, isRefined: boolean, label: string, value: string }>; + currentRefinement: string; + refine: (...args: any[]) => any; + createURL: (...args: any[]) => any; + searchForItems: (...args: any[]) => any; + isFromSearch: boolean; +} +export interface MenuExposed { + attribute: string; + showMore?: boolean; + limit?: number; + showMoreLimit?: number; + defaultRefinement?: string; + transformItems?: (...args: any[]) => any; + searchable?: boolean; +} +/** + * connectMenu connector provides the logic to build a widget that will give the user the ability to choose a single value for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectMenu.html + */ +export function connectMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export interface NumericMenuProvided { + /** the list of ranges the NumericMenu can display. */ + items: Array<{isRefined: boolean, label: string, value: string, noRefinement: boolean}>; + /** + * the refinement currently applied. follow the shape of a string with a pattern of '{start}:{end}' which corresponds to the current selected item. + * For instance, when the selected item is {start: 10, end: 20}, the searchState of the widget is '10:20'. When start isn’t defined, the searchState + * of the widget is ':{end}', and the same way around when end isn’t defined. However, when neither start nor end are defined, the searchState is an empty string. + */ + currentRefinement: string; + /** a function to select a range. */ + refine: (...args: any[]) => any; + /** a function to generate a URL for the corresponding search state */ + createURL: (...args: any[]) => any; +} +export interface NumericMenuExposed { + id?: string; + /** the name of the attribute in the records */ + attribute: string; + /** List of options. With a text label, and upper and lower bounds. */ + items: Array<{ + label: string | JSX.Element; + start?: number; + end?: number; + }>; + /** the value of the item selected by default, follow the shape of a string with a pattern of '{start}:{end}'. */ + defaultRefinement?: string; + /** (...args: any[]) => any 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; +} +/** + * connectNumericMenu connector provides the logic to build a widget that will give the user the ability to select a range value for a numeric attribute. + * Ranges are defined statically. + * + * https://community.algolia.com/react-instantsearch/connectors/connectNumericMenu.html + */ +export function connectNumericMenu(stateless: React.StatelessComponent): React.ComponentClass; +export function connectNumericMenu>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectPagination(Composed: React.ComponentType): React.ComponentClass; +export function connectPoweredBy(Composed: React.ComponentType): React.ComponentClass; +export function connectRange(Composed: React.ComponentType): React.ComponentClass; + +export interface RefinementListProvided { + /** a function to toggle a refinement */ + 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. + * 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. */ + isFromSearch: boolean; + /** a boolean that says whether you can currently refine */ + canRefine: boolean; +} +export interface RefinementListExposed { + /** the name of the attribute in the record */ + attribute: string; + /** allow search inside values */ + searchable?: boolean; + /** How to apply the refinements. Possible values: ‘or’ or ‘and’. */ + operator?: 'or' | 'and'; + /** true if the component should display a button that will expand the number of items */ + showMore?: boolean; + /** the minimum number of displayed items */ + limit?: number; + /** the maximun number of displayed items. Only used when showMore is set to true */ + showMoreLimit?: number; + /** + * the values of the items selected by default. The searchState of this widget takes the form of a list of strings, + * which correspond to the values of all selected refinements. However, when there are no refinements selected, + * the value of the searchState is an empty string. + */ + defaultRefinement?: string[]; + /** (...args: any[]) => any 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; +} + +/** + * connectRefinementList connector provides the logic to build a widget that will give the user the ability to choose multiple values for a specific facet. + * + * https://community.algolia.com/react-instantsearch/connectors/connectRefinementList.html + */ +export function connectRefinementList(stateless: React.StatelessComponent): React.ComponentClass; +export function connectRefinementList>(ctor: React.ComponentType): + ConnectedComponentClass; + +export function connectScrollTo(Composed: React.ComponentType): React.ComponentClass; + +export interface SearchBoxProvided { + /** a function to change the current query */ + refine: (...args: any[]) => any; + /** the current query used */ + currentRefinement: string; + /** a flag that indicates if InstantSearch has detected that searches are stalled */ + isSearchStalled: boolean; +} +export interface SearchBoxExposed { + /** Provide a default value for the query */ + defaultRefinement?: string; +} +export function connectSearchBox(stateless: React.StatelessComponent): React.ComponentClass; +export function connectSearchBox>(ctor: React.ComponentType): ConnectedComponentClass; + +export function connectSortBy(Composed: React.ComponentType): React.ComponentClass; + +export interface StateResultsProvided { + /** The search state of the instant search component. */ + searchState: SearchState; + /** + * The search results. + * In case of multiple indices: if used under , results will be those of the corresponding index + * otherwise it’ll be those of the root index + */ + searchResults: SearchResults; + /** In case of multiple indices you can retrieve all the results */ + allSearchResults: { [index: string]: SearchResults }; + /** If there is a search in progress. */ + searching: boolean; + /** Flag that indicates if React InstantSearch has detected that searches are stalled. */ + isSearchStalled: any; + /** If the search failed, the error will be logged here. */ + error: AlgoliaError; + /** If there is a search in a list in progress. */ + searchingForFacetValues: any; +} +/** + * The connectStateResults connector provides a way to access the `searchState` and the `searchResults` of InstantSearch. + * For instance this connector allows you to create results/noResults or query/noQuery pages. + * + * https://community.algolia.com/react-instantsearch/connectors/connectStateResults.html + */ +export function connectStateResults(stateless: React.StatelessComponent): React.ComponentClass; +export function connectStateResults>, TDoc>(ctor: React.ComponentType): ConnectedComponentClass>; + +export function connectStats(Composed: React.ComponentType): React.ComponentClass; +export function connectToggleRefinement(Composed: React.ComponentType): React.ComponentClass; + +export interface AlgoliaError { + stack: string; + name: string; + message: string; + debugData: any[]; + statusCode: number; +} + +type Omit = Pick>; + +export type ConnectedComponentClass + = React.ComponentClass & TExposedProps>; + +/** + * The searchState contains all widgets states. If a widget uses an attribute, + * we store it under its widget category to prevent collision. + * + * https://community.algolia.com/react-instantsearch/guide/Search_state.html + */ +export interface SearchState { + range?: { + [key: string]: { + min: number; + max: number; + } + }; + configure?: { + aroundLatLng: boolean; + [key: string]: any; + }; + refinementList?: { + [key: string]: string[] + }; + hierarchicalMenu?: { + [key: string]: string + }; + menu?: { + [key: string]: string + }; + multiRange?: { + [key: string]: string + }; + toggle?: { + [key: string]: boolean + }; + hitsPerPage?: number; + sortBy?: string; + query?: string; + page?: number; + + indices?: { + [index: string]: { + configure: { + hitsPerPage: number, + }, + } + }; +} + +/** + * The most basic possible document in an Algolia index: + * a set of string-value pairs. + */ +export interface BasicDoc { [k: string]: string; } + +/** + * The shape of the searchResults object provided + * via connectors + * https://community.algolia.com/algoliasearch-helper-js/reference.html#searchresults + */ +export interface SearchResults { + query: string; + hits: Array>; + index: string; + hitsPerPage: number; + nbHits: number; + nbPages: number; + page: number; + processingTimeMS: number; + exhaustiveNbHits: true; + disjunctiveFacets: any[]; + hierarchicalFacets: any[]; + facets: any[]; + aroundLatLng?: string; + automaticRadius?: string; +} + +/** + * All the records that match the search parameters. + * Each record is augmented with a new attribute `_highlightResult` which is an + * object keyed by attribute and contains additional properties + * https://community.algolia.com/algoliasearch-helper-js/reference.html#SearchResults#hits + */ +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 } : + never; + +type HighlightResultField = + TField extends Array ? + HighlightResultArray : + TField extends string ? + HighlightResultPrimitive : + HighlightResult; + +type HighlightResultArray = + TItem extends string ? + HighlightResultPrimitive[] : + Array>; + +interface HighlightResultPrimitive { + /** the value of the facet highlighted (html) */ + value: string; + /** full, partial or none depending on how the query terms match */ + matchLevel: 'none' | 'partial' | 'full'; + matchedWords: string[]; + fullyHighlighted?: boolean; +} + +// Turn off automatic exports - so we don't export internal types like Omit<> +export {}; diff --git a/types/react-instantsearch-core/react-instantsearch-core-tests.tsx b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx new file mode 100644 index 0000000000..e39a9f53e6 --- /dev/null +++ b/types/react-instantsearch-core/react-instantsearch-core-tests.tsx @@ -0,0 +1,221 @@ +import * as React from 'react'; +import { + createInstantSearch, + createIndex, + createConnector, + SearchResults, + connectStateResults, + SearchBoxProvided, + connectSearchBox, + connectRefinementList, + CurrentRefinementsProvided, + connectCurrentRefinements, + RefinementListProvided, + Refinement +} from 'react-instantsearch-core'; + +() => { + const InstantSearch = createInstantSearch(() => ({}), {Root: 'div', props: {className: `widget`}}); + + +
          +
          ; +}; + +() => { + const Index = createIndex({Root: 'div', props: {className: `widget`}}); + + +
          +
          ; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +() => { + const CoolWidget = createConnector({ + displayName: 'CoolWidget', + + getProvidedProps(props, searchState) { + // Since the `queryAndPage` searchState entry isn't necessarily defined, we need + // to default its value. + const [query, page] = searchState.queryAndPage || ['', 0]; + + // Connect the underlying component to the `queryAndPage` searchState entry. + return { + query, + page, + }; + }, + + refine(props, searchState, newQuery, newPage) { + // When the underlying component calls its `refine` prop, update the searchState + // with the new query and page. + return { + // `searchState` represents the search state of *all* widgets. We need to extend it + // instead of replacing it, otherwise other widgets will lose their + // respective state. + ...searchState, + queryAndPage: [newQuery, newPage], + }; + }, + })(props => +
          + The query is {props.query}, the page is {props.page}. + {/* + Clicking on this button will update the searchState to: + { + ...otherSearchState, + query: 'algolia', + page: 20, + } + */} +
          + ); + + +
          +
          ; +}; + +() => { + interface StateResultsProps { + searchResults: SearchResults<{ + field1: string + field2: number + field3: { compound: string } + }>; + // partial of StateResultsProvided + + additionalProp: string; + } + + const Stateless = ({ additionalProp, searchResults }: StateResultsProps) => +
          +

          {additionalProp}

          + {searchResults.hits.map((h) => { + // $ExpectType string + const compound = h._highlightResult.field3!.compound!.value; + return {compound}; + })} +
          ; + const ComposedStateless = connectStateResults(Stateless); + + ; // $ExpectError + + ; + + class MyComponent extends React.Component { + render() { + const { additionalProp, searchResults } = this.props; + return
          +

          {additionalProp}

          + {searchResults.hits.map((h) => { + // $ExpectType string[] + const words = h._highlightResult.field3!.compound!.matchedWords; + return {h.field2}: {words.join(',')}; + })} +
          ; + } + } + const ComposedMyComponent = connectStateResults(MyComponent); + + ; // $ExpectError + + ; +}; + +() => { + const InstantSearch = createInstantSearch( + () => null, // $ExpectError + {} + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Connectors.html +() => { + const MySearchBox = ({currentRefinement, refine}: SearchBoxProvided) => + refine(e.target.value)} + />; + + // `ConnectedSearchBox` renders a `` widget that is connected to + // the state, providing it with `currentRefinement` and `refine` props for + // 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-core/tsconfig.json b/types/react-instantsearch-core/tsconfig.json new file mode 100644 index 0000000000..44fe46a735 --- /dev/null +++ b/types/react-instantsearch-core/tsconfig.json @@ -0,0 +1,22 @@ +{ + "compilerOptions": { + "module": "commonjs", + "jsx": "react", + "lib": ["es6", "dom"], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-core-tests.tsx" + ] +} diff --git a/types/react-instantsearch-core/tslint.json b/types/react-instantsearch-core/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-core/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-dom/index.d.ts b/types/react-instantsearch-dom/index.d.ts new file mode 100644 index 0000000000..6ecb03c981 --- /dev/null +++ b/types/react-instantsearch-dom/index.d.ts @@ -0,0 +1,137 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +import { Hit, BasicDoc } from 'react-instantsearch-core'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// DOM +interface CommonWidgetProps { + /** + * All static text rendered by widgets, such as “Load more”, “Show more” are translatable using the translations prop on relevant widgets. + * This prop is a mapping of keys to translation values. Translation values can be either a String or a (...args: any[]) => any, as some take parameters. + * + * https://community.algolia.com/react-instantsearch/guide/i18n.html + */ + translations?: { [key: string]: string | ((...args: any[]) => any) }; +} + +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} +export class Index extends React.Component {} +export class Breadcrumb extends React.Component {} +export class ClearRefinements extends React.Component {} +export class CurrentRefinements extends React.Component {} +export class HierarchicalMenu extends React.Component {} +export class Highlight extends React.Component {} + +export interface HitsProps { + hitComponent?: React.ComponentType<{ hit: Hit }>; +} +/** + * Displays a list of hits. + * To configure the number of hits being shown, use the HitsPerPage widget, connectHitsPerPage connector or the Configure widget. + * + * https://community.algolia.com/react-instantsearch/widgets/Hits.html + */ +export class Hits extends React.Component> {} +export class HitsPerPage extends React.Component {} +export class InfiniteHits extends React.Component {} +export class Menu extends React.Component {} +export class MenuSelect extends React.Component {} +export class NumericMenu extends React.Component {} +export class Pagination extends React.Component {} +export class Panel extends React.Component {} +export class PoweredBy extends React.Component {} +export class RangeInput extends React.Component {} +export class RangeSlider extends React.Component {} +export class RatingMenu extends React.Component {} +export class RefinementList extends React.Component {} +export class ScrollTo extends React.Component {} + +export interface SearchBoxProps extends CommonWidgetProps { + focusShortcuts?: string[]; + autoFocus?: boolean; + defaultRefinement?: string; + searchAsYouType?: boolean; + showLoadingIndicator?: boolean; + + submit?: JSX.Element; + reset?: JSX.Element; + loadingIndicator?: JSX.Element; + + 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. + * + * https://community.algolia.com/react-instantsearch/widgets/SearchBox.html + */ +export class SearchBox extends React.Component {} +export class Snippet extends React.Component {} +export class SortBy extends React.Component {} +/** + * The Stats component displays the total number of matching hits and the time it took to get them (time spent in the Algolia server). + */ +export class Stats extends React.Component<{translations?: { [key: string]: (n: number, ms: number) => string }}> {} +export class ToggleRefinement extends React.Component {} diff --git a/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx new file mode 100644 index 0000000000..e10d3fde08 --- /dev/null +++ b/types/react-instantsearch-dom/react-instantsearch-dom-tests.tsx @@ -0,0 +1,280 @@ +import * as React from 'react'; +import { InstantSearch, Hits, Highlight, SearchBox, RefinementList, CurrentRefinements, ClearRefinements, Pagination, Menu, Configure, Index } from 'react-instantsearch/dom'; +import { Hit, connectRefinementList, connectMenu } from 'react-instantsearch-core'; + +// DOM +// https://community.algolia.com/react-instantsearch/Getting_started.html +() => { + const App = () => ( + + + + ); + + function Search() { + return ( +
          + +
          + ); + } + + function Product({ hit }: { hit: Hit }) { + return
          {hit.name}
          ; + } + + function Search2() { + return ( +
          + +
          + ); + } + + function Product2({ hit }: { hit: Hit }) { + return ( +
          + + + +
          + ); + } + + function Search3() { + return ( +
          + + + +
          + ); + } + + function Search4() { + return ( +
          + + + + + + +
          + ); + } +}; + +// https://community.algolia.com/react-instantsearch/guide//Highlighting_results.html +() => { + const Hit = ({ hit }: { hit: Hit }) => ( +

          + +

          + ); + + function App() { + return ( + + + + ); + } +}; + +// TODO +// () => { +// const CustomHighlight = connectHighlight( +// ({ highlight, attribute, hit, highlightProperty }) => { +// const parsedHit = highlight({ +// attribute, +// hit, +// highlightProperty: '_highlightResult' +// }); +// const highlightedHits = parsedHit.map(part => { +// if (part.isHighlighted) return {part.value}; +// return part.value; +// }); +// return
          {highlightedHits}
          ; +// } +// ); + +// const Hit = ({ hit }: { hit: Hit }) => ( +//

          +// +//

          +// ); + +// function App() { +// return ( +// +// +// +// ); +// } +// }; + +// https://community.algolia.com/react-instantsearch/guide/i18n.html +() => { + const App = () => ( + + + + ); +}; + +// https://community.algolia.com/react-instantsearch/guide/Sorting_and_filtering.html +// TODO +// () => { +// const App = () => ( +// +// +// +// orderBy(items, ['label', 'count'], ['asc', 'desc']) +// } +// /> +// +// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Default_refinements.html +() => { + const App = () => ( + + + + + ); +}; + +// TODO +// () => { +// const VirtualMenu = connectMenu(() => null); + +// const App = () => ( +// +//
          +// +// items.filter(item => item.currentRefinement !== 'Orange') +// } +// /> +// +// +// +//
          +//
          +// ); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Searching_in_Lists.html + +; + +() => { + // https://community.algolia.com/react-instantsearch/guide/Search_parameters.html + + + // widgets + ; +}; + +(() => { + 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; +import { renderToString } from 'react-dom/server'; + +() => { + // https://community.algolia.com/react-instantsearch/guide/Server-side_rendering.html + + // Now we create a dedicated `InstantSearch` component + const { InstantSearch, findResultsState } = createInstantSearch(); + + class App extends React.Component { + render() { + return ( + + + + + ); + } + } + + const server = createServer(async (req, res) => { + const searchState = {query: 'chair'}; + const resultsState = await findResultsState(App, {searchState}); + const appInitialState = {searchState, resultsState}; + const appAsString = renderToString(); + res.send( + ` + + + +

          Awesome server-side rendered search

          + ${appAsString}
          + + + + ` + ); + }); +}; diff --git a/types/react-instantsearch-dom/server.d.ts b/types/react-instantsearch-dom/server.d.ts new file mode 100644 index 0000000000..b1ba930ace --- /dev/null +++ b/types/react-instantsearch-dom/server.d.ts @@ -0,0 +1,14 @@ +import * as React from 'react'; + +/** + * Creates a specialized root InstantSearch component. It accepts + * an algolia client and a specification of the root Element. + * @param defaultAlgoliaClient - a function that builds an Algolia client + * @returns an InstantSearch root + */ +export function createInstantSearch( + defaultAlgoliaClient?: (appId: string, apiKey: string, options: { _useRequestCache: boolean }) => object +): { + InstantSearch: React.ComponentClass; + findResultsState(App: React.ComponentType, props: any): Promise +}; diff --git a/types/react-instantsearch-dom/tsconfig.json b/types/react-instantsearch-dom/tsconfig.json new file mode 100644 index 0000000000..15ec605c21 --- /dev/null +++ b/types/react-instantsearch-dom/tsconfig.json @@ -0,0 +1,26 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6", + "dom" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "server.d.ts", + "react-instantsearch-dom-tests.tsx" + ] +} diff --git a/types/react-instantsearch-dom/tslint.json b/types/react-instantsearch-dom/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-dom/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch-native/index.d.ts b/types/react-instantsearch-native/index.d.ts new file mode 100644 index 0000000000..6b328de132 --- /dev/null +++ b/types/react-instantsearch-native/index.d.ts @@ -0,0 +1,68 @@ +// Type definitions for react-instantsearch-native 5.3 +// Project: https://community.algolia.com/react-instantsearch +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +import * as React from 'react'; + +// Core +export { createConnector } from 'react-instantsearch-core'; +export { HIGHLIGHT_TAGS } from 'react-instantsearch-core'; +export { translatable } from 'react-instantsearch-core'; + +// Widget +export { Configure } from 'react-instantsearch-core'; + +// Connectors +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu } from 'react-instantsearch-core'; +export { connectNumericMenu } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; + +// Native +export interface InstantSearchProps { + apiKey: string; + appId: string; + indexName: string; + + algoliaClient?: any; + searchClient?: any; + createURL?: (...args: any[]) => any; + searchState?: any; + refresh?: boolean; + onSearchStateChange?: (...args: any[]) => any; + onSearchParameters?: (...args: any[]) => any; + resultsState?: any; + root?: { + Root: string | ((...args: any[]) => any); + props: any; + }; +} +/** + * is the root component of all React InstantSearch implementations. It provides all the connected components (aka widgets) a means to interact with the searchState. + * + * https://community.algolia.com/react-instantsearch/widgets/%3CInstantSearch%3E.html + */ +export class InstantSearch extends React.Component {} + +export class Index extends React.Component {} diff --git a/types/react-instantsearch-native/react-instantsearch-native-tests.tsx b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx new file mode 100644 index 0000000000..7a369b0487 --- /dev/null +++ b/types/react-instantsearch-native/react-instantsearch-native-tests.tsx @@ -0,0 +1,69 @@ +import * as React from "react"; + +import { SearchBox, Hits, Highlight, Menu } from "react-instantsearch-dom"; +import { InstantSearch, Index, connectStateResults } from 'react-instantsearch-native'; +import { values } from 'lodash'; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +const App = () => ( + + + +
          + + +
          +
          first:
          + +
          +
          +
          + + +
          +
          second:
          + +
          +
          +
          + + +
          +
          third:
          + +
          +
          +
          +
          +
          +
          +); + +const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
          + No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
          + ) +); + +const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
          +
          No results in category, products or brand
          + + + +
          + ) : ( + children as React.ReactElement + ); +}); diff --git a/types/react-instantsearch-native/tsconfig.json b/types/react-instantsearch-native/tsconfig.json new file mode 100644 index 0000000000..d4fb7501c4 --- /dev/null +++ b/types/react-instantsearch-native/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "jsx": "react", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-instantsearch-native-tests.tsx" + ] +} diff --git a/types/react-instantsearch-native/tslint.json b/types/react-instantsearch-native/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-instantsearch-native/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-instantsearch/connectors.d.ts b/types/react-instantsearch/connectors.d.ts new file mode 100644 index 0000000000..e926f79e0a --- /dev/null +++ b/types/react-instantsearch/connectors.d.ts @@ -0,0 +1,22 @@ +export { connectAutoComplete } from 'react-instantsearch-core'; +export { connectBreadcrumb } from 'react-instantsearch-core'; +export { connectConfigure } from 'react-instantsearch-core'; +export { connectCurrentRefinements } from 'react-instantsearch-core'; +export { connectGeoSearch, GeoSearchExposed, GeoSearchProvided, NESW } from 'react-instantsearch-core'; +export { connectHierarchicalMenu } from 'react-instantsearch-core'; +export { connectHighlight } from 'react-instantsearch-core'; +export { connectHits, Hit } from 'react-instantsearch-core'; +export { connectHitsPerPage } from 'react-instantsearch-core'; +export { connectInfiniteHits } from 'react-instantsearch-core'; +export { connectMenu, MenuExposed, MenuProvided } from 'react-instantsearch-core'; +export { connectNumericMenu, NumericMenuExposed, NumericMenuProvided } from 'react-instantsearch-core'; +export { connectPagination } from 'react-instantsearch-core'; +export { connectPoweredBy } from 'react-instantsearch-core'; +export { connectRange } from 'react-instantsearch-core'; +export { connectRefinementList, RefinementListExposed, RefinementListProvided } from 'react-instantsearch-core'; +export { connectScrollTo } from 'react-instantsearch-core'; +export { connectSearchBox, SearchBoxExposed, SearchBoxProvided } from 'react-instantsearch-core'; +export { connectSortBy } from 'react-instantsearch-core'; +export { connectStateResults, StateResultsProvided, SearchState, SearchResults } from 'react-instantsearch-core'; +export { connectStats } from 'react-instantsearch-core'; +export { connectToggleRefinement } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/dom.d.ts b/types/react-instantsearch/dom.d.ts new file mode 100644 index 0000000000..ad857eaa58 --- /dev/null +++ b/types/react-instantsearch/dom.d.ts @@ -0,0 +1,27 @@ +export { InstantSearch, InstantSearchProps } from 'react-instantsearch-dom'; +export { Index } from 'react-instantsearch-dom'; +export { Breadcrumb } from 'react-instantsearch-dom'; +export { ClearRefinements } from 'react-instantsearch-dom'; +export { Configure } from 'react-instantsearch-dom'; +export { CurrentRefinements } from 'react-instantsearch-dom'; +export { HierarchicalMenu } from 'react-instantsearch-dom'; +export { Highlight } from 'react-instantsearch-dom'; +export { Hits, HitsProps } from 'react-instantsearch-dom'; +export { HitsPerPage } from 'react-instantsearch-dom'; +export { InfiniteHits } from 'react-instantsearch-dom'; +export { Menu } from 'react-instantsearch-dom'; +export { MenuSelect } from 'react-instantsearch-dom'; +export { NumericMenu } from 'react-instantsearch-dom'; +export { Pagination } from 'react-instantsearch-dom'; +export { Panel } from 'react-instantsearch-dom'; +export { PoweredBy } from 'react-instantsearch-dom'; +export { RangeInput } from 'react-instantsearch-dom'; +export { RangeSlider } from 'react-instantsearch-dom'; +export { RatingMenu } from 'react-instantsearch-dom'; +export { RefinementList } from 'react-instantsearch-dom'; +export { ScrollTo } from 'react-instantsearch-dom'; +export { SearchBox, SearchBoxProps } from 'react-instantsearch-dom'; +export { Snippet } from 'react-instantsearch-dom'; +export { SortBy } from 'react-instantsearch-dom'; +export { Stats } from 'react-instantsearch-dom'; +export { ToggleRefinement } from 'react-instantsearch-dom'; diff --git a/types/react-instantsearch/index.d.ts b/types/react-instantsearch/index.d.ts new file mode 100644 index 0000000000..3f80cf4aa3 --- /dev/null +++ b/types/react-instantsearch/index.d.ts @@ -0,0 +1,8 @@ +// Type definitions for react-instantsearch 5.2 +// Project: https://community.algolia.com/react-instantsearch/ +// Definitions by: Gordon Burgett +// Justin Powell +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export { createConnector } from 'react-instantsearch-core'; diff --git a/types/react-instantsearch/native.d.ts b/types/react-instantsearch/native.d.ts new file mode 100644 index 0000000000..ff6ff89a3f --- /dev/null +++ b/types/react-instantsearch/native.d.ts @@ -0,0 +1,3 @@ +export { InstantSearch } from 'react-instantsearch-native'; +export { Index } from 'react-instantsearch-native'; +export { Configure } from 'react-instantsearch-native'; diff --git a/types/react-instantsearch/react-instantsearch-tests.tsx b/types/react-instantsearch/react-instantsearch-tests.tsx new file mode 100644 index 0000000000..9abf91c0ef --- /dev/null +++ b/types/react-instantsearch/react-instantsearch-tests.tsx @@ -0,0 +1,386 @@ +import * as React from "react"; + +import { connectMenu, connectRefinementList, connectStateResults, SearchState } from "react-instantsearch/connectors"; +import { InstantSearch, SearchBox, Index, Hits, Highlight, Menu } from "react-instantsearch/dom"; +import { orderBy, omit, values } from 'lodash'; +import { createInstantSearch } from "react-instantsearch-core"; + +// https://community.algolia.com/react-instantsearch/guide/Search_state.html +() => { + const searchState: SearchState = { + range: { + price: { + min: 20, + max: 3000 + } + }, + configure: { + aroundLatLng: true, + }, + refinementList: { + fruits: ['lemon', 'orange'] + }, + hierarchicalMenu: { + products: 'Laptops > Surface' + }, + menu: { + brands: 'Sony' + }, + multiRange: { + rank: '2:5' + }, + toggle: { + freeShipping: true + }, + hitsPerPage: 10, + sortBy: 'mostPopular', + query: 'ora', + page: 2 + }; +}; + +() => { + const searchState: SearchState = { + query: 'ora', // shared state between all indices + page: 2, // shared state between all indices + indices: { + index1: { + configure: { + hitsPerPage: 3, + }, + }, + index2: { + configure: { + hitsPerPage: 10, + }, + }, + }, + }; +}; + +// https://community.algolia.com/react-instantsearch/guide/Custom_connectors.html +// TODO +// () => { +// const CoolWidget = createConnector({ +// displayName: 'CoolWidget', + +// getProvidedProps(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // Connect the underlying component to the `queryAndPage` searchState entry. +// return { +// query, +// page, +// }; +// }, + +// refine(props, searchState, newQuery, newPage) { +// // When the underlying component calls its `refine` prop, update the searchState +// // with the new query and page. +// return { +// // `searchState` represents the search state of *all* widgets. We need to extend it +// // instead of replacing it, otherwise other widgets will lose their +// // respective state. +// ...searchState, +// queryAndPage: [newQuery, newPage], +// }; +// }, +// })(props => +//
          +// The query is {props.query}, the page is {props.page}. +// {/* +// Clicking on this button will update the searchState to: +// { +// ...otherSearchState, +// query: 'algolia', +// page: 20, +// } +// */} +//
          +// ); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine + +// getSearchParameters(searchParameters, props, searchState) { +// // Since the `queryAndPage` state entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// // When the `queryAndPage` state entry changes, update the query and page of +// // search. +// return searchParameters +// .setQuery(query) +// .setPage(page); +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters + +// getMetadata(props, searchState) { +// // Since the `queryAndPage` searchState entry isn't necessarily defined, we need +// // to default its value. +// const [query, page] = searchState.queryAndPage || ['', 0]; + +// const filters = []; +// if (query !== '') { +// filters.push({ +// // Unique identifier for this filter. +// key: `queryAndPage.query`, +// // String label (or node) that should appear in the CurrentRefinements +// // component. +// label: `Query: ${query}`, +// // Describes how clearing this filter affects the InstantSearch searchState. +// // In our case, clearing the query just resets it to an empty string +// // without affecting the page. +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// // Do not depend on the current `searchState` here. Since filters can be +// // cleared in batches, the `searchState` parameter is not up-to-date when +// // this method is called. +// queryAndPage: ['', nextSearchState.queryAndPage[1]], +// }; +// }, +// }); +// } + +// if (page !== 0) { +// filters.push({ +// key: `queryAndPage.page`, +// label: `Page: ${page}`, +// clear: nextSearchState => { +// return { +// ...nextSearchState, +// queryAndPage: [nextSearchState.queryAndPage[0], 0], +// }; +// }, +// }); +// } + +// return { +// // This widget manipulates the `queryAndPage` state entry. +// id: 'queryAndPage', +// filters, +// }; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// searchForFacetValues(props, searchState, nextRefinement) { +// return {facetName: props.attribute, query: nextRefinement}; +// }, +// })(Widget); +// }; + +// TODO +// () => { +// const Widget = () => null; + +// const CoolWidget = createConnector({ +// // displayName, getProvidedProps, refine, getSearchParameters, getMetadata + +// cleanUp(props, searchState) { +// return omit('queryAndPage', searchState); +// }, +// })(Widget); +// }; + +// https://community.algolia.com/react-instantsearch/guide/Conditional_display.html +() => { + const Content = connectStateResults( + ({ searchState }) => + searchState && searchState.query + ?
          + The query {searchState.query} exists +
          + :
          No query
          + ); +}; + +() => { + const Content = connectStateResults( + ({ searchState, searchResults }) => + searchResults && searchResults.nbHits !== 0 + ?
          Some results
          + :
          + No results has been found for {searchState.query} +
          + ); +}; + +() => { + const Content = connectStateResults( + ({ error }) => + error ?
          Some error
          :
          No error
          + ); +}; + +() => { + const Content = connectStateResults( + ({ searching }) => + searching ?
          We are searching
          :
          Search finished
          + ); +}; + +() => { + const Content = connectStateResults( + ({ searchingForFacetValues }) => + searchingForFacetValues ?
          We are searching
          :
          Search finished
          + ); +}; + +() => { + const App = () => ( + + + +
          + + +
          +
          first:
          + +
          +
          +
          + + +
          +
          second:
          + +
          +
          +
          + + +
          +
          third:
          + +
          +
          +
          +
          +
          +
          + ); + + const IndexResults = connectStateResults( + ({ searchState, searchResults, children }) => + searchResults && searchResults.nbHits !== 0 ? ( + children as React.ReactElement + ) : ( +
          + No results has been found for {searchState.query} and index{' '} + {searchResults ? searchResults.index : ''} +
          + ) + ); + + const AllResults = connectStateResults(({ allSearchResults, children }) => { + const hasResults = + allSearchResults && + values(allSearchResults).some(results => results.nbHits > 0); + + return !hasResults ? ( +
          +
          No results in category, products or brand
          + + + +
          + ) : ( + children as React.ReactElement + ); + }); +}; + +// https://github.com/algolia/react-instantsearch/blob/master/packages/react-instantsearch-dom/src/widgets/InstantSearch.js +() => { + const InstantSearch = createInstantSearch( + () => ({}), + { + Root: 'div', + props: { + className: 'ais-InstantSearch__root', + }, + } + ); + + ; +}; + +() => { + const RefinementListWithSearchBox = connectRefinementList(props => { + const values = props.items.map(item => { + const label = item._highlightResult + ? + : item.label; + + return ( +
        1. + props.refine(item.value)}> + {label} {item.isRefined ? '- selected' : ''} + +
        2. + ); + }); + + return ( +
          + props.searchForItems((e.target as HTMLInputElement).value)}/> +
            {values}
          +
          + ); + }); + + return ; +}; + +// https://community.algolia.com/react-instantsearch/guide/Virtual_widgets.html +() => { + const VirtualMenu = connectMenu(() => null); + const Hoodies = () => ; + + const App = () => ( + + + + + + ); +}; diff --git a/types/react-instantsearch/server.d.ts b/types/react-instantsearch/server.d.ts new file mode 100644 index 0000000000..d8fb0d1a46 --- /dev/null +++ b/types/react-instantsearch/server.d.ts @@ -0,0 +1 @@ +export { createInstantSearch } from 'react-instantsearch-dom/server'; diff --git a/types/react-instantsearch/tsconfig.json b/types/react-instantsearch/tsconfig.json new file mode 100644 index 0000000000..79afa53442 --- /dev/null +++ b/types/react-instantsearch/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "experimentalDecorators": true, + "jsx": "react", + "lib": ["es6", "dom"], + "module": "commonjs", + "noEmit": true, + "baseUrl": "../", + "typeRoots": [ + "../" + ], + "types": [], + "forceConsistentCasingInFileNames": true, + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true + }, + "files": [ + "index.d.ts", + "connectors.d.ts", + "dom.d.ts", + "native.d.ts", + "server.d.ts", + "react-instantsearch-tests.tsx" + ] +} diff --git a/types/react-instantsearch/tslint.json b/types/react-instantsearch/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-instantsearch/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file 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-intl/index.d.ts b/types/react-intl/index.d.ts index 899859a69d..aaba74820b 100644 --- a/types/react-intl/index.d.ts +++ b/types/react-intl/index.d.ts @@ -9,6 +9,7 @@ // Krister Kari // Martin Raedlinger // Kanitkorn Sujautra +// obedm503 // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -29,8 +30,8 @@ declare namespace ReactIntl { withRef?: boolean; } - function injectIntl

          (component: React.ComponentType

          , options?: InjectIntlConfig): - React.ComponentClass>> & { WrappedComponent: React.ComponentType

          }; + function injectIntl

          (component: React.ComponentType

          , options?: InjectIntlConfig): + React.ComponentClass>> & { WrappedComponent: React.ComponentType

          }; function addLocaleData(data: Locale[] | Locale): void; @@ -46,6 +47,7 @@ declare namespace ReactIntl { messages: React.Requireable; defaultLocale: React.Requireable; defaultFormats: React.Requireable; + onError: React.Requireable; } interface IntlFormat { @@ -78,6 +80,7 @@ declare namespace ReactIntl { defaultLocale: string; defaultFormats: any; now(): number; + onError(error: string): void; } interface InjectedIntlProps { @@ -190,12 +193,14 @@ declare namespace ReactIntl { namespace IntlProvider { interface Props { locale?: string; + timeZone?: string; formats?: any; messages?: any; defaultLocale?: string; defaultFormats?: any; textComponent?: any; initialNow?: any; + onError?: (error: string) => void; } } diff --git a/types/react-intl/react-intl-tests.tsx b/types/react-intl/react-intl-tests.tsx index d3d30757a1..63af762e61 100644 --- a/types/react-intl/react-intl-tests.tsx +++ b/types/react-intl/react-intl-tests.tsx @@ -401,7 +401,15 @@ class TestApp extends React.Component { hello: "Hello, {name}!" }; return ( - + console.error(error)} + > diff --git a/types/react-is/react-is-tests.tsx b/types/react-is/react-is-tests.tsx index 18ae0c4a26..3b41e9d06f 100644 --- a/types/react-is/react-is-tests.tsx +++ b/types/react-is/react-is-tests.tsx @@ -6,7 +6,7 @@ import * as ReactIs from 'react-is'; // Determining if a Component is Valid interface CompProps { - forwardedRef?: React.Ref; + forwardedRef: React.Ref | null; children?: React.ReactNode; } diff --git a/types/react-joyride/index.d.ts b/types/react-joyride/index.d.ts index d081aa87cf..13f691e56e 100644 --- a/types/react-joyride/index.d.ts +++ b/types/react-joyride/index.d.ts @@ -1,6 +1,7 @@ // Type definitions for react-joyride 2.0 // Project: https://github.com/gilbarbara/react-joyride // Definitions by: DongYoon Kang +// Kamran Ayub // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -106,7 +107,7 @@ export interface Props extends OverridableProps { /** * It will be called when Joyride's state changes. It returns a single parameter with the state. */ - callback?(options: (data: State) => any): void; + callback?: (data: State) => any; /** * The tour is played sequentially with the Next button. Defaults to false. @@ -135,6 +136,11 @@ export interface OverridableProps { */ showProgress?: boolean; + /** + * Display a button to skip the tour. + */ + showSkipButton?: boolean; + /** * Disable closing the tooltip on ESC. Defaults to false. */ @@ -150,6 +156,11 @@ export interface OverridableProps { */ disableOverlayClose?: boolean; + /** + * Disable auto scrolling between steps. + */ + disableScrolling?: boolean; + /** * The strings used in the tooltip. Defaults to `{ back: 'Back', close: 'Close', last: 'Last', next: 'Next', skip: 'Skip' }` */ diff --git a/types/react-joyride/react-joyride-tests.tsx b/types/react-joyride/react-joyride-tests.tsx index 82171e98e2..d69d151174 100644 --- a/types/react-joyride/react-joyride-tests.tsx +++ b/types/react-joyride/react-joyride-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Joyride, { Step } from "react-joyride"; +import Joyride, { Step, State } from "react-joyride"; class NewComponent extends React.Component { j: Joyride; @@ -42,7 +42,7 @@ class NewComponent extends React.Component { }]; render() { - return ; + return ; } doStuff() { @@ -56,4 +56,8 @@ class NewComponent extends React.Component { const { title, placement } = this.j.getProgress().step; } + + onCallback(data: State) { + return; + } } diff --git a/types/react-jsonschema-form/index.d.ts b/types/react-jsonschema-form/index.d.ts index 63a4de1b89..c17bda1a94 100644 --- a/types/react-jsonschema-form/index.d.ts +++ b/types/react-jsonschema-form/index.d.ts @@ -1,11 +1,11 @@ -// Type definitions for react-jsonschema-form 1.0.0 +// Type definitions for react-jsonschema-form 1.0.1 // Project: https://github.com/mozilla-services/react-jsonschema-form // Definitions by: Dan Fox // Ivan Jiang -// Kurt Preston // Philippe Bourdages // Lucian Buzzo // Sylvain Thénault +// Sebastian Busch // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -68,7 +68,12 @@ declare module "react-jsonschema-form" { [key: string]: FieldId; }; - export interface WidgetProps extends React.HTMLAttributes { + export interface WidgetProps extends Pick< + React.HTMLAttributes, + Exclude< + keyof React.HTMLAttributes, + "onBlur"|"onFocus"> + > { id: string; schema: JSONSchema6; value: any; @@ -79,6 +84,8 @@ declare module "react-jsonschema-form" { onChange: (value: any) => void; options: object; formContext: any; + onBlur: (id: string, value: string) => void; + onFocus: (id: string, value: string) => void; } export type Widget = diff --git a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx index 0bb6715372..90116127fd 100644 --- a/types/react-jsonschema-form/react-jsonschema-form-tests.tsx +++ b/types/react-jsonschema-form/react-jsonschema-form-tests.tsx @@ -1,5 +1,5 @@ import * as React from "react"; -import Form, { UiSchema, ErrorListProps } from "react-jsonschema-form"; +import Form, { UiSchema, ErrorListProps, WidgetProps } from "react-jsonschema-form"; import { JSONSchema6 } from "json-schema"; // example taken from the react-jsonschema-form playground: @@ -108,3 +108,9 @@ export class Example extends React.Component { ); } } + +export const CustomWidget: React.SFC = (props) => + props.onFocus('id', 'value')} + onBlur={()=> props.onFocus('id', 'value')} + /> diff --git a/types/react-leaflet-markercluster/index.d.ts b/types/react-leaflet-markercluster/index.d.ts new file mode 100644 index 0000000000..5db583d409 --- /dev/null +++ b/types/react-leaflet-markercluster/index.d.ts @@ -0,0 +1,13 @@ +// Type definitions for react-leaflet-markercluster 2.0 +// Project: https://github.com/YUzhva/react-leaflet-markercluster +// Definitions by: Adam Binford +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// +import * as Leaflet from 'leaflet'; +import * as ReactLeaflet from 'react-leaflet'; + +export type MarkerClusterGroupProps = ReactLeaflet.MapLayerProps & Leaflet.MarkerClusterGroupOptions; + +export default class MarkerClusterGroup

          extends ReactLeaflet.MapLayer

          { } diff --git a/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx new file mode 100644 index 0000000000..9fc901c527 --- /dev/null +++ b/types/react-leaflet-markercluster/react-leaflet-markercluster-tests.tsx @@ -0,0 +1,30 @@ +import * as React from 'react'; +import * as Leaflet from 'leaflet'; +import MarkerClusterGroup from 'react-leaflet-markercluster'; + +const MarkerCluster = ( + Leaflet.divIcon({ html: `${cluster.getChildCount()}` }) }/> +); diff --git a/types/react-leaflet-markercluster/tsconfig.json b/types/react-leaflet-markercluster/tsconfig.json new file mode 100644 index 0000000000..071c9c734d --- /dev/null +++ b/types/react-leaflet-markercluster/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-leaflet-markercluster-tests.tsx" + ] +} diff --git a/types/react-leaflet-markercluster/tslint.json b/types/react-leaflet-markercluster/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-leaflet-markercluster/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } 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-lifecycle-component/package.json b/types/react-lifecycle-component/package.json index bb0e2b57d2..7f5b19d45b 100644 --- a/types/react-lifecycle-component/package.json +++ b/types/react-lifecycle-component/package.json @@ -3,4 +3,4 @@ "dependencies": { "redux": "^4.0.0" } -} \ No newline at end of file +} diff --git a/types/react-loadable/index.d.ts b/types/react-loadable/index.d.ts index b27a4de764..bf8af8e794 100644 --- a/types/react-loadable/index.d.ts +++ b/types/react-loadable/index.d.ts @@ -1,6 +1,6 @@ // Type definitions for react-loadable 5.4 // Project: https://github.com/thejameskyle/react-loadable#readme -// Definitions by: Diogo Franco +// Definitions by: Jessica Franco // Oden S. // Ian Ker-Seymer // Tomek Łaziuk 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-mailchimp-subscribe/index.d.ts b/types/react-mailchimp-subscribe/index.d.ts index 55b5c487ed..ed0165ed00 100644 --- a/types/react-mailchimp-subscribe/index.d.ts +++ b/types/react-mailchimp-subscribe/index.d.ts @@ -2,7 +2,7 @@ // Project: https://revolunet.github.io/react-mailchimp-subscribe/ // Definitions by: Omar Diab // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.8 +// TypeScript Version: 2.9 import { Component, ReactNode } from "react"; diff --git a/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx b/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx index 0507d7657a..d09ef6cc9a 100644 --- a/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx +++ b/types/react-mailchimp-subscribe/react-mailchimp-subscribe-tests.tsx @@ -25,9 +25,7 @@ const Example: React.StatelessComponent = () => ( )} url="spam.biz/subscribe" /> - { /* once Typescript 2.9 is out, generics in components will be allowed, at that point uncomment these. */ } - { /* https://github.com/Microsoft/TypeScript/pull/22415 */ } - {/* + render={(hooks) => ( { @@ -52,6 +50,6 @@ const Example: React.StatelessComponent = () => ( /> )} url="spam.biz/subscribe" - /> */} + /> ); diff --git a/types/react-map-gl/index.d.ts b/types/react-map-gl/index.d.ts index 9e4796910b..3fea6a3ea9 100644 --- a/types/react-map-gl/index.d.ts +++ b/types/react-map-gl/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-map-gl 3.3 +// Type definitions for react-map-gl 4.0 // Project: https://github.com/uber/react-map-gl#readme // Definitions by: Robert Imig // Fabio Berta @@ -9,16 +9,18 @@ import * as React from 'react'; import * as MapboxGL from 'mapbox-gl'; import * as GeoJSON from 'geojson'; -export interface Viewport { +export interface ViewState { latitude: number; longitude: number; zoom: number; bearing?: number; pitch?: number; + altitude?: number; } export interface MapError { - message: string; + error?: { message: string; status: number }; + status: number; } export interface MapRequest { @@ -27,31 +29,37 @@ export interface MapRequest { credentials?: string; } -export interface MapboxProps extends Partial { - container?: {}; +export interface MapboxProps extends Partial { + container?: object; + gl?: object; mapboxApiAccessToken?: string; attributionControl?: boolean; preserveDrawingBuffer?: boolean; + reuseMaps?: boolean; + transformRequest?: (url?: string, resourceType?: string) => MapRequest; + mapOptions?: object; + mapStyle?: string | object; + visible?: boolean; onLoad?: () => void; onError?: (e: MapError) => void; - reuseMaps?: boolean; reuseMap?: boolean; - transformRequest?: (url?: string, resourceType?: string) => MapRequest; - - mapStyle?: string | {}; - - width: number; - height: number; - - viewState?: Viewport; - - altitude?: number; // Note: Non-public API, see https://github.com/mapbox/mapbox-gl-js/issues/1137 + width: number | string; + height: number | string; + viewState?: ViewState; } export interface StaticMapProps extends MapboxProps { + onResize?: (dimensions: { width: number; height: number }) => void; preventStyleDiffing?: boolean; - visible?: boolean; + disableTokenWarning?: boolean; className?: string; + style?: object; + visibilityConstraints?: { + minZoom?: number; + maxZoom?: number; + minPitch?: number; + maxPitch?: number; + }; } export interface QueryRenderedFeaturesParams { @@ -64,14 +72,71 @@ export class StaticMap extends React.Component { queryRenderedFeatures(geometry?: MapboxGL.PointLike | MapboxGL.PointLike[], parameters?: QueryRenderedFeaturesParams): Array>; } -export interface InteractiveMapState { +export interface ExtraState { isDragging: boolean; isHovering: boolean; } -export interface MapEvent { - lngLat: [number, number]; - features: Array<{}>; +export interface PositionInput { + pos: [number, number]; +} + +export interface MapControllerOptions { + onViewportChange?: (viewState: ViewState) => void; + onStateChange?: (state: MapState) => void; + eventManager?: any; + isInteractive: boolean; + scrollZoom?: boolean; + dragPan?: boolean; + dragRotate?: boolean; + doubleClickZoom?: boolean; + touchZoom?: boolean; + touchRotate?: boolean; + keyboard?: boolean; +} + +export interface ViewportProps { + width: number; + height: number; + latitude: number; + longitude: number; + zoom: number; + bearing: number; + pitch: number; + altitude: number; + maxZoom: number; + minZoom: number; + maxPitch: number; + minPitch: number; + transitionDuration?: number; + transitionInterpolator?: TransitionInterpolator; + transitionInterruption?: TRANSITION_EVENTS; + transitionEasing?: EasingFunction; +} + +export interface InteractiveState { + startPanLngLat?: [number, number]; + startZoomLngLat?: [number, number]; + startBearing?: number; + startPitch?: number; + startZoom?: number; +} + +export type MapStateProps = Partial; + +export class MapState { + constructor(props: MapStateProps); + getViewportProps(): ViewportProps; + getInteractiveState(): InteractiveState; + panStart(input: PositionInput): MapState; + pan(input: PositionInput & { startPos?: [number, number] }): MapState; + panEnd(): MapState; + rotateStart(input: PositionInput): MapState; + rotate(input: { deltaScaleX?: number; deltaScaleY?: number }): MapState; + rotateEnd(): MapState; + zoomStart(input: PositionInput): MapState; + zoom(input: PositionInput & { scale: number; startPos?: [number, number] }): MapState; + zoomEnd(): MapState; } export interface Center { @@ -93,11 +158,30 @@ export interface MapControlEvent { delta?: number; } -export interface BaseMapControls { +export interface BaseMapController { events: string[]; handleEvent(event: MapControlEvent): void; } +export class MapController implements BaseMapController { + events: string[]; + handleEvent(event: MapControlEvent): void; + getMapState(overrides: Partial): MapState; + setOptions(options: MapControllerOptions): void; + setState(newState: MapState): void; + updateViewport(newMapState: MapState, extraProps: any, extraState: ExtraState): void; +} + +export interface PointerEvent { + type: string; + point: [number, number]; + lngLat: [number, number]; + target: any; + srcEvent: any; + // backward compatibility: v3 interface + features: any[]; +} + export type EasingFunction = (t: number) => number; export enum TRANSITION_EVENTS { @@ -115,7 +199,7 @@ export class LinearInterpolator extends TransitionInterpolator { export class FlyToInterpolator extends TransitionInterpolator {} export interface ViewStateChangeInfo { - viewState: Viewport; + viewState: ViewState; } export interface InteractiveMapProps extends StaticMapProps { @@ -123,10 +207,9 @@ export interface InteractiveMapProps extends StaticMapProps { minZoom?: number; maxPitch?: number; minPitch?: number; - - onViewportChange?: (viewport: Viewport) => void; onViewStateChange?: (info: ViewStateChangeInfo) => void; - + onViewportChange?: (viewState: ViewState) => void; + onInteractionStateChange?: (state: ExtraState) => void; transitionDuration?: number; transitionInterpolator?: TransitionInterpolator; transitionInterruption?: TRANSITION_EVENTS; @@ -134,7 +217,6 @@ export interface InteractiveMapProps extends StaticMapProps { onTransitionStart?: () => void; onTransitionInterrupt?: () => void; onTransitionEnd?: () => void; - scrollZoom?: boolean; dragPan?: boolean; dragRotate?: boolean; @@ -142,26 +224,25 @@ export interface InteractiveMapProps extends StaticMapProps { touchZoom?: boolean; touchRotate?: boolean; keyboard?: boolean; - - onHover?: (event: MapEvent, lngLat: number[], features: any) => void; - onClick?: (event: MapEvent, lngLat: number[], features: any) => void; - - onContextMenu?: (event: MapEvent) => void; - + onHover?: (event: PointerEvent) => void; + onClick?: (event: PointerEvent) => void; + onDblClick?: (event: PointerEvent) => void; + onContextMenu?: (event: PointerEvent) => void; + onMouseDown?: (event: PointerEvent) => void; + onMouseMove?: (event: PointerEvent) => void; + onMouseUp?: (event: PointerEvent) => void; + onTouchStart?: (event: PointerEvent) => void; + onTouchMove?: (event: PointerEvent) => void; + onTouchEnd?: (event: PointerEvent) => void; + onMouseEnter?: (event: PointerEvent) => void; + onMouseLeave?: (event: PointerEvent) => void; + onMouseOut?: (event: PointerEvent) => void; + onWheel?: (event: PointerEvent) => void; touchAction?: string; - clickRadius?: number; - - getCursor?: (state: InteractiveMapState) => void; - - visibilityConstraints?: { - minZoom?: number; - maxZoom?: number; - minPitch?: number; - maxPitch?: number; - }; - - mapControls?: BaseMapControls; + interactiveLayerIds?: string[]; + getCursor?: (state: ExtraState) => void; + controller?: MapController; } export class InteractiveMap extends React.Component { @@ -180,12 +261,21 @@ export interface BaseControlProps { export class BaseControl extends React.Component {} +export interface DragEvent { + lngLat: [number, number]; + [key: string]: any; +} + export interface MarkerProps extends BaseControlProps { className?: string; longitude: number; latitude: number; offsetLeft?: number; offsetTop?: number; + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; } export class Marker extends BaseControl {} @@ -194,6 +284,7 @@ export interface PopupProps extends BaseControlProps { className?: string; longitude: number; latitude: number; + altitude?: number; offsetLeft?: number; offsetTop?: number; tipSize?: number; @@ -201,6 +292,7 @@ export interface PopupProps extends BaseControlProps { closeOnClick?: boolean; anchor?: 'top' | 'top-left' | 'top-right' | 'bottom' | 'bottom-left' | 'bottom-right' | 'left' | 'right'; dynamicPosition?: boolean; + sortByDepth?: boolean; onClose?: () => void; } @@ -209,13 +301,22 @@ export class Popup extends BaseControl {} export interface NavigationControlProps extends BaseControlProps { className?: string; onViewStateChange: (info: ViewStateChangeInfo) => void; - onViewportChange: (viewport: Viewport) => void; + onViewportChange: (viewport: ViewState) => void; showCompass?: boolean; showZoom?: boolean; } export class NavigationControl extends BaseControl {} +export interface DraggableControlProps extends BaseControlProps { + draggable?: boolean; + onDrag?: (event: DragEvent) => void; + onDragEnd?: (event: DragEvent) => void; + onDragStart?: (event: DragEvent) => void; +} + +export class DraggableControl extends BaseControl {} + export interface HTMLRedrawOptions { width: number; height: number; @@ -248,61 +349,3 @@ export interface SVGOverlayProps extends BaseControlProps { } export class SVGOverlay extends BaseControl {} - -export namespace experimental { - interface Options { - // TODO(deprecate): remove this when `onChangeViewport` gets deprecated - onChangeViewport?: (viewport: Viewport) => void; - // TODO(deprecate): remove this when `touchZoomRotate` gets deprecated - touchZoomRotate?: boolean; - - onViewStateChange?: (info: ViewStateChangeInfo) => void; - onViewportChange?: (viewport: Viewport) => void; - onStateChange?: (state: MapState) => void; - eventManager?: any; - scrollZoom?: boolean; - dragPan?: boolean; - dragRotate?: boolean; - doubleClickZoom?: boolean; - touchZoom?: boolean; - touchRotate?: boolean; - keyboard?: boolean; - } - - class MapState implements Viewport { - width: number; - height: number; - latitude: number; - longitude: number; - zoom: number; - bearing?: number; - pitch?: number; - altitude?: number; - - maxZoom?: number; - minZoom?: number; - maxPitch?: number; - minPitch?: number; - - transitionDuration?: number; - transitionInterpolator?: TransitionInterpolator; - transitionInterruption?: TRANSITION_EVENTS; - transitionEasing?: EasingFunction; - - startPanLngLat?: [number, number]; - startZoomLngLat?: [number, number]; - startBearing?: number; - startPitch?: number; - startZoom?: number; - } - - class MapControls implements BaseMapControls { - events: string[]; - - handleEvent(event: MapControlEvent): void; - getMapState(overrides: Partial): MapState; - setOptions(options: Options): void; - setState(newState: MapState): void; - updateViewport(newMapState: MapState, extraProps: any, extraState: InteractiveMapState): void; - } -} diff --git a/types/react-map-gl/react-map-gl-tests.tsx b/types/react-map-gl/react-map-gl-tests.tsx index 7eb5bfd590..c9024287c9 100644 --- a/types/react-map-gl/react-map-gl-tests.tsx +++ b/types/react-map-gl/react-map-gl-tests.tsx @@ -1,6 +1,6 @@ import * as React from "react"; import { - Viewport, + ViewState, InteractiveMap, CanvasOverlay, SVGOverlay, @@ -13,12 +13,12 @@ import { import * as MapboxGL from "mapbox-gl"; interface State { - viewport: Viewport; + viewState: ViewState; } class MyMap extends React.Component<{}, State> { readonly state: State = { - viewport: { + viewState: { bearing: 0, latitude: 0, longitude: 0, @@ -31,14 +31,14 @@ class MyMap extends React.Component<{}, State> { return (

          { + redraw={opts => { const { ctx, height, @@ -51,7 +51,7 @@ class MyMap extends React.Component<{}, State> { }} /> {}} + redraw={opts => {}} captureScroll={true} captureDrag={true} captureClick={true} @@ -61,7 +61,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -79,7 +79,7 @@ class MyMap extends React.Component<{}, State> { redraw={() => {}} /> { + redraw={opts => { const { height, project, @@ -98,7 +98,7 @@ class MyMap extends React.Component<{}, State> { /> +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 +import * as React from "react"; + +/** + * MentionsInput is the main component rendering the textarea control. It takes one or multiple Mention components as its children. + */ +export const MentionsInput: MentionsInputClass; + +/** + * Each Mention component represents a data source for a specific class of mentionable objects, such as users, template variables, issues, etc. + */ +export const Mention: React.SFC; + +/** + * The properties for the @see MentionsInput component. + */ +export interface MentionsInputProps { + /** + * If set to `true` a regular text input element will be rendered + * instead of a textarea + */ + singleLine?: boolean; + /** + * If set to `true` spaces will not interrupt matching suggestions + */ + allowSpaceInQuery?: boolean; + markup?: string; + value?: string; + displayTransform?: DisplayTransformFunc; + onChange?: OnChangeHandlerFunc; + placeholder?: string; + onBlur?: (event: React.FocusEvent | React.FocusEvent, clickedSuggestion: boolean) => void; + onSelect?: (event: React.UIEvent) => void; + onKeyDown?: (event: React.KeyboardEvent | React.KeyboardEvent) => void; + children: React.ReactElement | Array>; + className?: string; + style?: any; + regex?: RegExp; + suggestionsPortalHost?: Element; +} + +/** + * Exposes the type for use with the @see MentionsInputComponent.wrappedInstance which is added by react-mentions' use of substyle (https://github.com/jfschwarz/substyle). + */ +export interface MentionsInputComponentUnrwapped extends React.Component { + inputRef?: HTMLInputElement | HTMLTextAreaElement; +} + +/** + * Used with @see React.RefObject. + */ +export interface MentionsInputComponent extends React.Component { + // MentionsInput uses substyle (https://github.com/jfschwarz/substyle) which adds this wrappedInstance + wrappedInstance?: MentionsInputComponentUnrwapped; +} + +/** + * Used to reference MentionsInput element in a TSX file. + */ +export interface MentionsInputClass extends React.ComponentClass { +} + +/** + * Props definition for a mention subelement. + */ +export interface MentionProps { + type?: string; + onAdd?: (id: string | number, display: string) => void; + renderSuggestion?: (suggestion: SuggestionDataItem, search: string, highlightedDisplay: React.ReactNode, index: number, focused: boolean) => React.ReactNode; + className?: string; + trigger: string | RegExp; + isLoading?: boolean; + data: SuggestionDataItem[] | DataFunc; + style?: any; + appendSpaceOnAdd?: boolean; +} + +/** + * The shape of a mention. + */ +export interface MentionItem { + display: string; + id: string; + type: null; +} + +/** + * The shape of suggestion items. + */ +export interface SuggestionDataItem { + id: string | number; + display: string; +} + +/** + * Defines the function signature for implementing @see MentionsInputProps.displayTransform + */ +export type DisplayTransformFunc = (id: string, display: string, type: string) => string; + +/** + * Defines the function signature for implementing @see MentionsInputProps.onChange + */ +export type OnChangeHandlerFunc = (event: { target: { value: string } }, newValue: string, newPlainTextValue: string, mentions: MentionItem[]) => void; + +/** + * The function to implement asynchronous loading of suggestions in @see MentionProps.data . + */ +export type DataFunc = (query: string, callback: (data: SuggestionDataItem[]) => void) => void | SuggestionDataItem[]; diff --git a/types/react-mentions/lib/utils.d.ts b/types/react-mentions/lib/utils.d.ts new file mode 100644 index 0000000000..ab0d1e7aed --- /dev/null +++ b/types/react-mentions/lib/utils.d.ts @@ -0,0 +1,17 @@ +import { DisplayTransformFunc } from "../"; + +/** + * For the passed character index in the plain text string, returns the corresponding index in the marked up value string. + * If the passed character index lies inside a mention, the value of `inMarkupCorrection` defines the correction to apply: + * - 'START' to return the index of the mention markup's first char (default) + * - 'END' to return the index after its last char + * - 'NULL' to return null + */ +export function mapPlainTextIndex( + value: string, + markup: string, + indexInPlainText: number, + inMarkupCorrection: string, + displayTransform: DisplayTransformFunc, + regex: RegExp +): number; diff --git a/types/react-mentions/react-mentions-tests.tsx b/types/react-mentions/react-mentions-tests.tsx new file mode 100644 index 0000000000..49f5180720 --- /dev/null +++ b/types/react-mentions/react-mentions-tests.tsx @@ -0,0 +1,60 @@ +import * as React from "react"; +import { MentionsInput, Mention, SuggestionDataItem } from "react-mentions"; +import { mapPlainTextIndex } from "react-mentions/lib/utils"; + +interface TestProps { + data: SuggestionDataItem[]; + value?: string; + onChange?: () => void; + onAdd?: () => void; + regex: RegExp; +} + +export const TestSimple: React.SFC = (props) => { + return ( + `@${login}`} + > + + + ); +}; + +export const TestMultipleTrigger: React.SFC = (props) => { + return ( + + ( +
          + {highlightedDisplay} +
          + )} + onAdd={props.onAdd} + /> + + [{ id: search, display: search }]} + onAdd={props.onAdd} + /> +
          + ); +}; + +mapPlainTextIndex("foo", "bar", 1, "NULL", login => `@${login}`, /.*/); // $ExpectType number diff --git a/types/react-mentions/tsconfig.json b/types/react-mentions/tsconfig.json new file mode 100644 index 0000000000..260c003e2d --- /dev/null +++ b/types/react-mentions/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, + "jsx": "react" + }, + "files": [ + "index.d.ts", + "lib/utils.d.ts", + "react-mentions-tests.tsx" + ] +} diff --git a/types/react-mentions/tslint.json b/types/react-mentions/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-mentions/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-modal/index.d.ts b/types/react-modal/index.d.ts index 237c725332..d04a6b5c18 100644 --- a/types/react-modal/index.d.ts +++ b/types/react-modal/index.d.ts @@ -1,11 +1,12 @@ -// Type definitions for react-modal 3.2 +// Type definitions for react-modal 3.6 // Project: https://github.com/reactjs/react-modal // Definitions by: Rajab Shakirov , // Drew Noakes , // Thomas B Homburg , // Tatu Tamminen , // Uwe Wiemer , -// Peter Blazejewicz +// Peter Blazejewicz , +// Justin Powell // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -48,6 +49,9 @@ declare namespace ReactModal { /* String className to be applied to the document.body. */ bodyOpenClassName?: string; + /* String className to be applied to the document.html. */ + htmlOpenClassName?: string; + /* String or object className to be applied to the modal content. */ className?: string | Classes; @@ -87,6 +91,9 @@ declare namespace ReactModal { /* Additional aria attributes. */ aria?: Aria; + /* Additional data attributes to be applied to to the modal content in the form of "data-*" */ + data?: any; + /* String indicating the role of the modal, allowing the 'dialog' role to be applied if desired. */ role?: string; diff --git a/types/react-modal/react-modal-tests.tsx b/types/react-modal/react-modal-tests.tsx index 463ac1c7be..8dfd6d35e3 100644 --- a/types/react-modal/react-modal-tests.tsx +++ b/types/react-modal/react-modal-tests.tsx @@ -51,6 +51,10 @@ class ExampleOfUsingReactModal extends React.Component { labelledby: 'labelledby', describedby: 'describedby' }; + const customDataVariables = { + dataOne: 'one', + dataTwo: 'two' + }; return ( this.contentRef = instance} overlayRef={instance => this.overlayRef = instance} > diff --git a/types/react-native-auth0/index.d.ts b/types/react-native-auth0/index.d.ts index d6bd3e7cf1..7508386166 100644 --- a/types/react-native-auth0/index.d.ts +++ b/types/react-native-auth0/index.d.ts @@ -70,6 +70,11 @@ export interface UserInfoParams { token: string; } +export interface ResetPasswordParams { + email: string; + connection: string; +} + export interface UserInfo { email: string; emailVerified: boolean; @@ -88,6 +93,7 @@ export class Auth { passwordRealm(params: PasswordRealmParams): Promise; refreshToken(params: RefreshTokenParams): Promise; + resetPassword(params: ResetPasswordParams): Promise; revoke(params: RevokeParams): Promise; userInfo(params: UserInfoParams): Promise; } diff --git a/types/react-native-auth0/react-native-auth0-tests.ts b/types/react-native-auth0/react-native-auth0-tests.ts index 068833e349..8a10d5d2b6 100644 --- a/types/react-native-auth0/react-native-auth0-tests.ts +++ b/types/react-native-auth0/react-native-auth0-tests.ts @@ -49,6 +49,11 @@ auth0.auth.refreshToken({ scope: "openid" }); +auth0.auth.resetPassword({ + email: "me@example.com", + connection: "db-connection" +}); + auth0.auth.revoke({ refreshToken: "refresh-token" }); diff --git a/types/react-native-bluetooth-serial/tsconfig.json b/types/react-native-bluetooth-serial/tsconfig.json index 213f3fd025..80b4865dd3 100644 --- a/types/react-native-bluetooth-serial/tsconfig.json +++ b/types/react-native-bluetooth-serial/tsconfig.json @@ -1,10 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, diff --git a/types/react-native-calendars/index.d.ts b/types/react-native-calendars/index.d.ts index 647e64c0f2..402a3fff1a 100644 --- a/types/react-native-calendars/index.d.ts +++ b/types/react-native-calendars/index.d.ts @@ -2,6 +2,7 @@ // Project: https://github.com/wix/react-native-calendars#readme // Definitions by: Tyler Zhang // David Noreña +// Fabian Meul // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -23,6 +24,10 @@ export interface CalendarDot { selectedDotColor?: string; } +export interface CalendarThemeIdStyle { + [themeId: string]: ViewStyle | TextStyle; +} + export interface CalendarTheme { arrowColor?: string; backgroundColor?: string; @@ -43,6 +48,17 @@ export interface CalendarTheme { textMonthFontSize?: number; textSectionTitleColor?: string; todayTextColor?: string; + + // Theme ID's to style for + "stylesheet.calendar.header"?: CalendarThemeIdStyle; + "stylesheet.calendar.main"?: CalendarThemeIdStyle; + "stylesheet.calendar-list.main"?: CalendarThemeIdStyle; + "stylesheet.agenda.main"?: CalendarThemeIdStyle; + "stylesheet.agenda.list"?: CalendarThemeIdStyle; + "stylesheet.day.basic"?: CalendarThemeIdStyle; + "stylesheet.day.single"?: CalendarThemeIdStyle; + "stylesheet.day.multiDot"?: CalendarThemeIdStyle; + "stylesheet.day.period"?: CalendarThemeIdStyle; } export type DateCallbackHandler = (date: DateObject) => void; @@ -319,6 +335,11 @@ export interface CalendarListBaseProps extends CalendarBaseProps { * Enable or disable vertical scroll indicator. Default = false */ showScrollIndicator?: boolean; + + /** + * Initially selected day + */ + selected?: string; } export class CalendarList extends React.Component { } diff --git a/types/react-native-datepicker/tsconfig.json b/types/react-native-datepicker/tsconfig.json index b1dd56e20d..875993fd09 100644 --- a/types/react-native-datepicker/tsconfig.json +++ b/types/react-native-datepicker/tsconfig.json @@ -1,10 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, 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-doc-viewer/tsconfig.json b/types/react-native-doc-viewer/tsconfig.json index 86d578084a..e49d63b19e 100644 --- a/types/react-native-doc-viewer/tsconfig.json +++ b/types/react-native-doc-viewer/tsconfig.json @@ -1,10 +1,7 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6", - "dom" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, 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-drawer-layout/tsconfig.json b/types/react-native-drawer-layout/tsconfig.json index a0d6721b68..acad3b04bc 100644 --- a/types/react-native-drawer-layout/tsconfig.json +++ b/types/react-native-drawer-layout/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-drawer/tsconfig.json b/types/react-native-drawer/tsconfig.json index 1617e4715b..2624c7bb76 100644 --- a/types/react-native-drawer/tsconfig.json +++ b/types/react-native-drawer/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx index 7d1210f06a..5d4abb0117 100644 --- a/types/react-native-fbsdk/react-native-fbsdk-tests.tsx +++ b/types/react-native-fbsdk/react-native-fbsdk-tests.tsx @@ -2,6 +2,8 @@ import * as React from 'react'; import * as FBSDK from 'react-native-fbsdk'; import { View } from 'react-native'; +declare function alert(s: string): void; + const { LoginButton, AccessToken, diff --git a/types/react-native-fbsdk/tsconfig.json b/types/react-native-fbsdk/tsconfig.json index 0eae296778..e01b522313 100644 --- a/types/react-native-fbsdk/tsconfig.json +++ b/types/react-native-fbsdk/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-flip-card/index.d.ts b/types/react-native-flip-card/index.d.ts new file mode 100644 index 0000000000..6fc1156a1a --- /dev/null +++ b/types/react-native-flip-card/index.d.ts @@ -0,0 +1,46 @@ +// Type definitions for react-native-flip-card 3.5 +// Project: https://github.com/moschan/react-native-flip-card +// Definitions by: Jake Chapman +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import { Component, ReactNode, ComponentClass } from "react"; +import { + ViewProps, + TextProps, + StyleProp, + TextInputProps, + ViewStyle +} from "react-native"; + +// FlipCard +export interface FlipCardProps { + style?: StyleProp; + flip?: boolean; + friction?: number; + perspective?: number; + flipHorizontal?: boolean; + flipVertical?: boolean; + clickable?: boolean; + onFlipEnd?: () => void; + onFlipStart?: () => void; + alignHeight?: boolean; + alignWidth?: boolean; + useNativeDriver?: boolean; +} +// Face +export interface FaceProps { + chilren: JSX.Element[]; +} + +// Back +export interface BackProps { + flipHorizontal: boolean; + flipVertical: boolean; + perspective: number; + chilren: JSX.Element[]; +} + +export const Face: ComponentClass; +export const Back: ComponentClass; +export default class FlipCard extends Component {} diff --git a/types/react-native-flip-card/react-native-flip-card-tests.tsx b/types/react-native-flip-card/react-native-flip-card-tests.tsx new file mode 100644 index 0000000000..e741589be4 --- /dev/null +++ b/types/react-native-flip-card/react-native-flip-card-tests.tsx @@ -0,0 +1,33 @@ +import * as React from "react"; +import { View, Text, StyleSheet } from "react-native"; + +// Component +import FlipCard from "react-native-flip-card"; + +export default class FlipCardTest extends React.Component { + render() { + return ( + {}} + onFlipEnd={() => {}} + alignHeight={false} + alignWidth={false} + useNativeDriver={true} + > + + Front + + + Back + + + ); + } +} diff --git a/types/react-native-flip-card/tsconfig.json b/types/react-native-flip-card/tsconfig.json new file mode 100644 index 0000000000..92f1878d71 --- /dev/null +++ b/types/react-native-flip-card/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" + }, + "files": [ + "index.d.ts", + "react-native-flip-card-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-native-flip-card/tslint.json b/types/react-native-flip-card/tslint.json new file mode 100644 index 0000000000..30a1bdde2e --- /dev/null +++ b/types/react-native-flip-card/tslint.json @@ -0,0 +1,3 @@ +{ + "extends": "dtslint/dt.json" +} \ No newline at end of file diff --git a/types/react-native-fs/tsconfig.json b/types/react-native-fs/tsconfig.json index f491bb6a7a..5e4ae5b88a 100644 --- a/types/react-native-fs/tsconfig.json +++ b/types/react-native-fs/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-google-signin/index.d.ts b/types/react-native-google-signin/index.d.ts index 8bb895ce90..54e19715e1 100644 --- a/types/react-native-google-signin/index.d.ts +++ b/types/react-native-google-signin/index.d.ts @@ -1,7 +1,9 @@ -// Type definitions for react-native-google-signin 0.13 +// Type definitions for react-native-google-signin 1.0 // Project: https://github.com/devfd/react-native-google-signin // Definitions by: Jacob Froman // Michele Bombardi +// Christian Chown +// Eric Chen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -11,6 +13,7 @@ import { ViewProps } from 'react-native'; export interface GoogleSigninButtonProps extends ViewProps { size?: GoogleSigninButton.Size; color?: GoogleSigninButton.Color; + disabled?: boolean; onPress?(): void; } @@ -33,10 +36,11 @@ export namespace GoogleSigninButton { export interface HasPlayServicesParams { /** - * When autoresolve is true, the user will be prompted to install Play - * Services if on Android and they are not installed. + * When showPlayServicesUpdateDialog is true, the user will be prompted to + * install Play Services if on Android and they are not installed. + * Default is true */ - autoResolve?: boolean; + showPlayServicesUpdateDialog?: boolean; } export interface ConfigureParams { @@ -45,16 +49,16 @@ export interface ConfigureParams { */ scopes?: string[]; - /** - * iOS client ID from Developer Console. Required for iOS. - */ - iosClientId?: string; - /** * Web client ID from Developer Console. Required for offline access */ webClientId?: string; + /** + * If you want to specify the client ID of type iOS + */ + iosClientId?: string; + /** * Must be true if you wish to access user APIs on behalf of the user from * your own server @@ -78,22 +82,21 @@ export interface ConfigureParams { } export interface User { - id: string | null; - name: string | null; - email: string | null; + user: { + id: string | null; + name: string | null; + email: string | null; + photo: string | null; + familyName: string | null; + givenName: string | null; + }; scopes?: string[]; - photo: string | null; - familyName: string | null; - givenName: string | null; idToken: string | null; + accessToken: string | null; /** - * IOS ONLY. Use getAccessToken() on Android + * Deprecated */ - accessToken: string; - /** - * IOS ONLY. Use getAccessToken() on Android - */ - accessTokenExpirationDate: number; + accessTokenExpirationDate: number | null; /** * Not null only if a valid webClientId and offlineAccess: true was * specified in configure(). @@ -111,18 +114,13 @@ export namespace GoogleSignin { /** * Configures the library for login. MUST be called before attempting login */ - function configure(params?: ConfigureParams): Promise; + function configure(params?: ConfigureParams): void; /** - * Returns the current signed in user, or null if not signed in. - */ - function currentUser(): User | null; - - /** - * Returns a Promise that resolves with the current signed in user, or null + * Returns a Promise that resolves with the current signed in user or rejects * if not signed in. */ - function currentUserAsync(): Promise; + function signInSilently(): Promise; /** * Prompts the user to sign in with their Google account. Resolves with the @@ -135,20 +133,20 @@ export namespace GoogleSignin { */ function signOut(): Promise; - /** - * ANDROID ONLY. Resolves with the current signed in user's access token. - */ - function getAccessToken(): Promise; - /** * Removes your application from the user's authorized applications */ function revokeAccess(): Promise; + + /** + * Returns whether the user is currently signed in + */ + function isSignedIn(): Promise; } -export enum StatusCodes { - SIGN_IN_CANCELLED = '12501', - IN_PROGRESS = 'ASYNC_OP_IN_PROGRESS', - PLAY_SERVICES_NOT_AVAILABLE = 'PLAY_SERVICES_NOT_AVAILABLE', - SIGN_IN_REQUIRED = '4', -} +export const statusCodes: { + SIGN_IN_CANCELLED: string; + IN_PROGRESS: string; + PLAY_SERVICES_NOT_AVAILABLE: string; + SIGN_IN_REQUIRED: string; +}; diff --git a/types/react-native-google-signin/react-native-google-signin-tests.tsx b/types/react-native-google-signin/react-native-google-signin-tests.tsx index a8de31f0eb..f4f26bcc89 100644 --- a/types/react-native-google-signin/react-native-google-signin-tests.tsx +++ b/types/react-native-google-signin/react-native-google-signin-tests.tsx @@ -1,6 +1,6 @@ import * as React from 'react'; -import { GoogleSignin, GoogleSigninButton, User } from 'react-native-google-signin'; -import { StyleSheet, ViewStyle, View, Text, TouchableHighlight } from 'react-native'; +import { GoogleSignin, GoogleSigninButton, User, statusCodes } from 'react-native-google-signin'; +import { StyleSheet, View, Text, TouchableHighlight } from 'react-native'; interface State { user?: User; @@ -9,15 +9,25 @@ interface State { export default class Signin extends React.Component<{}, State> { state: State = {}; - componentDidMount() { + async componentDidMount() { GoogleSignin.configure({ scopes: ['https://www.googleapis.com/auth/drive.readonly'] - }).then(() => GoogleSignin.hasPlayServices({ autoResolve: true })); + }); + await GoogleSignin.hasPlayServices({ showPlayServicesUpdateDialog: true }); } async handleSigninPress(): Promise { - const user = await GoogleSignin.signIn(); - this.setState({ user }); + let user; + try { + user = await GoogleSignin.signInSilently(); + } catch (error) { + if (error.code === statusCodes.SIGN_IN_REQUIRED) { + user = await GoogleSignin.signIn(); + } + } + if (user) { + this.setState({ user }); + } } handleSignoutPress(): Promise { @@ -28,7 +38,7 @@ export default class Signin extends React.Component<{}, State> { if (this.state.user) { return ( - {this.state.user.name} + {this.state.user.user.name} this.handleSignoutPress()}> Sign Out diff --git a/types/react-native-huawei-protected-apps/index.d.ts b/types/react-native-huawei-protected-apps/index.d.ts new file mode 100644 index 0000000000..cecb0377c6 --- /dev/null +++ b/types/react-native-huawei-protected-apps/index.d.ts @@ -0,0 +1,19 @@ +// Type definitions for react-native-huawei-protected-apps 0.0 +// Project: https://github.com/pgengoux/react-native-huawei-protected-apps +// Definitions by: Christian Chown +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +export interface HuaweiProtectedAppsConfig { + title: string; + text: string; + doNotShowAgainText: string; + positiveText: string; + negativeText: string; +} + +declare let HuaweiProtectedApps: { + AlertIfHuaweiDevice(config: HuaweiProtectedAppsConfig): void; +}; + +export default HuaweiProtectedApps; diff --git a/types/react-native-huawei-protected-apps/react-native-huawei-protected-apps-tests.tsx b/types/react-native-huawei-protected-apps/react-native-huawei-protected-apps-tests.tsx new file mode 100644 index 0000000000..8bb0047300 --- /dev/null +++ b/types/react-native-huawei-protected-apps/react-native-huawei-protected-apps-tests.tsx @@ -0,0 +1,12 @@ +import * as React from "react"; +import HuaweiProtectedApps from "react-native-huawei-protected-apps"; + +const config = { + title: "Huawei Protected Apps", + text: "This app requires to be enabled in 'Protected Apps' in order to receive push notifcations", + doNotShowAgainText: "Do not show again", + positiveText: "PROTECTED APPS", + negativeText: "CANCEL" +}; + +HuaweiProtectedApps.AlertIfHuaweiDevice(config); diff --git a/types/react-native-huawei-protected-apps/tsconfig.json b/types/react-native-huawei-protected-apps/tsconfig.json new file mode 100644 index 0000000000..3c79da2804 --- /dev/null +++ b/types/react-native-huawei-protected-apps/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react-native", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-huawei-protected-apps-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-native-huawei-protected-apps/tslint.json b/types/react-native-huawei-protected-apps/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/react-native-huawei-protected-apps/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/react-native-material-design-searchbar/tsconfig.json b/types/react-native-material-design-searchbar/tsconfig.json index 41e6dc8bab..ad0e5ff24f 100644 --- a/types/react-native-material-design-searchbar/tsconfig.json +++ b/types/react-native-material-design-searchbar/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-material-kit/tsconfig.json b/types/react-native-material-kit/tsconfig.json index f18bd089b8..5ec874cdac 100644 --- a/types/react-native-material-kit/tsconfig.json +++ b/types/react-native-material-kit/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-material-textfield/tsconfig.json b/types/react-native-material-textfield/tsconfig.json index b3c2a6ebba..93b14898f2 100644 --- a/types/react-native-material-textfield/tsconfig.json +++ b/types/react-native-material-textfield/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-material-ui/tsconfig.json b/types/react-native-material-ui/tsconfig.json index 7c215a4a8b..770ecbe42c 100644 --- a/types/react-native-material-ui/tsconfig.json +++ b/types/react-native-material-ui/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-modalbox/react-native-modalbox-tests.tsx b/types/react-native-modalbox/react-native-modalbox-tests.tsx index a2e54a7653..31f104161f 100644 --- a/types/react-native-modalbox/react-native-modalbox-tests.tsx +++ b/types/react-native-modalbox/react-native-modalbox-tests.tsx @@ -16,6 +16,8 @@ interface State { sliderValue: number; } +const screen = Dimensions.get('window'); + class Example extends React.Component<{}, State> { modal1: Modal; modal2: Modal; diff --git a/types/react-native-modalbox/tsconfig.json b/types/react-native-modalbox/tsconfig.json index 1c41f2e346..8b996efbab 100644 --- a/types/react-native-modalbox/tsconfig.json +++ b/types/react-native-modalbox/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-popup-dialog/index.d.ts b/types/react-native-popup-dialog/index.d.ts index 3ff12802f4..dcf6e5cb1c 100644 --- a/types/react-native-popup-dialog/index.d.ts +++ b/types/react-native-popup-dialog/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-native-popup-dialog 1.0 +// Type definitions for react-native-popup-dialog 0.16 // Project: https://github.com/jacklam718/react-native-popup-dialog/blob/master/README.md // Definitions by: Paito Anderson // connectdotz @@ -55,7 +55,7 @@ export interface PopupDialogProps { dismissOnTouchOutside?: boolean; dismissOnHardwareBackPress?: boolean; haveOverlay?: boolean; - show?: boolean; + visible?: boolean; onShown?: () => void; onDismissed?: () => void; actions?: any[]; diff --git a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx index 379d4fd788..95bfa66f4e 100644 --- a/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx +++ b/types/react-native-popup-dialog/react-native-popup-dialog-tests.tsx @@ -72,7 +72,7 @@ class Test extends React.Component { dismissOnTouchOutside={false} dismissOnHardwareBackPress={false} haveOverlay={true} - show={true} + visible={true} onShown={() => { console.log('onShown'); }} onDismissed={() => { console.log('onDismissed'); }} /> diff --git a/types/react-native-popup-dialog/tsconfig.json b/types/react-native-popup-dialog/tsconfig.json index f870dbf139..a2cc61cfc5 100644 --- a/types/react-native-popup-dialog/tsconfig.json +++ b/types/react-native-popup-dialog/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-qrcode/tsconfig.json b/types/react-native-qrcode/tsconfig.json index b21253194b..3747539935 100644 --- a/types/react-native-qrcode/tsconfig.json +++ b/types/react-native-qrcode/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-referrer/index.d.ts b/types/react-native-referrer/index.d.ts new file mode 100644 index 0000000000..34f5429b4a --- /dev/null +++ b/types/react-native-referrer/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-referrer 0.1 +// Project: https://github.com/JeandeCampredon/react-native-referrer +// Definitions by: Christian Chown +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +declare let ReactNativeReferrer: { + getReferrer(): Promise; +}; + +export default ReactNativeReferrer; diff --git a/types/react-native-referrer/react-native-referrer-tests.tsx b/types/react-native-referrer/react-native-referrer-tests.tsx new file mode 100644 index 0000000000..4b7b3d88b8 --- /dev/null +++ b/types/react-native-referrer/react-native-referrer-tests.tsx @@ -0,0 +1,9 @@ +import * as React from "react"; +import { Platform } from "react-native"; +import ReactNativeReferrer from "react-native-referrer"; + +if (Platform.OS === 'android') { + ReactNativeReferrer.getReferrer().then(referrerString => { + console.log(referrerString); + }); +} diff --git a/types/react-native-referrer/tsconfig.json b/types/react-native-referrer/tsconfig.json new file mode 100644 index 0000000000..a1bcec56b8 --- /dev/null +++ b/types/react-native-referrer/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react-native", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-referrer-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-native-referrer/tslint.json b/types/react-native-referrer/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/react-native-referrer/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/react-native-restart/index.d.ts b/types/react-native-restart/index.d.ts new file mode 100644 index 0000000000..b73c06a291 --- /dev/null +++ b/types/react-native-restart/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-restart 0.0 +// Project: https://github.com/avishayil/react-native-restart#readme +// Definitions by: Christian Chown +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.9 + +declare let ReactNativeRestart: { + Restart(): void; +}; + +export default ReactNativeRestart; diff --git a/types/react-native-restart/react-native-restart-tests.tsx b/types/react-native-restart/react-native-restart-tests.tsx new file mode 100644 index 0000000000..dee25ace3d --- /dev/null +++ b/types/react-native-restart/react-native-restart-tests.tsx @@ -0,0 +1,4 @@ +import * as React from "react"; +import ReactNativeRestart from "react-native-restart"; + +ReactNativeRestart.Restart(); diff --git a/types/react-native-restart/tsconfig.json b/types/react-native-restart/tsconfig.json new file mode 100644 index 0000000000..85f654f9c1 --- /dev/null +++ b/types/react-native-restart/tsconfig.json @@ -0,0 +1,24 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": [ + "es6" + ], + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "jsx": "react-native", + "typeRoots": [ + "../" + ], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": [ + "index.d.ts", + "react-native-restart-tests.tsx" + ] +} \ No newline at end of file diff --git a/types/react-native-restart/tslint.json b/types/react-native-restart/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/react-native-restart/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/react-native-safe-area/index.d.ts b/types/react-native-safe-area/index.d.ts new file mode 100644 index 0000000000..fd38aec0a5 --- /dev/null +++ b/types/react-native-safe-area/index.d.ts @@ -0,0 +1,48 @@ +// Type definitions for react-native-safe-area 0.5 +// Project: https://github.com/miyabi/react-native-safe-area#readme +// Definitions by: Pavlos Vinieratos +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +/// + +import { EmitterSubscription } from 'react-native'; + +// from `TypeDefinition.js` +export interface SafeAreaInsets { top: number; left: number; bottom: number; right: number; } + +// from `SafeArea.[ios|android].js` +declare namespace SafeArea { + function getSafeAreaInsetsForRootView(): Promise<{ safeAreaInsets: SafeAreaInsets }>; + function addEventListener(eventType: string, listener: (...args: any[]) => any, context?: any): EmitterSubscription; + function removeEventListener(eventType: string, listener: (...args: any[]) => any): void; +} +export default SafeArea; + +// from `withSafeArea.js` +export type Direction = + | 'top' + | 'bottom' + | 'left' + | 'right' + | 'topLeft' // DEPRECATED + | 'topAndLeft' + | 'topRight' // DEPRECATED + | 'topAndRight' + | 'bottomLeft' // DEPRECATED + | 'bottomAndLeft' + | 'bottomRight' // DEPRECATED + | 'bottomAndRight' + | 'vertical' + | 'horizontal' + | 'verticalAndLeft' + | 'verticalAndRight' + | 'horizontalAndTop' + | 'horizontalAndBottom' + | 'all'; + +export function withSafeArea( + WrappedComponent: React.ComponentType, + applyTo?: 'margin' | 'padding' | 'absolutePosition' | 'contentInset', + direction?: Direction, +): React.ComponentType; diff --git a/types/react-native-safe-area/react-native-safe-area-tests.ts b/types/react-native-safe-area/react-native-safe-area-tests.ts new file mode 100644 index 0000000000..0dc931d026 --- /dev/null +++ b/types/react-native-safe-area/react-native-safe-area-tests.ts @@ -0,0 +1,4 @@ +import { View } from 'react-native'; +import { withSafeArea } from 'react-native-safe-area'; + +const SafeAreaView = withSafeArea(View); diff --git a/types/react-native-safe-area/tsconfig.json b/types/react-native-safe-area/tsconfig.json new file mode 100644 index 0000000000..6a88cd1448 --- /dev/null +++ b/types/react-native-safe-area/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", + "react-native-safe-area-tests.ts" + ] +} diff --git a/types/react-native-safe-area/tslint.json b/types/react-native-safe-area/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-safe-area/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-scaled-image/index.d.ts b/types/react-native-scaled-image/index.d.ts new file mode 100644 index 0000000000..cf938913a0 --- /dev/null +++ b/types/react-native-scaled-image/index.d.ts @@ -0,0 +1,17 @@ +// Type definitions for react-native-scaled-image 0.0 +// Project: https://github.com/nanlabs/react-native-scaled-image +// Definitions by: Matt Jaeger +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; +import { ImageSourcePropType, StyleProp, ImageStyle } from 'react-native'; + +export interface ScaledImageProps { + source: ImageSourcePropType; + height?: number; + width?: number; + style?: StyleProp; +} + +export default class ScaledImage extends React.Component {} diff --git a/types/react-native-scaled-image/react-native-scaled-image-tests.tsx b/types/react-native-scaled-image/react-native-scaled-image-tests.tsx new file mode 100644 index 0000000000..75d76c2843 --- /dev/null +++ b/types/react-native-scaled-image/react-native-scaled-image-tests.tsx @@ -0,0 +1,15 @@ +import * as React from 'react'; +import ScaledImage from 'react-native-scaled-image'; + +class Example extends React.Component { + render() { + return ( + + ); + } +} + +export default Example; diff --git a/types/react-native-scaled-image/tsconfig.json b/types/react-native-scaled-image/tsconfig.json new file mode 100644 index 0000000000..2f139b2f6c --- /dev/null +++ b/types/react-native-scaled-image/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "module": "commonjs", + "lib": ["es6"], + "jsx": "react-native", + "noImplicitAny": true, + "noImplicitThis": true, + "strictNullChecks": true, + "strictFunctionTypes": true, + "baseUrl": "../", + "typeRoots": ["../"], + "types": [], + "noEmit": true, + "forceConsistentCasingInFileNames": true + }, + "files": ["index.d.ts", "react-native-scaled-image-tests.tsx"] +} diff --git a/types/react-native-scaled-image/tslint.json b/types/react-native-scaled-image/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-scaled-image/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-scrollable-tab-view/index.d.ts b/types/react-native-scrollable-tab-view/index.d.ts index 9be23aa66c..d992012856 100644 --- a/types/react-native-scrollable-tab-view/index.d.ts +++ b/types/react-native-scrollable-tab-view/index.d.ts @@ -125,7 +125,7 @@ export default class ScrollableTabView extends React.Component = T & { - tabLabel: React.ReactType; + tabLabel: React.ReactChild; }; export interface DefaultTabBarProps { diff --git a/types/react-native-scrollable-tab-view/tsconfig.json b/types/react-native-scrollable-tab-view/tsconfig.json index 6b88cdde66..cc48436c97 100644 --- a/types/react-native-scrollable-tab-view/tsconfig.json +++ b/types/react-native-scrollable-tab-view/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-share/index.d.ts b/types/react-native-share/index.d.ts index d407d4df96..bf382a8b2c 100644 --- a/types/react-native-share/index.d.ts +++ b/types/react-native-share/index.d.ts @@ -1,32 +1,55 @@ -// Type definitions for react-native-share 1.0 +// Type definitions for react-native-share 1.1 // Project: https://github.com/react-native-community/react-native-share#readme // Definitions by: Mark Nelissen // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.1 declare namespace Share { - function open(options: OpenOptions): Promise; - function shareSingle(options: ShareSingleOptions): Promise; + function open(options: Options | MultipleOptions): Promise; + function shareSingle( + options: Options & { social: SupportedSocialApps } + ): Promise; } export default Share; -interface OpenOptions { - url: string; - type?: string; +interface OpenReturn { + app?: string; + dismissedAction?: boolean; +} + +interface ShareSingleReturn { message: string; +} + +interface Options { + url: string; + urls?: string[]; + type?: string; + message?: string; title?: string; subject?: string; excludedActivityTypes?: string; - showAppsToview?: boolean; + failOnCancel?: boolean; + showAppsToView?: boolean; } - -interface ShareSingleOptions { - url: string; +interface MultipleOptions { + url?: string; + urls: string[]; type?: string; - message: string; + message?: string; title?: string; subject?: string; - social: SupportedSocialApps; + excludedActivityTypes?: string; + failOnCancel?: boolean; + showAppsToView?: boolean; } -type SupportedSocialApps = 'twitter' | 'facebook' | 'whatsapp' | 'googleplus' | 'email'; +type SupportedSocialApps = + | "facebook" + | "pagesmanager" + | "twitter" + | "whatsapp" + | "instagram" + | "googleplus" + | "email"; diff --git a/types/react-native-share/react-native-share-tests.ts b/types/react-native-share/react-native-share-tests.ts index 375a4af4b6..a5702a9b59 100644 --- a/types/react-native-share/react-native-share-tests.ts +++ b/types/react-native-share/react-native-share-tests.ts @@ -1,12 +1,19 @@ import Share from 'react-native-share'; -// $ExpectType Promise +// $ExpectType Promise Share.open({ url: '', message: '', }); -// $ExpectType Promise +// $ExpectType Promise +Share.open({ + title: '', + message: '', + urls: [], +}); + +// $ExpectType Promise Share.open({ url: '', type: '', @@ -14,17 +21,17 @@ Share.open({ title: '', subject: '', excludedActivityTypes: '', - showAppsToview: true, + showAppsToView: true, }); -// $ExpectType Promise +// $ExpectType Promise Share.shareSingle({ url: '', message: '', social: 'facebook', }); -// $ExpectType Promise +// $ExpectType Promise Share.shareSingle({ url: '', type: '', diff --git a/types/react-native-snap-carousel/tsconfig.json b/types/react-native-snap-carousel/tsconfig.json index 4cba7b2f97..5fb352c2ca 100644 --- a/types/react-native-snap-carousel/tsconfig.json +++ b/types/react-native-snap-carousel/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-sortable-list/tsconfig.json b/types/react-native-sortable-list/tsconfig.json index 52474bc36f..a431d58043 100644 --- a/types/react-native-sortable-list/tsconfig.json +++ b/types/react-native-sortable-list/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-status-bar-height/index.d.ts b/types/react-native-status-bar-height/index.d.ts new file mode 100644 index 0000000000..6b24c8a9a2 --- /dev/null +++ b/types/react-native-status-bar-height/index.d.ts @@ -0,0 +1,6 @@ +// Type definitions for react-native-status-bar-height 2.1 +// Project: https://github.com/ovr/react-native-status-bar-height#readme +// Definitions by: Tom Spencer +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function getStatusBarHeight(skipAndroid?: boolean): number; diff --git a/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts b/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts new file mode 100644 index 0000000000..a31cb57259 --- /dev/null +++ b/types/react-native-status-bar-height/react-native-status-bar-height-tests.ts @@ -0,0 +1,5 @@ +import { getStatusBarHeight } from 'react-native-status-bar-height'; + +getStatusBarHeight(); // $ExpectType number +getStatusBarHeight(false); // $ExpectType number +getStatusBarHeight(true); // $ExpectType number diff --git a/types/react-native-status-bar-height/tsconfig.json b/types/react-native-status-bar-height/tsconfig.json new file mode 100644 index 0000000000..13c7ab69f5 --- /dev/null +++ b/types/react-native-status-bar-height/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", + "react-native-status-bar-height-tests.ts" + ] +} diff --git a/types/react-native-status-bar-height/tslint.json b/types/react-native-status-bar-height/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-status-bar-height/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-svg-charts/tsconfig.json b/types/react-native-svg-charts/tsconfig.json index ea66ecf6b7..73c13515f8 100644 --- a/types/react-native-svg-charts/tsconfig.json +++ b/types/react-native-svg-charts/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-svg-charts/tslint.json b/types/react-native-svg-charts/tslint.json index c040aa7670..ca872cae09 100644 --- a/types/react-native-svg-charts/tslint.json +++ b/types/react-native-svg-charts/tslint.json @@ -1,6 +1,6 @@ { - "extends": "dtslint/dt.json", - "rules": { - "strict-export-declare-modifiers": false - } + "extends": "dtslint/dt.json", + "rules": { + "strict-export-declare-modifiers": false + } } diff --git a/types/react-native-swiper/tsconfig.json b/types/react-native-swiper/tsconfig.json index 68d1350773..3f5a191dc8 100644 --- a/types/react-native-swiper/tsconfig.json +++ b/types/react-native-swiper/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-tab-navigator/tsconfig.json b/types/react-native-tab-navigator/tsconfig.json index b8e913c472..eacb5b77da 100644 --- a/types/react-native-tab-navigator/tsconfig.json +++ b/types/react-native-tab-navigator/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-text-input-mask/tsconfig.json b/types/react-native-text-input-mask/tsconfig.json index c9b3f10fc3..812d310366 100644 --- a/types/react-native-text-input-mask/tsconfig.json +++ b/types/react-native-text-input-mask/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-toast-native/tsconfig.json b/types/react-native-toast-native/tsconfig.json index 656114c120..e4f36e018d 100644 --- a/types/react-native-toast-native/tsconfig.json +++ b/types/react-native-toast-native/tsconfig.json @@ -2,8 +2,7 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "es6", - "dom" + "es6" ], "noImplicitAny": true, "noImplicitThis": true, diff --git a/types/react-native-uuid-generator/index.d.ts b/types/react-native-uuid-generator/index.d.ts new file mode 100644 index 0000000000..ad5cb96bec --- /dev/null +++ b/types/react-native-uuid-generator/index.d.ts @@ -0,0 +1,11 @@ +// Type definitions for react-native-uuid-generator 4.0 +// Project: https://github.com/Traviskn/react-native-uuid-generator#readme +// Definitions by: burtek +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +declare namespace UUIDGenerator { + function getRandomUUID(): Promise; + function getRandomUUID(callback: (uuid: string) => void): void; +} + +export default UUIDGenerator; diff --git a/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts new file mode 100644 index 0000000000..b65f0ef410 --- /dev/null +++ b/types/react-native-uuid-generator/react-native-uuid-generator-tests.ts @@ -0,0 +1,5 @@ +import UUIDGenerator from 'react-native-uuid-generator'; + +UUIDGenerator.getRandomUUID().then((uuid: string) => { }).catch((error: any) => { }); + +UUIDGenerator.getRandomUUID((uuid: string) => { }); diff --git a/types/react-native-uuid-generator/tsconfig.json b/types/react-native-uuid-generator/tsconfig.json new file mode 100644 index 0000000000..30c1f52249 --- /dev/null +++ b/types/react-native-uuid-generator/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", + "react-native-uuid-generator-tests.ts" + ] +} diff --git a/types/react-native-uuid-generator/tslint.json b/types/react-native-uuid-generator/tslint.json new file mode 100644 index 0000000000..3db14f85ea --- /dev/null +++ b/types/react-native-uuid-generator/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } diff --git a/types/react-native-vector-icons/tsconfig.json b/types/react-native-vector-icons/tsconfig.json index 993aae3195..15b50d6d34 100644 --- a/types/react-native-vector-icons/tsconfig.json +++ b/types/react-native-vector-icons/tsconfig.json @@ -2,7 +2,6 @@ "compilerOptions": { "module": "commonjs", "lib": [ - "dom", "es6" ], "noImplicitAny": true, @@ -36,4 +35,4 @@ "Zocial.d.ts", "react-native-vector-icons-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/react-native-video/index.d.ts b/types/react-native-video/index.d.ts index e84bcc7637..63d0ff6c89 100644 --- a/types/react-native-video/index.d.ts +++ b/types/react-native-video/index.d.ts @@ -1,13 +1,11 @@ -// Type definitions for react-native-video 2.0 +// Type definitions for react-native-video 3.1 // Project: https://github.com/react-native-community/react-native-video // Definitions by: HuHuanming // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import * as React from 'react'; -import { - ViewProps -} from 'react-native'; +import { ViewProps } from 'react-native'; export interface OnLoadData { canPlayFastForward: boolean; @@ -32,73 +30,92 @@ export interface LoadError { }; } +export const TextTrackType: { + SRT: 'application/x-subrip'; + TTML: 'application/ttml+xml'; + VTT: 'text/vtt'; +}; + export interface VideoProperties extends ViewProps { - /* Native only */ - src?: any; - seek?: number; - fullscreen?: boolean; - onVideoLoadStart?(): void; - onVideoLoad?(): void; - onVideoBuffer?(): void; - onVideoError?(): void; - onVideoProgress?(): void; - onVideoSeek?(): void; - onVideoEnd?(): void; - onTimedMetadata?(): void; - onVideoFullscreenPlayerWillPresent?(): void; - onVideoFullscreenPlayerDidPresent?(): void; - onVideoFullscreenPlayerWillDismiss?(): void; - onVideoFullscreenPlayerDidDismiss?(): void; + /* Native only */ + src?: any; + seek?: number; + fullscreen?: boolean; + onVideoLoadStart?(): void; + onVideoLoad?(): void; + onVideoBuffer?(): void; + onVideoError?(): void; + onVideoProgress?(): void; + onVideoSeek?(): void; + onVideoEnd?(): void; + onTimedMetadata?(): void; + onVideoFullscreenPlayerWillPresent?(): void; + onVideoFullscreenPlayerDidPresent?(): void; + onVideoFullscreenPlayerWillDismiss?(): void; + onVideoFullscreenPlayerDidDismiss?(): void; - /* Wrapper component */ - // Opaque type returned by require('./video.mp4') - source: { uri?: string } | number; - resizeMode?: string; - poster?: string; - repeat?: boolean; - paused?: boolean; - muted?: boolean; - volume?: number; - rate?: number; - playInBackground?: boolean; - playWhenInactive?: boolean; - ignoreSilentSwitch?: 'ignore' | 'obey'; - disableFocus?: boolean; - controls?: boolean; - currentTime?: number; - progressUpdateInterval?: number; - useTextureView?: boolean; - onLoadStart?(): void; - onLoad?(data: OnLoadData): void; - onBuffer?(): void; - onError?(error: LoadError): void; - onProgress?(data: { - currentTime: number; - playableDuration: number; - }): void; - onSeek?(): void; - onEnd?(): void; - onFullscreenPlayerWillPresent?(): void; - onFullscreenPlayerDidPresent?(): void; - onFullscreenPlayerWillDismiss?(): void; - onFullscreenPlayerDidDismiss?(): void; - onReadyForDisplay?(): void; - onPlaybackStalled?(): void; - onPlaybackResume?(): void; - onPlaybackRateChange?(): void; - onAudioFocusChanged?(): void; - onAudioBecomingNoisy?(): void; + /* Wrapper component */ + // Opaque type returned by require('./video.mp4') + source: { uri?: string } | number; + resizeMode?: string; + poster?: string; + repeat?: boolean; + paused?: boolean; + muted?: boolean; + volume?: number; + rate?: number; + playInBackground?: boolean; + playWhenInactive?: boolean; + ignoreSilentSwitch?: 'ignore' | 'obey'; + disableFocus?: boolean; + controls?: boolean; + currentTime?: number; + progressUpdateInterval?: number; + useTextureView?: boolean; + allowsExternalPlayback?: boolean; - /* Required by react-native */ - scaleX?: number; - scaleY?: number; - translateX?: number; - translateY?: number; - rotation?: number; + onLoadStart?(): void; + onLoad?(data: OnLoadData): void; + onBuffer?(): void; + onError?(error: LoadError): void; + onProgress?(data: { + currentTime: number; + playableDuration: number; + seekableDuration: number; + }): void; + onSeek?(): void; + onEnd?(): void; + onFullscreenPlayerWillPresent?(): void; + onFullscreenPlayerDidPresent?(): void; + onFullscreenPlayerWillDismiss?(): void; + onFullscreenPlayerDidDismiss?(): void; + onReadyForDisplay?(): void; + onPlaybackStalled?(): void; + onPlaybackResume?(): void; + onPlaybackRateChange?(): void; + onAudioFocusChanged?(): void; + onAudioBecomingNoisy?(): void; + selectedTextTrack?: { + type: 'system' | 'disabled' | 'title' | 'language' | 'index'; + value?: string | number; + }; + textTracks?: Array<{ + title?: string; + language?: string; + type: 'application/x-subrip' | 'application/ttml+xml' | 'text/vtt'; + uri: string; + }>; + + /* Required by react-native */ + scaleX?: number; + scaleY?: number; + translateX?: number; + translateY?: number; + rotation?: number; } export default class Video extends React.Component { - seek(time: number): void; - presentFullscreenPlayer(): void; - dismissFullscreenPlayer(): void; + seek(time: number, tolerance?: number): void; + presentFullscreenPlayer(): void; + dismissFullscreenPlayer(): void; } diff --git a/types/react-native-video/react-native-video-tests.tsx b/types/react-native-video/react-native-video-tests.tsx index 0e7990a04e..2df7edfccd 100644 --- a/types/react-native-video/react-native-video-tests.tsx +++ b/types/react-native-video/react-native-video-tests.tsx @@ -1,66 +1,12 @@ import * as React from 'react'; -import { - StyleSheet, - Text, - View, - ViewStyle -} from 'react-native'; import Video from 'react-native-video'; -class VideoTest extends React.Component { - constructor(props: {}) { - super(props); - } - - render(): React.ReactElement { - return ( -