diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 54d80df8e5..81913375f9 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -276,7 +276,7 @@ /types/await-timeout/ @szhu /types/awesomplete/ @webbiesdk @bmdixon @tbekolay @chrislopresto /types/aws-iot-device-sdk/ @niik @mlamp -/types/aws-lambda/ @skarum @tobyhede @buggy @y13i @wwwy3y3 @OrthoDex @MichaelMarner @daniel-cottone @kostya-misura @coderbyheart @palmithor @daniloraisi @simonbuchan @Haydabase @repl-chris @aneilbaboo @jeznag @louislarry @dpapukchiev @ohookins @trevor-leach @jagregory @dalen @loikg @skyzenr @richardcornelissen +/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 @dalen @loikg @skyzenr @richardcornelissen @redlickigrzegorz /types/aws-param-store/ @jasonthomasgray /types/aws-serverless-express/ @threesquared @jcaffey @mattmeye @albertovasquez /types/aws4/ @ajcrites @@ -375,7 +375,7 @@ /types/bindings/ @unindented /types/bintrees/ @CjS77 /types/bip21/ @stefanhuber -/types/bip32/ @me +/types/bip32/ @eduhenke /types/bip38/ @micksatana /types/bip39/ @micksatana /types/bit-array/ @mudkipme @@ -440,11 +440,10 @@ /types/bootstrap3-dialog/ @nakupanda @cnboland /types/bounce.js/ @cherrry /types/box2d/ @jbaldwin -/types/boxen/ @BendingBender /types/bpmn-moddle/ @haydos89 /types/brace-expansion/ @BendingBender /types/braces/ @vemoo -/types/braft-editor/ @me +/types/braft-editor/ @petitspois /types/braintree-web/ @chlela /types/breeze/ @borisyankov /types/bricks.js/ @kondi @@ -459,7 +458,7 @@ /types/browser-resolve/ @marionebl /types/browser-sync/ @joeskeen @aznnomness /types/browserify/ @AndrewGaspar @jvilk @leonard-thieu @LinusU -/types/browserslist/ @davecardwell +/types/browserslist/ @davecardwell @AndrewLeedham /types/browserslist-useragent/ @nju33 /types/bs58/ @chrootsu @BendingBender /types/bs58/v3/ @chrootsu @@ -526,8 +525,9 @@ /types/carbon__themes/ @vpicone /types/carbon__type/ @vpicone /types/card-validator/ @ChanceM +/types/carlo/ @adierkens /types/case-sensitive-paths-webpack-plugin/ @r3nya -/types/caseless/ @downace @mastermatt +/types/caseless/ @downace @mastermatt @forivall /types/cash/ @akvlko /types/casperjs/ @jedmao @urielch /types/cassandra-driver/ @Svjard @pc-jedi @michal-b-kaminski @@ -539,6 +539,7 @@ /types/cavy/ @tyler-hoffman /types/cbor/ @pushplay /types/ccap/ @taoqf +/types/centra/ @twooster /types/cesium/ @Zuzon @hnipps @szechyjs @golyalpha /types/cfn-response/ @ivoisbelongtous /types/chai/ @jedmao @Bartvds @AGBrown @olivr70 @mwistrand @joshuakgoldberg @shaunluttin @Naktibalda @micksatana @ErikSchierboom @@ -551,10 +552,10 @@ /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 /types/chai-jquery/ @kazimanzurrashid /types/chai-json-schema/ @ulrichheiniger +/types/chai-moment/ @chrisgodsey /types/chai-oequal/ @mizunashi-mana /types/chai-roughly/ @swist /types/chai-spies/ @kuzn-ilya @harm-less @jounisuo @@ -607,7 +608,6 @@ /types/clean-css/v3/ @tkrotoff /types/clean-regexp/ @BendingBender /types/clean-stack/ @BendingBender -/types/clean-webpack-plugin/ @j-f1 /types/clear-require/ @dan-j /types/clearbladejs-client/ @ClearBlade /types/clearbladejs-node/ @ClearBlade @@ -634,6 +634,7 @@ /types/clmtrackr/ @hellochar /types/clndr/ @jasperjn /types/clockpicker/ @jfcere +/types/clone-deep/ @tanfonto /types/cloneable-readable/ @qlonik /types/cloner/ @matrumz /types/closure-compiler/ @mprobst @@ -704,7 +705,7 @@ /types/condense-whitespace/ @djcsdy /types/confidence/ @jppellerin /types/config/ @RWander @forrestbice @jndonald3 @albertovasquez -/types/config-yaml/ @me +/types/config-yaml/ @Arylo /types/configstore/ @ArcticLight /types/configurable/ @jewbre /types/confit/ @ethanresnick @@ -749,7 +750,6 @@ /types/cookies/ @WangZishi @jkeylu @BendingBender /types/copy/ @ffflorian /types/copy-paste/ @SrTobi -/types/copy-text-to-clipboard/ @BendingBender /types/copy-webpack-plugin/ @flying-sheep /types/copyfiles/ @ffflorian /types/cordova-ionic/ @hendrikmaus @@ -792,9 +792,7 @@ /types/country-select-js/ @humrochagf /types/countup.js/ @shermendev /types/coverup/ @bevalorous -/types/cp-file/ @BendingBender /types/cpx/ @alan-agius4 -/types/cpy/ @mhegazy @BendingBender /types/cqrs-domain/ @blissi /types/cradle/ @panuhorsmalahti /types/crc/ @YuJianrong @@ -831,6 +829,7 @@ /types/css/ @ilich /types/css-font-loading-module/ @slikts /types/css-modules/ @NeekSandhu +/types/css-modules-loader-core/ @skovy /types/css-to-style/ @bengry /types/css-tree/ @erik-kallen /types/cssbeautify/ @rictic @@ -946,7 +945,6 @@ /types/debounce-fn/ @BendingBender /types/debounce-promise/ @whtsky /types/debug/ @swook @galtalmor @zamb3zi @brasten @npenin -/types/decamelize/ @samverschueren /types/decay/ @enaeseth /types/decode-entities/ @waspothegreat /types/decode-uri-component/ @BendingBender @@ -1014,6 +1012,7 @@ /types/diffie-hellman/ @BendingBender /types/digibyte/ @lautarodragan @werewolfe /types/dinero.js/ @BendingBender +/types/dingtalk-robot-sender/ @bangbang93 /types/dir-glob/ @BendingBender /types/dir-resolve/ @andy-ms /types/dirname-regex/ @BendingBender @@ -1043,9 +1042,12 @@ /types/dom-mediacapture-record/ @eliasmeire /types/dom-to-image/ @JipSterk /types/dom4/ @adidahiya @giladgray +/types/domelementtype/ @johandavidson +/types/domhandler/ @johandavidson /types/domo/ @Steve-Fenton /types/dompurify/ @bazuzi @FlowCrypt /types/domready/ @dotnetnerd +/types/domutils/ @johandavidson /types/donna/ @vvakame /types/dookie/ @swanest /types/dot/ @ZombieHunter @@ -1106,8 +1108,9 @@ /types/easy-table/ @nikeee /types/easy-xapi/ @DeadAlready /types/easy-xapi-utils/ @DeadAlready +/types/easydate/ @satyarohith /types/ebongarde-root/ @Ebongarde -/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia @iRON5 @bilalucar +/types/echarts/ @xieisabug @AntiMoron @liveangela @Ovilia @iRON5 @bilalucar @tmtron @dwhitney /types/ecma-proposal-math-extensions/ @ksm2 /types/ecurve/ @mhegazy /types/ed25519/ @erikma @@ -1280,9 +1283,9 @@ /types/expired/ @BendingBender /types/expired-storage/ @intolerance /types/expirymanager/ @DanielRose -/types/expo/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel @burtek @jkillian @satya164 @vinitsood -/types/expo/v31/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel @burtek @jkillian @satya164 -/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 @burtek @jkillian @satya164 @vinitsood @mattiassamskar @jaulz +/types/expo/v31/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @levansuper @ihmpavel @burtek @jkillian @satya164 @mattiassamskar +/types/expo/v30/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo @mattiassamskar /types/expo/v27/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @moshfeu @prokopcm @tinaroh @binki @mo /types/expo/v26/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @tinaroh /types/expo/v25/ @KonstantinKai @martynaskadisa @janaagaard75 @ssanchezmarc @fhelwanger @umidbekkarimov @@ -1367,6 +1370,7 @@ /types/factory-girl/ @stackbuilders @sestrella @elcuy /types/faker/ @bensw @basp @Kuniwak @mattbishop /types/faker/v3/ @Kuniwak +/types/falafel/ @delprzemo /types/falcor/ @Quramy /types/falcor-express/ @Quramy /types/falcor-http-datasource/ @Quramy @@ -1425,7 +1429,6 @@ /types/figures/ @BendingBender /types/file-exists/ @BendingBender /types/file-saver/ @cyrilschumacher @DaIgeb @chrismbarr -/types/file-type/ @tcaesvk @BendingBender /types/file-url/ @coderslagoon /types/filenamify/ @rokt33r /types/filenamify-url/ @cprecioso @@ -1720,6 +1723,7 @@ /types/get-node-dimensions/ @vincekovacs /types/get-port/ @plantain-00 @BendingBender /types/get-range/ @BendingBender +/types/get-res/ @satyarohith /types/get-stdin/ @DanielRosenwasser /types/get-stream/ @douglasduteil @BendingBender /types/get-urls/ @BendingBender @@ -1837,7 +1841,8 @@ /types/grasp/ @agnoster /types/gravatar/ @denis-sokolov /types/gravatar-url/ @ivangabriele -/types/greasemonkey/ @kotas +/types/greasemonkey/ @kotas @nikolay-borzov +/types/greasemonkey/v3/ @kotas /types/grecaptcha/ @DethAriel @rafaeltavares /types/grecaptcha/v0/ @brentj73 /types/gregorian-calendar/ @cwalv @@ -1989,7 +1994,7 @@ /types/hexo-fs/ @segayuu /types/hexo-log/ @segayuu /types/hexo-util/ @segayuu -/types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens +/types/highcharts/ @damianog @baltie @AlbertOzimek @hanssens @jgresham /types/highcharts-ng/ @scatcher /types/highland/ @Bartvds @hgwood @iwllyu @alvis @notbobthebuilder /types/highlight.js/ @nikeee @sourrust @joshuakgoldberg @@ -2048,7 +2053,6 @@ /types/humane/ @jmvrbanac /types/humanize-ms/ @adamzerella /types/humanize-plus/ @DenisCarriere -/types/humanize-string/ @ragnarok56 /types/humanize-url/ @BendingBender /types/humanparser/ @MichalPodeszwa /types/humps/ @nikeee @@ -2086,7 +2090,6 @@ /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 @@ -2120,6 +2123,7 @@ /types/ink/ @cprecioso /types/ink-spinner/ @lukostry /types/ink-table/ @lukostry +/types/ink-testing-library/ @MancunianSam /types/ink-text-input/ @lukostry /types/inline-css/ @philipisapain /types/inline-style-prefixer/ @ahz @dpetrezselyova @franklixuefei @@ -2214,7 +2218,6 @@ /types/is-running/ @danwbyrne /types/is-scoped/ @postcrafter /types/is-stream/ @me -/types/is-svg/ @BendingBender /types/is-text-path/ @mhegazy /types/is-touch-device/ @screendriver /types/is-trademarked/ @BendingBender @@ -2238,7 +2241,7 @@ /types/issue-parser/ @Leko /types/issue-regex/ @BendingBender /types/istanbul/ @tkrotoff -/types/istanbul-lib-coverage/ @jason0x43 +/types/istanbul-lib-coverage/ @jason0x43 @loryman /types/istanbul-lib-hook/ @jason0x43 /types/istanbul-lib-instrument/ @jason0x43 /types/istanbul-lib-report/ @jason0x43 @@ -2521,8 +2524,8 @@ /types/jsrender/ @zakki /types/jsreport-core/ @taoqf /types/jsreport-html-embedded-in-docx/ @taoqf -/types/jsreport-html-to-xlsx/ @me -/types/jsreport-html-to-xlsx/v1/ @me +/types/jsreport-html-to-xlsx/ @taoqf +/types/jsreport-html-to-xlsx/v1/ @taoqf /types/jsreport-jsrender/ @taoqf /types/jsreport-phantom-pdf/ @taoqf /types/jsreport-xlsx/ @taoqf @@ -2766,7 +2769,7 @@ /types/lingui__macro/ @huan086 /types/lingui__react/ @huan086 /types/linkify-issues/ @BendingBender -/types/linkify-it/ @praxxis +/types/linkify-it/ @praxxis @alexplumb /types/linkify-urls/ @BendingBender /types/linkifyjs/ @szhu @ovidiubute /types/list-git-remotes/ @BendingBender @@ -3295,6 +3298,7 @@ /types/mixto/ @vvakame /types/mjml/ @aahoughton @marpstar /types/mjml-react/ @henrinormak +/types/mkcert/ @asachin96 /types/mkdirp/ @Bartvds @mrmlnc /types/mkdirp-promise/ @pluma /types/mkpath/ @optical @@ -3333,13 +3337,13 @@ /types/moment-strftime2/ @dex4er /types/moment-timezone/ @michelsalib @alanblins @asermax @borys-kupar /types/money-math/ @taoqf -/types/mongo-sanitize/ @CedricCazin +/types/mongo-sanitize/ @CedricCazin @penumbra1 /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 @Manc /types/mongodb/v2/ @CaselIT @alanmarcell @bitjson @dante-101 @mcortesi /types/mongodb-memory-server/ @dmitryrogozhny /types/mongodb-uri/ @mernxl -/types/mongoose/ @horiuchi @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio @emmanuelgautier @frontendmonster @mingchen @penumbra1 -/types/mongoose/v4/ @simonxca @horiuchi @lukasz-zak +/types/mongoose/ @horiuchi @lukasz-zak @Alorel @jendrikw @ethanresnick @vologab @jussikinnula @ondratra @alfirin @idandrd @various89 @Fazendaaa @NormanPerrin @danmana @stablio @emmanuelgautier @frontendmonster @mingchen @penumbra1 @orblazer +/types/mongoose/v4/ @simonxca @horiuchi @lukasz-zak @murbanowicz /types/mongoose-auto-increment/ @AyaMorisawa /types/mongoose-deep-populate/ @AyaMorisawa /types/mongoose-geojson-schema/ @bondz @@ -3377,7 +3381,7 @@ /types/msportalfx-test/ @julioct /types/mssql/ @jaminfarr @buzinas @mrrichar @elhaard @pkeuter @mcdado /types/mu2/ @jedigo -/types/mui-datatables/ @favna +/types/mui-datatables/ @favna @ankithkonda /types/muicss/ @samuelneff /types/multer/ @jt000 @DavidBR-SW @mxl @hyunseob /types/multer-gridfs-storage/ @devconcept @@ -3529,7 +3533,7 @@ /types/node-localstorage/ @intolerance /types/node-memwatch/ @Kroisse /types/node-mysql-wrapper/ @kataras -/types/node-notifier/ @tkQubo +/types/node-notifier/ @tkQubo @loryman /types/node-polyglot/ @timjk @liamross /types/node-powershell/ @rodrigoff /types/node-pushnotifications/ @menushka @@ -3591,12 +3595,10 @@ /types/npm-keyword/ @BendingBender /types/npm-license-crawler/ @ffflorian /types/npm-list-author-packages/ @ffflorian -/types/npm-name/ @BendingBender /types/npm-package-arg/ @mgroenhoff @OiYouYeahYou /types/npm-packlist/ @ajafff /types/npm-paths/ @BendingBender /types/npm-registry-package-info/ @ffflorian -/types/npm-run-path/ @BendingBender /types/npm-user/ @BendingBender /types/npm-user-packages/ @BendingBender /types/npmlog/ @DanielMSchmidt @littlepiggy03 @@ -3680,7 +3682,7 @@ /types/openlayers/ @osechet @wb14123 @ailrun @mylen @iamthechad @danmana @yairtawil @pierremarc @hauke96 @gberaudo /types/openlayers/v3/ @osechet @matthiasdailey-ccri /types/openlayers/v2/ @bolhovsky -/types/openpgp/ @errietta @damonpam @po5i @ecamellini +/types/openpgp/ @errietta @damonpam @po5i @ecamellini @SardineFish /types/openstack-wrapper/ @sanjaymadane /types/opentok/ @westy92 @CatGuardian /types/opentype.js/ @danmarshall @edzis @@ -3735,7 +3737,6 @@ /types/p-retry/ @BendingBender /types/p-series/ @BendingBender /types/p-settle/ @natesilva -/types/p-some/ @BendingBender /types/p-tap/ @BendingBender /types/p-time/ @BendingBender /types/p-timeout/ @BendingBender @@ -3833,7 +3834,6 @@ /types/path-exists/v1/ @shiwano /types/path-is-absolute/ @mhegazy /types/path-is-inside/ @aomarks -/types/path-key/ @BendingBender /types/path-regex/ @BendingBender /types/path-type/ @BendingBender /types/pathfinding/ @BNedry @@ -3859,7 +3859,7 @@ /types/pendo-io-browser/ @aaronbeall /types/permit/ @jannikkeye /types/persona/ @Nycto -/types/pet-finder-api/ @me +/types/pet-finder-api/ @ncipollina /types/petit-dom/ @JamesMessinger /types/pg/ @pspeter3 /types/pg/v6/ @pspeter3 @@ -3875,6 +3875,7 @@ /types/phantom/ @horiuchi @llRandom /types/phantomcss/ @abauzac /types/phantomjs/ @jedhunsaker @keesey +/types/phin/ @twooster /types/phoenix/ @mciastek @John-Goff @princemaple /types/phone/ @DxCx /types/phone-formatter/ @westy92 @@ -3978,6 +3979,7 @@ /types/power-assert/ @vvakame /types/power-assert-formatter/ @vvakame /types/powerbi-visuals-tools/ @zBritva @Microsoft +/types/preact-i18n/ @ltetzlaff /types/precise/ @codeanimal /types/precond/ @olsio /types/preloadjs/ @endel @@ -4047,6 +4049,8 @@ /types/prosemirror-test-builder/ @ifiokjr /types/prosemirror-transform/ @bradleyayers @davidka @timjb @patsimm /types/prosemirror-view/ @bradleyayers @davidka @timjb @patsimm +/types/protoc-plugin/ @jonnyreeves +/types/protocol-buffers-schema/ @claasahl /types/proton-native/ @khanhas @ltetzlaff /types/protractor-browser-logs/ @rokadias /types/protractor-helpers/ @johncant @@ -4056,7 +4060,6 @@ /types/proxy-lists/ @BehindTheMath /types/proxy-verifier/ @BehindTheMath /types/proxyquire/ @jt000 -/types/ps-list/ @BendingBender /types/ps-tree/ @alessiopcc /types/pseudo-audio-param/ @kirbysayshi /types/psl/ @BendingBender @@ -4071,7 +4074,7 @@ /types/pumpify/ @JustinBeckwith @aoberoi /types/punycode/ @yavanosta /types/pupa/ @nju33 -/types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick +/types/puppeteer/ @marvinhagemeister @cdeutsch @ksm2 @SimonSchick @SerbanGhita /types/puppeteer/v0/ @marvinhagemeister @cdeutsch /types/puppeteer-core/ @mtsmfm /types/pure-render-decorator/ @seansfkelley @@ -4095,8 +4098,6 @@ /types/qs-middleware/ @davecardwell /types/qtip2/ @Seltzer @leonard-thieu /types/querystringify/ @ilich -/types/quick-lru/ @BendingBender -/types/quick-lru/v1/ @BendingBender /types/quill/ @sumitkm @guillaume-ro-fr @43081j @AnielloFalcone @mhamri /types/quixote/ @greybax /types/qunit/ @waratuman @mike-north @@ -4160,7 +4161,7 @@ /types/rdflib/ @cenotelie /types/re-base/ @jordandrako /types/reach__router/ @kingdaro -/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Jessidhia @pshrmn @threepointone @saranshkataria +/types/react/ @johnnyreilly @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz @theruther4d @guilhermehubner @ferdaber @jrakotoharisoa @pascaloliv @hotell @franklixuefei @Jessidhia @pshrmn @saranshkataria /types/react/v15/ @bbenezech @pzavolinsky @digiguru @ericanderson @tkrotoff @DovydasNavickas @onigoetz /types/react-adal/ @dkorolev1 /types/react-albus/ @sseppola @conradreuter @kuirak @@ -4175,10 +4176,10 @@ /types/react-autocomplete/ @lstanden /types/react-autosuggest/ @nicolas-schmitt @pjo256 @robessog @tbayne @cdeutsch @rosskevin /types/react-avatar-editor/ @diogocorrea @gabsprates @lsenta @davidspiess -/types/react-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen @enricoboccadifuoco @lonyele +/types/react-beautiful-dnd/ @varHarrie @bradleyayers @paustint @marknelissen @enricoboccadifuoco @lonyele @lukyth /types/react-better-password/ @mhuynh1 -/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly @janb87 @ldthorne -/types/react-blessed/ @me +/types/react-big-calendar/ @piotrwitek @paustint @pikpok @eps1lon @strongpauly @janb87 @ldthorne @siavelis +/types/react-blessed/ @guoshencheng /types/react-body-classname/ @mhegazy /types/react-bootstrap/ @walkerburgin @vsiao @danilojrr @Batbold-Gansukh @octatone @chengsieuly @mretolaza @katbusch @vitosamson @LKay @aaronbeall @jrakotoharisoa @r3nya @t49tran @bes /types/react-bootstrap-date-picker/ @LKay @ssi-hu-antal-bodnar @@ -4201,7 +4202,7 @@ /types/react-coinhive/ @sktbcbbs /types/react-collapse/ @Kimahriman /types/react-collapsible/ @knegusen -/types/react-color/ @LKay @markspolakovs @mntdn @nkgrnkgr +/types/react-color/ @LKay @markspolakovs @mntdn @nkgrnkgr @0815Strohhut /types/react-confirm/ @santiagodoldan @marknelissen /types/react-content-loader/ @alaatm @samwalshnz /types/react-copy-to-clipboard/ @mabels @BernabeFelix @@ -4221,7 +4222,7 @@ /types/react-data-grid/v1/ @SupernaviX /types/react-datagrid/ @stephenjelfs /types/react-date-range/ @Junbong -/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley @justingrant @jakeboone02 +/types/react-datepicker/ @radziksh @andrewBalekha @smrq @Rogach @royxue @KoalaHuman @seansfkelley @justingrant @jakeboone02 @Ky6uk @aviklai /types/react-daterange-picker/ @uncovertruth @MartynasZilinskas @donaldtf @vladflorescu94 /types/react-dates/ @ArturAmpilogov @NathanNZ /types/react-daum-postcode/ @Sa-ryong @@ -4265,7 +4266,8 @@ /types/react-google-login-component/ @koss-lebedev /types/react-google-maps-loader/ @vasilysn /types/react-google-places-suggest/ @vasilysn -/types/react-google-recaptcha/ @KoalaHuman @tomsturge +/types/react-google-recaptcha/ @KoalaHuman @tomsturge @MaxwellBo +/types/react-google-recaptcha/v0/ @KoalaHuman @tomsturge /types/react-gravatar/ @invliD /types/react-grid-layout/ @abirkholz @alitaheri @ZheyangSong @andrewhathaway @manav-m /types/react-hamburger-menu/ @grzesie2k @@ -4313,7 +4315,7 @@ /types/react-json/ @spielc /types/react-json-pretty/ @LKay /types/react-json-tree/ @gnestor @zainafzal08 -/types/react-jsonschema-form/ @iamdanfox @iplus26 @phbou72 @LucianBuzzo @sthenault @sbusch +/types/react-jsonschema-form/ @iamdanfox @iplus26 @phbou72 @LucianBuzzo @sthenault @sbusch @medfreeman /types/react-jss/ @eps1lon @jlaw90 /types/react-kawaii/ @ZhangYiJiang /types/react-lazyload/ @m0a @@ -4334,6 +4336,7 @@ /types/react-mce/ @morphologue /types/react-mdl/ @bradzacher /types/react-measure/ @asvetliakov @marcfallows +/types/react-medium-image-zoom/ @james-ff /types/react-mentions/ @activescott @efedorenko /types/react-mixin/ @tkqubo /types/react-modal/ @radziksh @drewnoakes @homburg @ttamminen @hallowatcher @peterblazejewicz @jpowell @@ -4341,7 +4344,7 @@ /types/react-motion-loop/ @j-em /types/react-motion-slider/ @asvetliakov /types/react-motion-ui-pack/ @jsonunger -/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel @souvik-ghosh @nossbigg +/types/react-native/ @alloy @huhuanming @iRoachie @skn0tt @timwangdev @kamal @nelyousfi @alexdunne @swissmanu @bm-software @tkrotoff @a-tarasyuk @mvdam @esemesek @mrnickel @souvik-ghosh @nossbigg @saranshkataria /types/react-native-android-taskdescription/ @christianchown /types/react-native-auth0/ @ascariandrea @marknelissen /types/react-native-autocomplete-input/ @ifiokjr @@ -4432,7 +4435,7 @@ /types/react-notification-system-redux/ @LKay /types/react-notify-toast/ @klaascuvelier /types/react-numeric-input/ @heatherbooker @akx -/types/react-onclickoutside/ @LKay @surgeboris +/types/react-onclickoutside/ @LKay @surgeboris @NilSet /types/react-onclickoutside/v5/ @LKay /types/react-onsenui/ @salim7 @jemmyw @lirbank /types/react-outside-click-handler/ @zubivan @@ -4572,7 +4575,6 @@ /types/reactstrap/ @alihammad @mfal @danilobjr @FaithForHumans @timc13 @patrickrgaffney @prabodht @georg94 /types/reactstrap/v4/ @alihammad @mfal @danilobjr @fabiopaiva /types/read/ @timjk -/types/read-chunk/ @crispybee /types/read-package-tree/ @mgroenhoff /types/read-pkg/ @jdxcode /types/read-pkg-up/ @dudeofawesome @jdxcode @@ -4597,7 +4599,7 @@ /types/recursive-readdir/ @elisee @MicahZoltu /types/recursive-readdir/v1/ @elisee /types/redent/ @BendingBender -/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete @blablapolicja @ferrantejake +/types/redis/ @soywiz @CodeAnimal @MugeSo @UppaJung @Rokt33r @43081j @barnski @1pete @blablapolicja @ferrantejake @OpesanyaAdebayo /types/redis-errors/ @43081j /types/redis-mock/ @BendingBender /types/redis-rate-limiter/ @westy92 @nodify-at @@ -4700,6 +4702,7 @@ /types/requirejs-domready/ @lefb766 /types/requires-port/ @BendingBender /types/resemblejs/ @pimterry +/types/reserved-words/ @skovy /types/reservoir/ @danvk /types/resize-img/ @higuri /types/resize-observer-browser/ @chivesrs @@ -4755,6 +4758,7 @@ /types/rn-fetch-blob/ @pengcao1 /types/roads/ @dancespiele /types/roads-server/ @dancespiele +/types/roarr/ @psaxton /types/rocksdb/ @MeirionHughes @danwbyrne /types/roll/ @icopp /types/rolling-rate-limiter/ @l-jonas @@ -4774,6 +4778,7 @@ /types/round-to/ @seangenabe /types/route-parser/ @ianks @bobbuehler /types/routie/ @Adilson +/types/rox-react-native/ @ahanriat /types/royalslider/ @csrakowski @sKopheK /types/rpio/ @DominikPalo @Pencl /types/rrc/ @DeividasBakanas @@ -5004,12 +5009,11 @@ /types/sindresorhus__df/ @whatknight /types/sindresorhus__djb2a/ @BendingBender /types/sindresorhus__fnv1a/ @BendingBender -/types/sindresorhus__slugify/ @cprecioso /types/sindresorhus__string-hash/ @BendingBender /types/sindresorhus__to-milliseconds/ @BendingBender /types/single-line-log/ @ffflorian /types/single-spa-react/ @Garrett-Smith-iq @chrisdopuch -/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse @alecf @SimonSchick +/types/sinon/ @mrbigdog2u @rationull @lumaxis @nicojs @43081j @joshuakgoldberg @gjednaszewski @johnjesse @alecf @SimonSchick @bergundy /types/sinon-as-promised/ @igrayson /types/sinon-chai/ @kazimanzurrashid @jedmao @elpdpt /types/sinon-chai/v2/ @kazimanzurrashid @jedmao @@ -5181,7 +5185,7 @@ /types/storybook__channels/ @bmatcuk /types/storybook__react/ @joscha @wapgear @dandean /types/storybook__react-native/ @joscha @wapgear @alechill @iRoachie @ceyhuno -/types/storybook__vue/ @pntgupta +/types/storybook__vue/ @pntgupta @jurgisrudaks /types/strange/ @wanganjun /types/stream-array/ @Tyler-Murphy /types/stream-buffers/ @Jason3S @@ -5220,7 +5224,7 @@ /types/strip-color/ @BendingBender /types/strip-indent/ @BendingBender /types/strip-json-comments/ @dmoonfire -/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr @SimonSchick @yultyyev @cpsoinos @saranshkataria @0xJoKe +/types/stripe/ @wjohnsto @codeanimal @sampsonjoliver @LinusU @brannon @kkamperschroer @starhoshi @bruun @galtalmor @htunnicliff @squirly @tzarger @ifiokjr @SimonSchick @yultyyev @cpsoinos @adamduren @saranshkataria @0xJoKe @delianides /types/stripe-checkout/ @cgwrench /types/stripe-v2/ @ejsmith @amritk @adamcmiel @jleider @galuszkak /types/stripe-v3/ @ejsmith @amritk @adamcmiel @jleider @galuszkak @slangeder @@ -5317,6 +5321,7 @@ /types/tabulator/ @euginio /types/tabulator-tables/ @jojoshua /types/tail/ @spacejack +/types/tampermonkey/ @silverwzw @nikolay-borzov /types/tapable/ @e-cloud @johnnyreilly /types/tapable/v0/ @e-cloud /types/tape/ @Bartvds @sodatea @DennisSchwartz @mikehenrty @rostrowski @@ -5379,7 +5384,6 @@ /types/tildify/ @BendingBender /types/tile-reduce/ @DenisCarriere /types/tilebelt/ @DenisCarriere -/types/time-span/ @BendingBender @mdvorscak /types/timelinejs/ @rolandzwaga /types/timelinejs3/ @MikeMatusz /types/timer-machine/ @dolanmiu @@ -5432,7 +5436,6 @@ /types/transducers-js/ @colinkahn @dphilipson @NaridaL /types/transducers.js/ @dphilipson /types/transliteration/ @tony19 -/types/trash/ @matthew-matvei @hoishin @BendingBender /types/traverse/ @newclear /types/traverson/ @marcinporebski /types/travis-fold/ @andy-ms @@ -5446,6 +5449,7 @@ /types/trim-newlines/ @djcsdy /types/triple-beam/ @danwbyrne /types/triplesec/ @threesquared +/types/trouter/ @stahlstift /types/trunk8/ @niemyjski /types/trusted-types/ @vrana /types/tryer/ @bengry @@ -5453,6 +5457,7 @@ /types/tspromise/ @soywiz /types/ttf2woff2/ @ThomasdenH /types/tunnel/ @BendingBender +/types/turbolinks/ @evankim390 /types/turndown/ @sergey-zhidkov /types/tus-js-client/ @kevhiggins @Acconut /types/tv4/ @Bartvds @psnider @@ -5598,10 +5603,11 @@ /types/vfile/ @bizen241 @rokt33r /types/vfile-location/ @ikatyang @rokt33r /types/vfile-message/ @rokt33r -/types/victory/ @asvetliakov @snerks @Havret @allreadyExisted @jlismore +/types/victory/ @asvetliakov @snerks @Havret @allreadyExisted @jlismore @stackbuilders @ibarrae /types/video.js/ @vbortone @scleriot @SWBennett06 @IgelCampus @giofreitas @gjanblaszczyk @sroucheray @AkxeOne @meikidd /types/viewability-helper/ @lironzluf /types/viewerjs/ @lrh3321 +/types/viewport-list/ @satyarohith /types/viewport-mercator-project/ @fnberta /types/viewporter/ @borisyankov /types/vimeo/ @DazWilkin @@ -5629,8 +5635,9 @@ /types/vortex-web-client/ @Pro /types/voucher-code-generator/ @JWebCoder /types/voximplant-websdk/ @aylarov +/types/vscode/ @Microsoft /types/vue-chartkick/ @cnsmedia -/types/vue-color/ @me +/types/vue-color/ @mildful /types/vue-markdown/ @neodon /types/vue-resource/ @kaorun343 /types/vue-scrollto/ @vincekovacs @@ -5843,7 +5850,6 @@ /types/yui/ @giabao /types/yup/ @dhardtke @vtserman @MoretonBayRC @sseppola @YashdalfTheGray @vincentjames501 @robertbullen @sat0yu @dancrumb /types/z-schema/ @pgonzal -/types/zapier-platform-core/ @bradleyayers /types/zeit__next-typescript/ @icopp /types/zen-observable/ @aicest @JounQin @itomtom /types/zen-push/ @daprahamian diff --git a/README.md b/README.md index 746d9d9f3e..b50272dbf4 100644 --- a/README.md +++ b/README.md @@ -57,7 +57,7 @@ You may need to add manual [references](http://www.typescriptlang.org/docs/handb ## How can I contribute? -DefinitelyTyped only works because of contributions by users like you! +Definitely Typed only works because of contributions by users like you! ### Test @@ -89,7 +89,7 @@ then follow the instructions to [edit an existing package](#edit-an-existing-pac ### Make a pull request -Once you've tested your package, you can share it on DefinitelyTyped. +Once you've tested your package, you can share it on Definitely Typed. First, [fork](https://guides.github.com/activities/forking/) this repository, install [node](https://nodejs.org/), and run `npm install`. @@ -117,7 +117,7 @@ If it doesn't, you can do so yourself in the comment associated with the PR. #### Create a new package -If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to DefinitelyTyped. +If you are the library author and your package is written in TypeScript, [bundle the autogenerated declaration files](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) in your package instead of publishing to Definitely Typed. If you are adding typings for an NPM package, create a directory with the same name. If the package you are adding typings for is not on NPM, make sure the name you choose for it does not conflict with the name of a package on NPM. @@ -137,7 +137,7 @@ See all options at [dts-gen](https://github.com/Microsoft/dts-gen). You may edit the `tsconfig.json` to add new files, to add `"target": "es6"` (needed for async functions), to add to `"lib"`, or to add the `"jsx"` compiler option. -DefinitelyTyped members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down. +Definitely Typed members routinely monitor for new PRs, though keep in mind that the number of other PRs may slow things down. For a good example package, see [base64-js](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/base64-js). @@ -165,18 +165,31 @@ For a good example package, see [base64-js](https://github.com/DefinitelyTyped/D #### Removing a package -When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from DefinitelyTyped to avoid confusion. +When a package [bundles](http://www.typescriptlang.org/docs/handbook/declaration-files/publishing.html) its own types, types should be removed from Definitely Typed to avoid confusion. You can remove it by running `npm run not-needed -- typingsPackageName asOfVersion sourceRepoURL [libraryName]`. - `typingsPackageName`: This is the name of the directory to delete. - `asOfVersion`: A stub will be published to `@types/foo` with this version. Should be higher than any currently published version. - `sourceRepoURL`: This should point to the repository that contains the typings. -- `libraryName`: Descriptive name of the library, e.g. "Angular 2" instead of "angular2". (If ommitted, will be identical to "typingsPackageName".) +- `libraryName`: Name of npm package that replaces the Definitely Typed types. Usually this is identical to "typingsPackageName", in which case you can omit it. -Any other packages in DefinitelyTyped that referenced the deleted package should be updated to reference the bundled types. To do this, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`. +Any other packages in Definitely Typed that referenced the deleted package should be updated to reference the bundled types. +You can get this list by looking at the errors from `npm run test`. +To fix the errors, add a `package.json` with `"dependencies": { "foo": "x.y.z" }`. +For example: -If a package was never on DefinitelyTyped, it does not need to be added to `notNeededPackages.json`. +```json +{ + "private": true, + "dependencies": { + "foo": "^2.6.0" + } +} +``` +When you add a `package.json` to dependents of `foo`, you will also need to open a PR to add `foo` [to dependenciesWhitelist.txt in types-publisher](https://github.com/Microsoft/types-publisher/blob/master/dependenciesWhitelist.txt). + +If a package was never on Definitely Typed, it does not need to be added to `notNeededPackages.json`. #### Lint @@ -225,11 +238,11 @@ The `master` branch is automatically published to the `@types` scope on NPM than #### I've submitted a pull request. How long until it is merged? -It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or DefinitelyTyped team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs. +It depends, but most pull requests will be merged within a week. PRs that have been approved by an author listed in the definition's header are usually merged more quickly; PRs for new definitions will take more time as they require more review from maintainers. Each PR is reviewed by a TypeScript or Definitely Typed team member before being merged, so please be patient as human factors may cause delays. Check the [PR Burndown Board](https://github.com/DefinitelyTyped/DefinitelyTyped/projects/3?card_filter_query=is%3Aopen) to see progress as maintainers work through the open PRs. #### My PR is merged; when will the `@types` NPM package be updated? -NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the DefinitelyTyped Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate. +NPM packages should update within a few minutes. If it's been more than an hour, mention the PR number on [the Definitely Typed Gitter channel](https://gitter.im/DefinitelyTyped/DefinitelyTyped) and the current maintainer will get the correct team member to investigate. #### I'm writing a definition that depends on another definition. Should I use `` or an import? @@ -325,13 +338,13 @@ You can look [here](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/mast This may belong in [TSJS-Lib-Generator](https://github.com/Microsoft/TSJS-lib-generator#readme). See the guidelines there. If the standard is still a draft, it belongs here. Use a name beginning with `dom-` and include a link to the standard as the "Project" link in the header. -When it graduates draft mode, we may remove it from DefinitelyTyped and deprecate the associated `@types` package. +When it graduates draft mode, we may remove it from Definitely Typed and deprecate the associated `@types` package. -#### How do DefinitelyTyped package versions relate to versions of the corresponding library? +#### How do Definitely Typed package versions relate to versions of the corresponding library? _NOTE: The discussion in this section assumes familiarity with [Semantic versioning](https://semver.org/)_ -Each DefinitelyTyped package is versioned when published to NPM. +Each Definitely Typed package is versioned when published to NPM. The [types-publisher](https://github.com/Microsoft/types-publisher) (the tool that publishes `@types` packages to npm) will set the declaration package's version by using the `major.minor` version number listed in the first line of its `index.d.ts` file. For example, here are the first few lines of [Node's type declarations](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/1253faabf5e0d2c5470db6ea87795d7f96fef7e2/types/node/index.d.ts) for version `10.12.x` at the time of writing: @@ -339,24 +352,24 @@ For example, here are the first few lines of [Node's type declarations](https:// // Type definitions for Node.js 10.12 // Project: http://nodejs.org/ // Definitions by: Microsoft TypeScript -// DefinitelyTyped +// Definitely Typed // Alberto Schiabel ``` Because `10.12` is at the end the first line, the npm version of the `@types/node` package will also be `10.12.x`. Note that the first-line comment in the `index.d.ts` file should only contain the `major.minor` version (e.g. `10.12`) and should not contain a patch version (e.g. `10.12.4`). This is because only the major and minor release numbers are aligned between library packages and type declaration packages. -The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by DefinitelyTyped and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. +The patch release number of the type declaration package (e.g. `.0` in `10.12.0`) is initialized to zero by Definitely Typed and is incremented each time a new `@types/node` package is published to NPM for the same major/minor version of the corresponding library. Sometimes type declaration package versions and library package versions can get out of sync. Below are a few common reasons why, in order of how much they inconvenience users of a library. Only the last case is typically problematic. * As noted above, the patch version of the type declaration package is unrelated to the library patch version. - This allows DefinitelyTyped to safely update type declarations for the same major/minor version of a library. + This allows Definitely Typed to safely update type declarations for the same major/minor version of a library. * If updating a package for new functionality, don't forget to update the version number to line up with that version of the library. If users make sure versions correspond between JavaScript packages and their respective `@types` packages, then `npm update` should typically just work. -* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update DefinitelyTyped when new library features are released. +* It's common for type declaration package updates to lag behind library updates because it's often library users, not maintainers, who update Definitely Typed when new library features are released. So there may be a lag of days, weeks, or even months before a helpful community member sends a PR to update the type declaration package for a new library release. If you're impacted by this, you can be the change you want to see in the world and you can be that helpful community member! @@ -366,7 +379,7 @@ Only the last case is typically problematic. [Semantic versioning](https://semver.org/) requires that versions with breaking changes must increment the major version number. For example, a library that removes a publicly exported function after its `3.5.8` release must bump its version to `4.0.0` in its next release. -Furthermore, when the library's `4.0.0` release is out, its DefinitelyTyped type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API. +Furthermore, when the library's `4.0.0` release is out, its Definitely Typed type declaration package should also be updated to `4.0.0`, including any breaking changes to the library's API. Many libraries have a large installed base of developers (including maintainers of other packages using that library as a dependency) who won't move right away to a new version that has breaking changes, because it might be months until a maintainer has time to rewrite code to adapt to the new version. In the meantime, users of old library versions still may want to update type declarations for older versions. @@ -398,7 +411,7 @@ At the time of writing, the [history v2 `tsconfig.json`](https://github.com/Defi } ``` -If there are other packages in DefinitelyTyped that are incompatible with the new version, you will need to add path mappings to the old version. +If there are other packages in Definitely Typed that are incompatible with the new version, you will need to add path mappings to the old version. You will also need to do this recursively for packages depending on packages depending on the old version. For example, `react-router` depends on `history@2`, so [react-router `tsconfig.json`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/react-router/v2/tsconfig.json) has a path mapping to `"history": [ "history/v2" ]`. diff --git a/notNeededPackages.json b/notNeededPackages.json index 812d1f9f1b..4cda1eb572 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -18,6 +18,12 @@ "sourceRepoURL": "https://github.com/ceolter/ag-grid", "asOfVersion": "3.2.0" }, + { + "libraryName": "aggregate-error", + "typingsPackageName": "aggregate-error", + "sourceRepoURL": "https://github.com/sindresorhus/aggregate-error", + "asOfVersion": "2.2.0" + }, { "libraryName": "ajv", "typingsPackageName": "ajv", @@ -468,6 +474,12 @@ "sourceRepoURL": "https://github.com/MikeMcl/decimal.js", "asOfVersion": "7.4.0" }, + { + "libraryName": "decompress-response", + "typingsPackageName": "decompress-response", + "sourceRepoURL": "https://github.com/sindresorhus/decompress-response", + "asOfVersion": "4.1.0" + }, { "libraryName": "deepmerge", "typingsPackageName": "deepmerge", @@ -510,6 +522,12 @@ "sourceRepoURL": "https://github.com/joyent/docker-file-parser", "asOfVersion": "1.0.3" }, + { + "libraryName": "dom-loaded", + "typingsPackageName": "dom-loaded", + "sourceRepoURL": "https://github.com/sindresorhus/dom-loaded", + "asOfVersion": "1.1.0" + }, { "libraryName": "dot-case", "typingsPackageName": "dot-case", @@ -564,6 +582,12 @@ "sourceRepoURL": "https://github.com/loopline-systems/electron-builder", "asOfVersion": "2.8.0" }, + { + "libraryName": "element-ready", + "typingsPackageName": "element-ready", + "sourceRepoURL": "https://github.com/sindresorhus/element-ready", + "asOfVersion": "3.1.0" + }, { "libraryName": "email-addresses", "typingsPackageName": "email-addresses", @@ -684,6 +708,18 @@ "sourceRepoURL": "https://github.com/sindresorhus/file-type", "asOfVersion": "10.9.1" }, + { + "libraryName": "filenamify", + "typingsPackageName": "filenamify", + "sourceRepoURL": "https://github.com/sindresorhus/filenamify", + "asOfVersion": "3.0.0" + }, + { + "libraryName": "filenamify-url", + "typingsPackageName": "filenamify-url", + "sourceRepoURL": "https://github.com/sindresorhus/filenamify-url", + "asOfVersion": "2.0.0" + }, { "libraryName": "FineUploader", "typingsPackageName": "fine-uploader", @@ -696,6 +732,12 @@ "sourceRepoURL": "https://www.firebase.com/docs/javascript/firebase", "asOfVersion": "3.2.1" }, + { + "libraryName": "fkill", + "typingsPackageName": "fkill", + "sourceRepoURL": "https://github.com/sindresorhus/fkill", + "asOfVersion": "6.0.0" + }, { "libraryName": "flatpickr", "typingsPackageName": "flatpickr", @@ -744,6 +786,12 @@ "sourceRepoURL": "https://github.com/manuelbieh/Geolib", "asOfVersion": "2.0.23" }, + { + "libraryName": "get-stream", + "typingsPackageName": "get-stream", + "sourceRepoURL": "https://github.com/sindresorhus/get-stream", + "asOfVersion": "5.0.0" + }, { "libraryName": "github", "typingsPackageName": "github", @@ -810,6 +858,18 @@ "sourceRepoURL": "https://handsontable.com/", "asOfVersion": "0.35.0" }, + { + "libraryName": "has-yarn", + "typingsPackageName": "has-yarn", + "sourceRepoURL": "https://github.com/sindresorhus/has-yarn", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "hasha", + "typingsPackageName": "hasha", + "sourceRepoURL": "https://github.com/sindresorhus/hasha", + "asOfVersion": "4.0.0" + }, { "libraryName": "hibp", "typingsPackageName": "hibp", @@ -888,6 +948,12 @@ "sourceRepoURL": "https://github.com/sindresorhus/internal-ip", "asOfVersion": "4.1.0" }, + { + "libraryName": "into-stream", + "typingsPackageName": "into-stream", + "sourceRepoURL": "https://github.com/sindresorhus/into-stream", + "asOfVersion": "5.0.0" + }, { "libraryName": "inversify", "typingsPackageName": "inversify", @@ -948,6 +1014,12 @@ "sourceRepoURL": "https://github.com/jonschlinkert/is-plain-object", "asOfVersion": "2.0.4" }, + { + "libraryName": "is-scoped", + "typingsPackageName": "is-scoped", + "sourceRepoURL": "https://github.com/sindresorhus/is-scoped", + "asOfVersion": "2.0.0" + }, { "libraryName": "is-svg", "typingsPackageName": "is-svg", @@ -1056,6 +1128,12 @@ "sourceRepoURL": "https://github.com/elitechance/lambda-phi", "asOfVersion": "1.0.1" }, + { + "libraryName": "latest-version", + "typingsPackageName": "latest-version", + "sourceRepoURL": "https://github.com/sindresorhus/latest-version", + "asOfVersion": "5.0.0" + }, { "libraryName": "ldclient-js", "typingsPackageName": "ldclient-js", @@ -1068,6 +1146,12 @@ "sourceRepoURL": "https://github.com/stevemao/left-pad", "asOfVersion": "1.2.0" }, + { + "libraryName": "leven", + "typingsPackageName": "leven", + "sourceRepoURL": "https://github.com/sindresorhus/leven", + "asOfVersion": "3.0.0" + }, { "libraryName": "Linq.JS", "typingsPackageName": "linq", @@ -1158,6 +1242,12 @@ "sourceRepoURL": "https://github.com/runk/node-maxmind", "asOfVersion": "2.0.5" }, + { + "libraryName": "mem", + "typingsPackageName": "mem", + "sourceRepoURL": "https://github.com/sindresorhus/mem", + "asOfVersion": "4.2.0" + }, { "libraryName": "mendixmodelsdk", "typingsPackageName": "mendixmodelsdk", @@ -1260,6 +1350,18 @@ "sourceRepoURL": "https://github.com/paularmstrong/normalizr", "asOfVersion": "2.0.18" }, + { + "libraryName": "npm-email", + "typingsPackageName": "npm-email", + "sourceRepoURL": "https://github.com/sindresorhus/npm-email", + "asOfVersion": "3.1.0" + }, + { + "libraryName": "npm-keyword", + "typingsPackageName": "npm-keyword", + "sourceRepoURL": "https://github.com/sindresorhus/npm-keyword", + "asOfVersion": "6.0.0" + }, { "libraryName": "npm-name", "typingsPackageName": "npm-name", @@ -1272,6 +1374,12 @@ "sourceRepoURL": "https://github.com/sindresorhus/npm-run-path", "asOfVersion": "3.0.1" }, + { + "libraryName": "npm-user", + "typingsPackageName": "npm-user", + "sourceRepoURL": "https://github.com/sindresorhus/npm-user", + "asOfVersion": "4.0.0" + }, { "libraryName": "Nuka Carousel", "typingsPackageName": "nuka-carousel", @@ -1302,48 +1410,162 @@ "sourceRepoURL": "https://github.com/sindresorhus/ora", "asOfVersion": "3.2.0" }, + { + "libraryName": "p-any", + "typingsPackageName": "p-any", + "sourceRepoURL": "https://github.com/sindresorhus/p-any", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-cancelable", + "typingsPackageName": "p-cancelable", + "sourceRepoURL": "https://github.com/sindresorhus/p-cancelable", + "asOfVersion": "1.1.0" + }, + { + "libraryName": "p-catch-if", + "typingsPackageName": "p-catch-if", + "sourceRepoURL": "https://github.com/sindresorhus/p-catch-if", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-debounce", + "typingsPackageName": "p-debounce", + "sourceRepoURL": "https://github.com/sindresorhus/p-debounce", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-each-series", + "typingsPackageName": "p-each-series", + "sourceRepoURL": "https://github.com/sindresorhus/p-each-series", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-event", "typingsPackageName": "p-event", "sourceRepoURL": "https://github.com/sindresorhus/p-event", "asOfVersion": "3.0.0" }, + { + "libraryName": "p-every", + "typingsPackageName": "p-every", + "sourceRepoURL": "https://github.com/kevva/p-every", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-limit", "typingsPackageName": "p-limit", "sourceRepoURL": "https://github.com/sindresorhus/p-limit", "asOfVersion": "2.2.0" }, + { + "libraryName": "p-locate", + "typingsPackageName": "p-locate", + "sourceRepoURL": "https://github.com/sindresorhus/p-locate", + "asOfVersion": "4.0.0" + }, + { + "libraryName": "p-log", + "typingsPackageName": "p-log", + "sourceRepoURL": "https://github.com/sindresorhus/p-log", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-map", "typingsPackageName": "p-map", "sourceRepoURL": "https://github.com/sindresorhus/p-map", "asOfVersion": "2.0.0" }, + { + "libraryName": "p-map-series", + "typingsPackageName": "p-map-series", + "sourceRepoURL": "https://github.com/sindresorhus/p-map-series", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-memoize", + "typingsPackageName": "p-memoize", + "sourceRepoURL": "https://github.com/sindresorhus/p-memoize", + "asOfVersion": "3.0.0" + }, + { + "libraryName": "p-one", + "typingsPackageName": "p-one", + "sourceRepoURL": "https://github.com/kevva/p-one", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-pipe", "typingsPackageName": "p-pipe", "sourceRepoURL": "https://github.com/sindresorhus/p-pipe", "asOfVersion": "2.0.1" }, + { + "libraryName": "p-progress", + "typingsPackageName": "p-progress", + "sourceRepoURL": "https://github.com/sindresorhus/p-progress", + "asOfVersion": "0.3.0" + }, + { + "libraryName": "p-props", + "typingsPackageName": "p-props", + "sourceRepoURL": "https://github.com/sindresorhus/p-props", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-queue", "typingsPackageName": "p-queue", "sourceRepoURL": "https://github.com/sindresorhus/p-queue", "asOfVersion": "3.2.1" }, + { + "libraryName": "p-reduce", + "typingsPackageName": "p-reduce", + "sourceRepoURL": "https://github.com/sindresorhus/p-reduce", + "asOfVersion": "2.0.0" + }, + { + "libraryName": "p-retry", + "typingsPackageName": "p-retry", + "sourceRepoURL": "https://github.com/sindresorhus/p-retry", + "asOfVersion": "4.0.0" + }, + { + "libraryName": "p-series", + "typingsPackageName": "p-series", + "sourceRepoURL": "https://github.com/sindresorhus/p-series", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-some", "typingsPackageName": "p-some", "sourceRepoURL": "https://github.com/sindresorhus/p-some", "asOfVersion": "4.0.1" }, + { + "libraryName": "p-tap", + "typingsPackageName": "p-tap", + "sourceRepoURL": "https://github.com/sindresorhus/p-tap", + "asOfVersion": "2.0.0" + }, { "libraryName": "p-throttle", "typingsPackageName": "p-throttle", "sourceRepoURL": "https://github.com/sindresorhus/p-throttle", "asOfVersion": "2.1.0" }, + { + "libraryName": "p-timeout", + "typingsPackageName": "p-timeout", + "sourceRepoURL": "https://github.com/sindresorhus/p-timeout", + "asOfVersion": "3.0.0" + }, + { + "libraryName": "package-json", + "typingsPackageName": "package-json", + "sourceRepoURL": "https://github.com/sindresorhus/package-json", + "asOfVersion": "6.1.0" + }, { "libraryName": "param-case", "typingsPackageName": "param-case", @@ -1380,6 +1602,12 @@ "sourceRepoURL": "https://github.com/pillarjs/path-to-regexp", "asOfVersion": "1.7.0" }, + { + "libraryName": "path-type", + "typingsPackageName": "path-type", + "sourceRepoURL": "https://github.com/sindresorhus/path-type", + "asOfVersion": "4.0.0" + }, { "libraryName": "perfect-scrollbar", "typingsPackageName": "perfect-scrollbar", @@ -1422,6 +1650,18 @@ "sourceRepoURL": "https://github.com/sindresorhus/pkg-conf", "asOfVersion": "3.0.0" }, + { + "libraryName": "pkg-dir", + "typingsPackageName": "pkg-dir", + "sourceRepoURL": "https://github.com/sindresorhus/pkg-dir", + "asOfVersion": "4.0.0" + }, + { + "libraryName": "pkg-versions", + "typingsPackageName": "pkg-versions", + "sourceRepoURL": "https://github.com/sindresorhus/pkg-versions", + "asOfVersion": "2.0.0" + }, { "libraryName": "plottable", "typingsPackageName": "plottable", @@ -1800,6 +2040,12 @@ "sourceRepoURL": "https://github.com/zeh/simplesignal", "asOfVersion": "1.0.0" }, + { + "libraryName": "@sindresorhus/df", + "typingsPackageName": "sindresorhus__df", + "sourceRepoURL": "https://github.com/sindresorhus/df", + "asOfVersion": "3.0.0" + }, { "libraryName": "@sindresorhus/slugify", "typingsPackageName": "sindresorhus__slugify", @@ -2004,6 +2250,12 @@ "sourceRepoURL": "https://github.com/kriasoft/universal-router", "asOfVersion": "8.0.0" }, + { + "libraryName": "unused-filename", + "typingsPackageName": "unused-filename", + "sourceRepoURL": "https://github.com/sindresorhus/unused-filename", + "asOfVersion": "2.0.0" + }, { "libraryName": "upper-case", "typingsPackageName": "upper-case", @@ -2064,6 +2316,12 @@ "sourceRepoURL": "https://github.com/sindresorhus/wait-for-localhost", "asOfVersion": "3.1.0" }, + { + "libraryName": "wallpaper", + "typingsPackageName": "wallpaper", + "sourceRepoURL": "https://github.com/sindresorhus/wallpaper", + "asOfVersion": "4.3.0" + }, { "libraryName": "webcola", "typingsPackageName": "webcola", diff --git a/types/aggregate-error/aggregate-error-tests.ts b/types/aggregate-error/aggregate-error-tests.ts deleted file mode 100644 index 69e544f9ee..0000000000 --- a/types/aggregate-error/aggregate-error-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import AggregateError = require('aggregate-error'); - -const err = new AggregateError([new Error('foo'), 'bar']); - -for (const el of Array.from(err)) { - const err: Error = el; -} - -throw err; diff --git a/types/aggregate-error/index.d.ts b/types/aggregate-error/index.d.ts deleted file mode 100644 index 8c8c4cd3b2..0000000000 --- a/types/aggregate-error/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for aggregate-error 1.0 -// Project: https://github.com/sindresorhus/aggregate-error#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = AggregateError; - -declare class AggregateError extends Error implements Iterable { - constructor(errors: Iterable); - - [Symbol.iterator](): Iterator; -} diff --git a/types/aggregate-error/tsconfig.json b/types/aggregate-error/tsconfig.json deleted file mode 100644 index f092ab1c3e..0000000000 --- a/types/aggregate-error/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "aggregate-error-tests.ts" - ] -} \ No newline at end of file diff --git a/types/bser/index.d.ts b/types/bser/index.d.ts new file mode 100644 index 0000000000..75695d85b1 --- /dev/null +++ b/types/bser/index.d.ts @@ -0,0 +1,100 @@ +// Type definitions for bser 2.0 +// Project: https://facebook.github.io/watchman/docs/bser.html +// Definitions by: Claas Ahlrichs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.7 + +/// + +import { EventEmitter } from "events"; +import Int64 = require("node-int64"); + +export type InputWrapper = + | Buffer + | string + | NodeJS.TypedArray + | DataView + | ArrayBuffer + | SharedArrayBuffer; +export type IntWrapper = number | Int64; +export type AnyWrapper = boolean | IntWrapper | null | string | object; + +export class Accumulator { + buf: Buffer; + readOffset: number; + writeOffset: number; + + constructor(initsize?: number); + + append(buf: InputWrapper): void; + + assertReadableSize(size: number): void; + + peekDouble(): number; + + peekInt(size: number): IntWrapper; + + peekString(size: number): string; + + readAdvance(size: number): void; + + readAvail(): number; + + readDouble(): number; + + // replace "IntWrapper" with "number"? + readInt(bytes: number): IntWrapper; + + readString(size: number): string; + + reserve(size: number): void; + + writeAvail(): number; + + writeByte(value: number): void; + + writeDouble(value: number): void; + + writeInt(value: number, size: number): void; +} + +export class BunserBuf extends EventEmitter { + buf: Accumulator; + state: 0 | 1; + // replace "IntWrapper" with "number"? + pduLen?: false | IntWrapper; + + constructor(); + + append( + buf: InputWrapper, + synchronous?: false + ): AnyWrapper | AnyWrapper[] | undefined; + append(buf: InputWrapper, synchronous: true): void; + + decodeAny(): AnyWrapper | AnyWrapper[]; + + decodeArray(): AnyWrapper[]; + + // replace "IntWrapper" with "number"? + decodeInt(relaxSizeAsserts?: boolean): false | IntWrapper; + + decodeObject(): object; + + decodeString(): string; + + decodeTemplate(): AnyWrapper[]; + + expectCode(expected: number): void; + + process(synchronous?: false): AnyWrapper | AnyWrapper[] | undefined; + process(synchronous: true): void; + + processLater(): void; + + raise(reason: string): void; +} + +export function dumpToBuffer(val: any): Buffer; + +export function loadFromBuffer(input: InputWrapper): AnyWrapper | AnyWrapper[]; diff --git a/types/bser/test/sample1.ts b/types/bser/test/sample1.ts new file mode 100644 index 0000000000..3958260c42 --- /dev/null +++ b/types/bser/test/sample1.ts @@ -0,0 +1,4 @@ +import * as bser from "bser"; + +const encoded = bser.dumpToBuffer(["hello"]); +console.log(bser.loadFromBuffer(encoded)); // ['hello'] diff --git a/types/bser/test/sample2.ts b/types/bser/test/sample2.ts new file mode 100644 index 0000000000..2ab145626a --- /dev/null +++ b/types/bser/test/sample2.ts @@ -0,0 +1,7 @@ +import * as bser from "bser"; + +const bunser = new bser.BunserBuf(); + +bunser.on("value", obj => { + console.log(obj); +}); diff --git a/types/bser/test/sample3.ts b/types/bser/test/sample3.ts new file mode 100644 index 0000000000..41831c4447 --- /dev/null +++ b/types/bser/test/sample3.ts @@ -0,0 +1,16 @@ +import * as bser from "bser"; +import net from "net"; + +const obj = "sample data"; +const bunser = new bser.BunserBuf(); + +bunser.on("value", obj => { + console.log("data from socket", obj); +}); + +const socket = net.connect("/socket"); + +socket.on("data", buf => { + bunser.append(buf); +}); +socket.write(bser.dumpToBuffer(obj)); diff --git a/types/bser/test/tests.ts b/types/bser/test/tests.ts new file mode 100644 index 0000000000..2037e0517b --- /dev/null +++ b/types/bser/test/tests.ts @@ -0,0 +1,86 @@ +import * as bser from "bser"; +import Int64 from "node-int64"; +import * as assert from "assert"; + +// This is a hard-coded template representation from the C test suite +const template = + "\x00\x01\x03\x28" + + "\x0b\x00\x03\x02\x02\x03\x04\x6e\x61\x6d\x65\x02" + + "\x03\x03\x61\x67\x65\x03\x03\x02\x03\x04\x66\x72" + + "\x65\x64\x03\x14\x02\x03\x04\x70\x65\x74\x65\x03" + + "\x1e\x0c\x03\x19"; + +const val = bser.loadFromBuffer(template); +assert.deepStrictEqual(val, [ + { name: "fred", age: 20 }, + { name: "pete", age: 30 }, + { age: 25 } +]); + +function roundtrip(val: any) { + const encoded = bser.dumpToBuffer(val); + const decoded = bser.loadFromBuffer(encoded); + assert.deepStrictEqual(decoded, val); +} + +const values_to_test = [ + 1, + "hello", + 1.5, + false, + true, + new Int64("0x0123456789abcdef"), + 127, + 128, + 129, + 32767, + 32768, + 32769, + 65534, + 65536, + 65537, + 2147483647, + 2147483648, + 2147483649, + null, + [1, 2, 3], + { foo: "bar" }, + { nested: { struct: "hello", list: [true, false, 1, "string"] } } +]; + +for (const value of values_to_test) { + roundtrip(value); +} +roundtrip(values_to_test); + +// Verify Accumulator edge cases +const acc = new bser.Accumulator(8); +acc.append("hello"); +assert.equal(acc.readAvail(), 5); +assert.equal(acc.readOffset, 0); +assert.equal(acc.readString(3), "hel"); +assert.equal(acc.readOffset, 3); +assert.equal(acc.readAvail(), 2); +assert.equal(acc.writeAvail(), 3); + +// This should trigger a shunt and not make the buffer bigger +acc.reserve(5); +assert.equal(acc.readOffset, 0, "shunted"); +assert.equal(acc.readAvail(), 2, "still have 2 available to read"); +assert.equal(acc.writeAvail(), 6, "2 left to read out of 8 total space"); +assert.equal(acc.peekString(2), "lo", "have the correct remainder"); + +// Don't include keys that have undefined values +const res = bser.dumpToBuffer({ expression: undefined }); +assert.deepStrictEqual(bser.loadFromBuffer(res), {}); + +// Dump numbers without fraction to integers +let buffer; +buffer = bser.dumpToBuffer(1); +assert.equal(buffer.toString("hex"), "000105020000000301"); +buffer = bser.dumpToBuffer(1.0); +assert.equal(buffer.toString("hex"), "000105020000000301"); + +// Dump numbers with fraction to double +buffer = bser.dumpToBuffer(1.1); +assert.equal(buffer.toString("hex"), "00010509000000079a9999999999f13f"); diff --git a/types/sindresorhus__df/tsconfig.json b/types/bser/tsconfig.json similarity index 59% rename from types/sindresorhus__df/tsconfig.json rename to types/bser/tsconfig.json index 9dcf70310e..4fb45a708a 100644 --- a/types/sindresorhus__df/tsconfig.json +++ b/types/bser/tsconfig.json @@ -1,28 +1,23 @@ { "compilerOptions": { "module": "commonjs", - "lib": [ - "es6" - ], + "lib": ["es6"], "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": true, + "strictFunctionTypes": true, "baseUrl": "../", - "typeRoots": [ - "../" - ], + "typeRoots": ["../"], "types": [], "noEmit": true, - "strictFunctionTypes": true, "forceConsistentCasingInFileNames": true, - "paths": { - "@sindresorhus/df": [ - "sindresorhus__df" - ] - } + "esModuleInterop": true }, "files": [ "index.d.ts", - "sindresorhus__df-tests.ts" + "test/tests.ts", + "test/sample1.ts", + "test/sample2.ts", + "test/sample3.ts" ] } diff --git a/types/aggregate-error/tslint.json b/types/bser/tslint.json similarity index 100% rename from types/aggregate-error/tslint.json rename to types/bser/tslint.json diff --git a/types/bull/bull-tests.tsx b/types/bull/bull-tests.tsx index 13ae21f5a4..64f4eef698 100644 --- a/types/bull/bull-tests.tsx +++ b/types/bull/bull-tests.tsx @@ -70,6 +70,19 @@ videoQueue.add({video: 'http://example.com/video1.mov'}); audioQueue.add({audio: 'http://example.com/audio1.mp3'}); imageQueue.add({image: 'http://example.com/image1.tiff'}); +////////////////////////////////////////////////////////////////////////////////// +// +// Test Redis Cluster connexion +// +////////////////////////////////////////////////////////////////////////////////// + +const clusterQueue = new Queue('queue on redis cluster', { + prefix: 'cluster-test', + createClient: (clusterUri: Redis.ClusterNode) => { + return new Redis.Cluster([{port: 6379, host: '127.0.0.1'}]); + } +}); + ////////////////////////////////////////////////////////////////////////////////// // // Re-using Redis Connections diff --git a/types/bull/index.d.ts b/types/bull/index.d.ts index cd2d1a9047..5297eadb19 100644 --- a/types/bull/index.d.ts +++ b/types/bull/index.d.ts @@ -49,9 +49,9 @@ declare namespace Bull { /** * When specified, the `Queue` will use this function to create new `ioredis` client connections. - * This is useful if you want to re-use connections. + * This is useful if you want to re-use connections or connect to a Redis cluster. */ - createClient?(type: 'client' | 'subscriber' | 'bclient', redisOpts?: Redis.RedisOptions): Redis.Redis; + createClient?(type: 'client' | 'subscriber' | 'bclient', redisOpts?: Redis.RedisOptions): Redis.Redis | Redis.Cluster; /** * Prefix to use for all redis keys diff --git a/types/chai-moment/chai-moment-tests.ts b/types/chai-moment/chai-moment-tests.ts new file mode 100644 index 0000000000..6354c4796b --- /dev/null +++ b/types/chai-moment/chai-moment-tests.ts @@ -0,0 +1,14 @@ +import { assert, expect, use } from 'chai'; +import chaiMoment = require('chai-moment'); + +use(chaiMoment); + +// bdd style +expect('2019-03-14').to.be.afterMoment('2019-03-12', 'day'); +expect('2019-03-14').to.be.beforeMoment('2019-03-16'); +expect('2019-03-14').to.be.sameMoment('2019-03-14', 'day'); + +// tdd style +assert.afterMoment('2019-03-14', '2019-03-12'); +assert.beforeMoment('2019-03-14', '2019-03-18', 'day'); +assert.sameMoment('2019-03-14', '2019-03-14', 'day'); diff --git a/types/chai-moment/index.d.ts b/types/chai-moment/index.d.ts new file mode 100644 index 0000000000..0b19b7573f --- /dev/null +++ b/types/chai-moment/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for chai-moment 0.1 +// Project: https://github.com/picardy/chai-moment +// Definitions by: Chris Godsey +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +/// + +declare global { + namespace Chai { + interface Assertion extends LanguageChains, NumericComparison, TypeComparison { + afterMoment(expected: string, granularity?: string): void; + beforeMoment(expected: string, granularity?: string): void; + sameMoment(expected: string, granularity?: string): void; + } + + interface Assert { + afterMoment(val: any, exp: any, granularity?: any, msg?: any): void; + beforeMoment(val: any, exp: any, granularity?: any, msg?: any): void; + sameMoment(val: any, exp: any, granularity?: any, msg?: any): void; + } + } +} + +declare function chaiMoment(chai: any, utils: any): void; +export = chaiMoment; diff --git a/types/fkill/tsconfig.json b/types/chai-moment/tsconfig.json similarity index 93% rename from types/fkill/tsconfig.json rename to types/chai-moment/tsconfig.json index 2e36e29395..571fe4f114 100644 --- a/types/fkill/tsconfig.json +++ b/types/chai-moment/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "fkill-tests.ts" + "chai-moment-tests.ts" ] } diff --git a/types/chai-moment/tslint.json b/types/chai-moment/tslint.json new file mode 100644 index 0000000000..2750cc0197 --- /dev/null +++ b/types/chai-moment/tslint.json @@ -0,0 +1 @@ +{ "extends": "dtslint/dt.json" } \ No newline at end of file diff --git a/types/circular-dependency-plugin/circular-dependency-plugin-tests.ts b/types/circular-dependency-plugin/circular-dependency-plugin-tests.ts new file mode 100644 index 0000000000..8c627651e7 --- /dev/null +++ b/types/circular-dependency-plugin/circular-dependency-plugin-tests.ts @@ -0,0 +1,29 @@ +import * as CircularDependencyPlugin from 'circular-dependency-plugin'; +import * as webpack from 'webpack'; + +new CircularDependencyPlugin(); +new CircularDependencyPlugin({}); + +const MAX_CYCLES = 5; +let numCyclesDetected = 0; + +new CircularDependencyPlugin({ + allowAsyncCycles: false, + cwd: process.cwd(), + exclude: /a\.js|node_modules/, + failOnError: true, + onDetected({ module: webpackModuleRecord, paths, compilation }) { + numCyclesDetected++; + compilation.warnings.push(new Error(paths.join(' -> '))); + }, + onStart({ compilation }) { + numCyclesDetected = 0; + }, + onEnd({ compilation }) { + if (numCyclesDetected > MAX_CYCLES) { + compilation.errors.push(new Error('Too many cycles')); + } + }, +}); + +webpack({ plugins: [new CircularDependencyPlugin()] }); diff --git a/types/circular-dependency-plugin/index.d.ts b/types/circular-dependency-plugin/index.d.ts new file mode 100644 index 0000000000..89c14b0ec0 --- /dev/null +++ b/types/circular-dependency-plugin/index.d.ts @@ -0,0 +1,30 @@ +// Type definitions for circular-dependency-plugin 5.0 +// Project: https://github.com/aackerman/circular-dependency-plugin +// Definitions by: Olegs Jeremejevs +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.3 + +import { Plugin, Module, compilation } from 'webpack'; + +export = CircularDependencyPlugin; + +declare class CircularDependencyPlugin extends Plugin { + constructor(options?: CircularDependencyPlugin.Options); + // Not exposing `isCyclic` because it isn't meant to be public, I believe +} + +declare namespace CircularDependencyPlugin { + interface Options { + allowAsyncCycles?: boolean; + cwd?: string; + exclude?: RegExp; + failOnError?: boolean; + onDetected?: (x: { + module: Module; + paths: string[]; + compilation: compilation.Compilation; + }) => void; + onEnd?: (x: { compilation: compilation.Compilation }) => void; + onStart?: (x: { compilation: compilation.Compilation }) => void; + } +} diff --git a/types/decompress-response/tsconfig.json b/types/circular-dependency-plugin/tsconfig.json similarity index 90% rename from types/decompress-response/tsconfig.json rename to types/circular-dependency-plugin/tsconfig.json index c7a77a9fd1..476eb673dd 100644 --- a/types/decompress-response/tsconfig.json +++ b/types/circular-dependency-plugin/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "decompress-response-tests.ts" + "circular-dependency-plugin-tests.ts" ] } diff --git a/types/decompress-response/tslint.json b/types/circular-dependency-plugin/tslint.json similarity index 100% rename from types/decompress-response/tslint.json rename to types/circular-dependency-plugin/tslint.json diff --git a/types/cytoscape/index.d.ts b/types/cytoscape/index.d.ts index b4ca7de92f..aec7c9bf6c 100644 --- a/types/cytoscape/index.d.ts +++ b/types/cytoscape/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Cytoscape.js 3.3 +// Type definitions for Cytoscape.js 3.4 // Project: http://js.cytoscape.org/ // Definitions by: Fabian Schmidt and Fred Eisele // Shenghan Gao @@ -3229,7 +3229,7 @@ declare namespace cytoscape { * This finds the shortest path from the starting node to all other nodes in the collection. * http://js.cytoscape.org/#eles.bellmanFord */ - bellmanFort(options: SearchBellmanFordOptions): SearchBellmanFordResult; + bellmanFord(options: SearchBellmanFordOptions): SearchBellmanFordResult; /** * Perform Kruskal's algorithm on the elements in the collection, * returning the minimum spanning tree, assuming undirected edges. diff --git a/types/decompress-response/decompress-response-tests.ts b/types/decompress-response/decompress-response-tests.ts deleted file mode 100644 index f47665cbe0..0000000000 --- a/types/decompress-response/decompress-response-tests.ts +++ /dev/null @@ -1,6 +0,0 @@ -import decompressResponse = require("decompress-response"); -import http = require("http"); - -http.get("localhost", response => { - response = decompressResponse(response); -}); diff --git a/types/decompress-response/index.d.ts b/types/decompress-response/index.d.ts deleted file mode 100644 index 8e7ec88646..0000000000 --- a/types/decompress-response/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Type definitions for decompress-response 3.3 -// Project: https://github.com/sindresorhus/decompress-response#readme -// Definitions by: Daniel Rosenwasser -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import http = require("http"); - -export = decompress_response; -declare function decompress_response(response: http.IncomingMessage): http.IncomingMessage; diff --git a/types/dom-loaded/dom-loaded-tests.ts b/types/dom-loaded/dom-loaded-tests.ts deleted file mode 100644 index f8a3e5486d..0000000000 --- a/types/dom-loaded/dom-loaded-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ -import domLoaded = require("dom-loaded"); - -domLoaded.then(() => console.log("DOM is loaded")); diff --git a/types/dom-loaded/index.d.ts b/types/dom-loaded/index.d.ts deleted file mode 100644 index 5d4d5154c4..0000000000 --- a/types/dom-loaded/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for dom-loaded 1.0 -// Project: https://github.com/sindresorhus/dom-loaded#readme -// Definitions by: Lukas Tetzlaf -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare const domLoaded: Promise; -export = domLoaded; diff --git a/types/domutils/index.d.ts b/types/domutils/index.d.ts index 14971086cb..5300a68a8c 100644 --- a/types/domutils/index.d.ts +++ b/types/domutils/index.d.ts @@ -82,7 +82,7 @@ export function getName(elem: DomElement): string; * @argument dom An array of DomElement that should be stringified * @argument [opts] Optional options object */ -export function getOuterHTML(dom: DomElement[], opts: { decodeEntities?: boolean, xmlMode?: boolean}): string; +export function getOuterHTML(dom: DomElement[], opts?: { decodeEntities?: boolean, xmlMode?: boolean}): string; export function getParent(elem: DomElement): DomElement; export function getSiblings(elem: DomElement): DomElement[]; export function getText(elem: DomElement): string; diff --git a/types/echarts/index.d.ts b/types/echarts/index.d.ts index 1332f0114a..41b3fe801f 100644 --- a/types/echarts/index.d.ts +++ b/types/echarts/index.d.ts @@ -7,6 +7,7 @@ // Roman // Bilal // TMTron +// dwhitney // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 diff --git a/types/echarts/options/series/lines.d.ts b/types/echarts/options/series/lines.d.ts index 957acf0ac7..de22abf5fb 100644 --- a/types/echarts/options/series/lines.d.ts +++ b/types/echarts/options/series/lines.d.ts @@ -13253,8 +13253,6 @@ declare namespace echarts { */ name?: string; - children: [DataObject]; - /** * An array includes two ore more than two coordinates. * Each coordinate could be `[x, y]` in diff --git a/types/element-ready/element-ready-tests.ts b/types/element-ready/element-ready-tests.ts deleted file mode 100644 index e003947bc1..0000000000 --- a/types/element-ready/element-ready-tests.ts +++ /dev/null @@ -1,9 +0,0 @@ -import elementReady = require('element-ready'); - -const p = elementReady('#unicorn'); - -p.then(element => { - const el: HTMLElement = element; -}); - -p.cancel(); diff --git a/types/element-ready/index.d.ts b/types/element-ready/index.d.ts deleted file mode 100644 index 03a750b59d..0000000000 --- a/types/element-ready/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for element-ready 2.1 -// Project: https://github.com/sindresorhus/element-ready#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -import pCancelable = require('p-cancelable'); - -export = elementReady; - -declare function elementReady(selector: string): pCancelable.PCancelable; diff --git a/types/ember/index.d.ts b/types/ember/index.d.ts index d7aaa35b36..d048007d8f 100755 --- a/types/ember/index.d.ts +++ b/types/ember/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for Ember.js 3.0 +// Type definitions for Ember.js 3.1 // Project: http://emberjs.com/, https://github.com/emberjs/ember // Definitions by: Jed Mao // bttf diff --git a/types/ember/test/helper.ts b/types/ember/test/helper.ts index 4743841e31..ec4806b18f 100755 --- a/types/ember/test/helper.ts +++ b/types/ember/test/helper.ts @@ -14,8 +14,14 @@ class SessionService extends Ember.Service { currentUser: User; } +declare module '@ember/service' { + interface Registry { + session: SessionService; + } +} + const CurrentUserEmailHelper = Ember.Helper.extend({ - session: Ember.inject.service() as Ember.ComputedProperty, + session: Ember.inject.service('session'), onNewUser: Ember.observer('session.currentUser', function(this: Ember.Helper) { this.recompute(); }), diff --git a/types/ember__controller/ember__controller-tests.ts b/types/ember__controller/ember__controller-tests.ts deleted file mode 100644 index 02307f447c..0000000000 --- a/types/ember__controller/ember__controller-tests.ts +++ /dev/null @@ -1,11 +0,0 @@ -import Controller from '@ember/controller'; - -Controller.extend ({ - queryParams: ['category'], - category: null, - isExpanded: false, - - toggleBody() { - this.toggleProperty('isExpanded'); - } -}); diff --git a/types/ember__controller/index.d.ts b/types/ember__controller/index.d.ts index 77522a3b29..5071811a85 100644 --- a/types/ember__controller/index.d.ts +++ b/types/ember__controller/index.d.ts @@ -31,9 +31,11 @@ export interface ControllerMixin extends ActionHandler { export const ControllerMixin: Mixin; // tslint:disable-next-line:no-empty-interface export default class Controller extends EmberObject.extend(ControllerMixin) {} +export function inject(): ComputedProperty & PropertyDecorator; export function inject( name: K -): ComputedProperty; +): ComputedProperty & PropertyDecorator; +export function inject(target: object, propertyKey: string | symbol): void; // A type registry for Ember `Controller`s. Meant to be declaration-merged // so string lookups resolve to the correct type. diff --git a/types/ember__controller/test/main.ts b/types/ember__controller/test/main.ts new file mode 100644 index 0000000000..88722b0909 --- /dev/null +++ b/types/ember__controller/test/main.ts @@ -0,0 +1,14 @@ +import Controller, { inject } from "@ember/controller"; + +Controller.extend({ + queryParams: ["category"], + category: null, + isExpanded: false, + + first: inject(), + second: inject('second'), + + toggleBody() { + this.toggleProperty("isExpanded"); + } +}); diff --git a/types/ember__controller/test/octane.ts b/types/ember__controller/test/octane.ts new file mode 100644 index 0000000000..9d4c73bf8d --- /dev/null +++ b/types/ember__controller/test/octane.ts @@ -0,0 +1,26 @@ +import Controller, { inject } from "@ember/controller"; + +class FirstController extends Controller { + foo = "bar"; + @inject second: InstanceType; + @inject() otherSecond: InstanceType; + @inject("second") moreSecond: InstanceType; + + first() { + return ""; + } +} +const SecondController = Controller.extend({ + foo: "bar", + + second() { + return ""; + } +}); + +declare module "@ember/controller" { + interface Registry { + first: FirstController; + second: InstanceType; + } +} diff --git a/types/ember__controller/tsconfig.json b/types/ember__controller/tsconfig.json index 865ec007ac..5ca97b037a 100644 --- a/types/ember__controller/tsconfig.json +++ b/types/ember__controller/tsconfig.json @@ -10,6 +10,7 @@ "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, + "experimentalDecorators": true, "baseUrl": "../", "typeRoots": [ "../" @@ -25,6 +26,7 @@ }, "files": [ "index.d.ts", - "ember__controller-tests.ts" + "test/main.ts", + "test/octane.ts" ] } diff --git a/types/ember__object/computed.d.ts b/types/ember__object/computed.d.ts index e63ee86294..8053c5a82a 100644 --- a/types/ember__object/computed.d.ts +++ b/types/ember__object/computed.d.ts @@ -1,4 +1,4 @@ -import { computed } from '@ember/object'; +import { computed } from "@ember/object"; /** * A computed property transforms an objects function into a property. @@ -36,13 +36,70 @@ export default class ComputedProperty { meta(): {}; } -export const alias: typeof computed.alias; -export const and: typeof computed.and; -export const bool: typeof computed.bool; -export const collect: typeof computed.collect; -export const deprecatingAlias: typeof computed.deprecatingAlias; -export const empty: typeof computed.empty; -export const equal: typeof computed.equal; +/** + * Creates a new property that is an alias for another property + * on an object. Calls to `get` or `set` this property behave as + * though they were called on the original property. + */ +export function alias( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * A computed property that performs a logical `and` on the + * original values for the provided dependent properties. + */ +export function and( + ...dependentKeys: string[] +): ComputedProperty & PropertyDecorator; +/** + * A computed property that converts the provided dependent property + * into a boolean value. + */ +export function bool( + dependentKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that returns the array of values + * for the provided dependent properties. + */ +export function collect( + ...dependentKeys: string[] +): ComputedProperty & PropertyDecorator; + +/** + * Creates a new property that is an alias for another property + * on an object. Calls to `get` or `set` this property behave as + * though they were called on the original property, but also + * print a deprecation warning. + */ +export function deprecatingAlias( + dependentKey: string, + options: { id: string; until: string } +): ComputedProperty & PropertyDecorator; +/** + * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options + */ +export function deprecatingAlias( + dependentKey: string, + options?: { id?: string; until?: string } +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that returns true if the value of the dependent + * property is null, an empty string, empty array, or empty function. + */ +export function empty( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns true if the provided dependent property + * is equal to the given value. + */ +export function equal( + dependentKey: string, + value: any +): ComputedProperty & PropertyDecorator; /** * Expands `pattern`, invoking `callback` for each expansion. */ @@ -50,28 +107,213 @@ export function expandProperties( pattern: string, callback: (expanded: string) => void ): void; -export const filter: typeof computed.filter; -export const filterBy: typeof computed.filterBy; -export const gt: typeof computed.gt; -export const gte: typeof computed.gte; -export const intersect: typeof computed.intersect; -export const lt: typeof computed.lt; -export const lte: typeof computed.lte; -export const map: typeof computed.map; -export const mapBy: typeof computed.mapBy; -export const match: typeof computed.match; -export const max: typeof computed.max; -export const min: typeof computed.min; -export const none: typeof computed.none; -export const not: typeof computed.not; -export const notEmpty: typeof computed.notEmpty; -export const oneWay: typeof computed.oneWay; -export const or: typeof computed.or; -export const readOnly: typeof computed.readOnly; -export const reads: typeof computed.reads; -export const setDiff: typeof computed.setDiff; -export const sort: typeof computed.sort; -export const sum: typeof computed.sum; -export const union: typeof computed.union; -export const uniq: typeof computed.uniq; -export const uniqBy: typeof computed.uniqBy; + +/** + * Filters the array by the callback. + */ +export function filter( + dependentKey: string, + callback: (value: any, index: number, array: any[]) => boolean +): ComputedProperty & PropertyDecorator; + +/** + * Filters the array by the property and value + */ +export function filterBy( + dependentKey: string, + propertyKey: string, + value?: any +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that returns true if the provided dependent property + * is greater than the provided value. + */ +export function gt( + dependentKey: string, + value: number +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns true if the provided dependent property + * is greater than or equal to the provided value. + */ +export function gte( + dependentKey: string, + value: number +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the elements + * two or more dependent arrays have in common. + */ +export function intersect( + ...propertyKeys: string[] +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that returns true if the provided dependent property + * is less than the provided value. + */ +export function lt( + dependentKey: string, + value: number +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns true if the provided dependent property + * is less than or equal to the provided value. + */ +export function lte( + dependentKey: string, + value: number +): ComputedProperty & PropertyDecorator; + +/** + * Returns an array mapped via the callback + */ +export function map( + dependentKey: string, + callback: (value: any, index: number, array: any[]) => U +): ComputedProperty & PropertyDecorator; + +/** + * Returns an array mapped to the specified key. + */ +export function mapBy( + dependentKey: string, + propertyKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which matches the original value for the + * dependent property against a given RegExp, returning `true` + * if the value matches the RegExp and `false` if it does not. + */ +export function match( + dependentKey: string, + regexp: RegExp +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that calculates the maximum value in the + * dependent array. This will return `-Infinity` when the dependent + * array is empty. + */ +export function max( + dependentKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that calculates the minimum value in the + * dependent array. This will return `Infinity` when the dependent + * array is empty. + */ +export function min( + dependentKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property that returns true if the value of the dependent + * property is null or undefined. This avoids errors from JSLint complaining + * about use of ==, which can be technically confusing. + */ +export function none( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns the inverse boolean value + * of the original value for the dependent property. + */ +export function not( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns true if the value of the dependent + * property is NOT null, an empty string, empty array, or empty function. + */ +export function notEmpty( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * Where `computed.alias` aliases `get` and `set`, and allows for bidirectional + * data flow, `computed.oneWay` only provides an aliased `get`. The `set` will + * not mutate the upstream property, rather causes the current property to + * become the value set. This causes the downstream property to permanently + * diverge from the upstream property. + */ +export function oneWay( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * A computed property which performs a logical `or` on the + * original values for the provided dependent properties. + */ +export function or( + ...dependentKeys: string[] +): ComputedProperty & PropertyDecorator; +/** + * Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides + * a readOnly one way binding. Very often when using `computed.oneWay` one does + * not also want changes to propagate back up, as they will replace the value. + */ +export function readOnly( + dependentKey: string +): ComputedProperty & PropertyDecorator; +/** + * This is a more semantically meaningful alias of `computed.oneWay`, + * whose name is somewhat ambiguous as to which direction the data flows. + */ +export function reads( + dependentKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the + * properties from the first dependent array that are not in the second + * dependent array. + */ +export function setDiff( + setAProperty: string, + setBProperty: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the + * properties from the first dependent array sorted based on a property + * or sort function. + */ +export function sort( + itemsKey: string, + sortDefinition: string | ((itemA: any, itemB: any) => number) +): ComputedProperty & PropertyDecorator; +/** + * A computed property that returns the sum of the values + * in the dependent array. + */ +export function sum( + dependentKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the unique + * elements from one or more dependent arrays. + */ +export function uniq( + propertyKey: string +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the unique + * elements from one or more dependent arrays. + */ +export function union( + ...propertyKeys: string[] +): ComputedProperty & PropertyDecorator; + +/** + * A computed property which returns a new array with all the unique + * elements from an array, with uniqueness determined by specific key. + */ +export function uniqBy( + dependentKey: string, + propertyKey: string +): ComputedProperty & PropertyDecorator; diff --git a/types/ember__object/index.d.ts b/types/ember__object/index.d.ts index f287a51a90..fb5a76efd2 100644 --- a/types/ember__object/index.d.ts +++ b/types/ember__object/index.d.ts @@ -1,19 +1,20 @@ -// Type definitions for non-npm package @ember/object 3.0 +// Type definitions for non-npm package @ember/object 3.1 // Project: https://emberjs.com/api/ember/3.4/modules/@ember%2Fobject // Definitions by: Mike North // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 -import CoreObject from '@ember/object/core'; -import Observable from '@ember/object/observable'; +import CoreObject from "@ember/object/core"; +import Observable from "@ember/object/observable"; import { ComputedPropertyCallback, UnwrapComputedPropertyGetter, UnwrapComputedPropertySetter, UnwrapComputedPropertyGetters, - UnwrapComputedPropertySetters -} from '@ember/object/-private/types'; -import ComputedProperty from '@ember/object/computed'; + UnwrapComputedPropertySetters, + ExtractPropertyNamesOfType +} from "@ember/object/-private/types"; +import ComputedProperty, * as ComputedNamespace from "@ember/object/computed"; /** * `Ember.Object` is the main base class for all Ember objects. It is a subclass @@ -21,252 +22,96 @@ import ComputedProperty from '@ember/object/computed'; * see the documentation for each of these. */ export default class EmberObject extends CoreObject.extend(Observable) {} +declare function computed(...deps: string[]): (target: object, propertyKey: string) => void; +declare function computed( + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + k3: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + k3: string, + k4: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + k6: string, + cb: ComputedPropertyCallback +): ComputedProperty; +declare function computed( + k1: string, + k2: string, + k3: string, + k4: string, + k5: string, + k6: string, + k7: string, + ...rest: any[] +): ComputedProperty; -export const computed: { - (cb: ComputedPropertyCallback): ComputedProperty; - (k1: string, cb: ComputedPropertyCallback): ComputedProperty; - ( - k1: string, - k2: string, - cb: ComputedPropertyCallback - ): ComputedProperty; - ( - k1: string, - k2: string, - k3: string, - cb: ComputedPropertyCallback - ): ComputedProperty; - ( - k1: string, - k2: string, - k3: string, - k4: string, - cb: ComputedPropertyCallback - ): ComputedProperty; - ( - k1: string, - k2: string, - k3: string, - k4: string, - k5: string, - cb: ComputedPropertyCallback - ): ComputedProperty; - ( - k1: string, - k2: string, - k3: string, - k4: string, - k5: string, - k6: string, - cb: ComputedPropertyCallback - ): ComputedProperty; - ( - k1: string, - k2: string, - k3: string, - k4: string, - k5: string, - k6: string, - k7: string, - ...rest: any[] - ): ComputedProperty; +declare namespace computed { + const empty: typeof ComputedNamespace.empty; + const notEmpty: typeof ComputedNamespace.notEmpty; + const none: typeof ComputedNamespace.none; + const not: typeof ComputedNamespace.not; + const bool: typeof ComputedNamespace.bool; + const match: typeof ComputedNamespace.match; + const equal: typeof ComputedNamespace.equal; + const gt: typeof ComputedNamespace.gt; + const gte: typeof ComputedNamespace.gte; + const lt: typeof ComputedNamespace.lt; + const lte: typeof ComputedNamespace.lte; + const and: typeof ComputedNamespace.and; + const or: typeof ComputedNamespace.or; + const alias: typeof ComputedNamespace.alias; + const oneWay: typeof ComputedNamespace.oneWay; + const reads: typeof ComputedNamespace.reads; + const readOnly: typeof ComputedNamespace.readOnly; + const deprecatingAlias: typeof ComputedNamespace.deprecatingAlias; + const sum: typeof ComputedNamespace.sum; + const max: typeof ComputedNamespace.max; + const min: typeof ComputedNamespace.min; + const map: typeof ComputedNamespace.map; + const mapBy: typeof ComputedNamespace.mapBy; + const filter: typeof ComputedNamespace.filter; + const filterBy: typeof ComputedNamespace.filterBy; + const uniq: typeof ComputedNamespace.uniq; + const uniqBy: typeof ComputedNamespace.uniqBy; + const union: typeof ComputedNamespace.union; + const intersect: typeof ComputedNamespace.intersect; + const setDiff: typeof ComputedNamespace.setDiff; + const collect: typeof ComputedNamespace.collect; + const sort: typeof ComputedNamespace.sort; +} - /** - * A computed property that returns true if the value of the dependent - * property is null, an empty string, empty array, or empty function. - */ - empty(dependentKey: string): ComputedProperty; - /** - * A computed property that returns true if the value of the dependent - * property is NOT null, an empty string, empty array, or empty function. - */ - notEmpty(dependentKey: string): ComputedProperty; - /** - * A computed property that returns true if the value of the dependent - * property is null or undefined. This avoids errors from JSLint complaining - * about use of ==, which can be technically confusing. - */ - none(dependentKey: string): ComputedProperty; - /** - * A computed property that returns the inverse boolean value - * of the original value for the dependent property. - */ - not(dependentKey: string): ComputedProperty; - /** - * A computed property that converts the provided dependent property - * into a boolean value. - */ - bool(dependentKey: string): ComputedProperty; - /** - * A computed property which matches the original value for the - * dependent property against a given RegExp, returning `true` - * if the value matches the RegExp and `false` if it does not. - */ - match(dependentKey: string, regexp: RegExp): ComputedProperty; - /** - * A computed property that returns true if the provided dependent property - * is equal to the given value. - */ - equal(dependentKey: string, value: any): ComputedProperty; - /** - * A computed property that returns true if the provided dependent property - * is greater than the provided value. - */ - gt(dependentKey: string, value: number): ComputedProperty; - /** - * A computed property that returns true if the provided dependent property - * is greater than or equal to the provided value. - */ - gte(dependentKey: string, value: number): ComputedProperty; - /** - * A computed property that returns true if the provided dependent property - * is less than the provided value. - */ - lt(dependentKey: string, value: number): ComputedProperty; - /** - * A computed property that returns true if the provided dependent property - * is less than or equal to the provided value. - */ - lte(dependentKey: string, value: number): ComputedProperty; - /** - * A computed property that performs a logical `and` on the - * original values for the provided dependent properties. - */ - and(...dependentKeys: string[]): ComputedProperty; - /** - * A computed property which performs a logical `or` on the - * original values for the provided dependent properties. - */ - or(...dependentKeys: string[]): ComputedProperty; - /** - * Creates a new property that is an alias for another property - * on an object. Calls to `get` or `set` this property behave as - * though they were called on the original property. - */ - alias(dependentKey: string): ComputedProperty; - /** - * Where `computed.alias` aliases `get` and `set`, and allows for bidirectional - * data flow, `computed.oneWay` only provides an aliased `get`. The `set` will - * not mutate the upstream property, rather causes the current property to - * become the value set. This causes the downstream property to permanently - * diverge from the upstream property. - */ - oneWay(dependentKey: string): ComputedProperty; - /** - * This is a more semantically meaningful alias of `computed.oneWay`, - * whose name is somewhat ambiguous as to which direction the data flows. - */ - reads(dependentKey: string): ComputedProperty; - /** - * Where `computed.oneWay` provides oneWay bindings, `computed.readOnly` provides - * a readOnly one way binding. Very often when using `computed.oneWay` one does - * not also want changes to propagate back up, as they will replace the value. - */ - readOnly(dependentKey: string): ComputedProperty; - /** - * Creates a new property that is an alias for another property - * on an object. Calls to `get` or `set` this property behave as - * though they were called on the original property, but also - * print a deprecation warning. - */ - deprecatingAlias( - dependentKey: string, - options: { id: string; until: string } - ): ComputedProperty; - /** - * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-function-options - */ - deprecatingAlias( - dependentKey: string, - options?: { id?: string; until?: string } - ): ComputedProperty; - /** - * A computed property that returns the sum of the values - * in the dependent array. - */ - sum(dependentKey: string): ComputedProperty; - /** - * A computed property that calculates the maximum value in the - * dependent array. This will return `-Infinity` when the dependent - * array is empty. - */ - max(dependentKey: string): ComputedProperty; - /** - * A computed property that calculates the minimum value in the - * dependent array. This will return `Infinity` when the dependent - * array is empty. - */ - min(dependentKey: string): ComputedProperty; - /** - * Returns an array mapped via the callback - */ - map( - dependentKey: string, - callback: (value: any, index: number, array: any[]) => U - ): ComputedProperty; - /** - * Returns an array mapped to the specified key. - */ - mapBy(dependentKey: string, propertyKey: string): ComputedProperty; - /** - * Filters the array by the callback. - */ - filter( - dependentKey: string, - callback: (value: any, index: number, array: any[]) => boolean - ): ComputedProperty; - /** - * Filters the array by the property and value - */ - filterBy( - dependentKey: string, - propertyKey: string, - value?: any - ): ComputedProperty; - /** - * A computed property which returns a new array with all the unique - * elements from one or more dependent arrays. - */ - uniq(propertyKey: string): ComputedProperty; - /** - * A computed property which returns a new array with all the unique - * elements from an array, with uniqueness determined by specific key. - */ - uniqBy(dependentKey: string, propertyKey: string): ComputedProperty; - /** - * A computed property which returns a new array with all the unique - * elements from one or more dependent arrays. - */ - union(...propertyKeys: string[]): ComputedProperty; - /** - * A computed property which returns a new array with all the elements - * two or more dependent arrays have in common. - */ - intersect(...propertyKeys: string[]): ComputedProperty; - /** - * A computed property which returns a new array with all the - * properties from the first dependent array that are not in the second - * dependent array. - */ - setDiff( - setAProperty: string, - setBProperty: string - ): ComputedProperty; - /** - * A computed property that returns the array of values - * for the provided dependent properties. - */ - collect(...dependentKeys: string[]): ComputedProperty; - /** - * A computed property which returns a new array with all the - * properties from the first dependent array sorted based on a property - * or sort function. - */ - sort( - itemsKey: string, - sortDefinition: string | ((itemA: any, itemB: any) => number) - ): ComputedProperty; -}; +export { computed }; /** * Specify a method that observes property changes. */ @@ -387,7 +232,9 @@ export function defineProperty( export function notifyPropertyChange(obj: object, keyName: string): void; -declare module '@ember/utils/-private/types' { +export const action: MethodDecorator; + +declare module "@ember/utils/-private/types" { interface TypeLookup { class: typeof EmberObject; instance: EmberObject; diff --git a/types/ember__object/test/octane.ts b/types/ember__object/test/octane.ts new file mode 100644 index 0000000000..d475cab777 --- /dev/null +++ b/types/ember__object/test/octane.ts @@ -0,0 +1,217 @@ +import { action, computed, default as EmberObject } from "@ember/object"; +import { + alias, + and, + bool, + collect, + deprecatingAlias, + empty, + equal, + filter, + filterBy, + gt, + gte, + intersect, + lt, + lte, + map, + mapBy, + match, + max, + min, + none, + not, + notEmpty, + oneWay, + or, + readOnly, + reads, + setDiff, + sort, + sum, + union, + uniq, + uniqBy +} from "@ember/object/computed"; + +// Native class syntax +class Foo extends EmberObject { + firstName: string; + lastName: string; + + @action // $ExpectError + bar: string; + + @computed("firstName", "lastName") + get fullName() { + return `${this.firstName} ${this.lastName}`; + } + + @action + foo() {} +} + +// Computed property macros + +class Bar extends EmberObject { + firstName: string; + last: string; + + values: number[]; + + @alias aliasTest0: string; // $ExpectError + @alias() aliasTest1: string; // $ExpectError + @alias("firstName") aliasTest2: string; + + @and andTest0: boolean; // $ExpectError + @and() andTest1: boolean; + @and("firstName") andTest2: boolean; + @and("firstName", "lastName") andTest3: boolean; + + @bool boolTest0: boolean; // $ExpectError + @bool() boolTest1: boolean; // $ExpectError + @bool("firstName") boolTest2: boolean; + + @collect collectTest0: any; // $ExpectError + @collect() collectTest1: any; + @collect("firstName") collectTest2: any; + + @deprecatingAlias deprecatingAliasTest0: string; // $ExpectError + @deprecatingAlias() deprecatingAliasTest1: string; // $ExpectError + @deprecatingAlias("firstName") deprecatingAliasTest2: string; + + @empty emptyTest0: boolean; // $ExpectError + @empty() emptyTest1: boolean; // $ExpectError + @empty("firstName") emptyTest2: boolean; + + @equal equalTest0: boolean; // $ExpectError + @equal() equalTest1: boolean; // $ExpectError + @equal("firstName") equalTest2: boolean; // $ExpectError + @equal("firstName", "lastName") equalTest3: boolean; + + @filter filterTest1: string[]; // $ExpectError + @filter() filterTest2: string[]; // $ExpectError + @filter("firstName") filterTest3: string[]; // $ExpectError + @filter("firstName", x => x) filterTest4: string[]; + + @filterBy filterByTest1: any[]; // $ExpectError + @filterBy() filterByTest2: any[]; // $ExpectError + @filterBy("firstName") filterByTest3: any[]; // $ExpectError + @filterBy("firstName", "id") filterByTest4: any[]; + + @gt gtTest1: boolean; // $ExpectError + @gt() gtTest2: boolean; // $ExpectError + @gt("firstName") gtTest3: boolean; // $ExpectError + @gt("firstName", 3) gtTest4: boolean; + + @gte gteTest1: boolean; // $ExpectError + @gte() gteTest2: boolean; // $ExpectError + @gte("firstName") gteTest3: boolean; // $ExpectError + @gte("firstName", 3) gteTest4: boolean; + + @intersect intersectTest1: any; // $ExpectError + @intersect() intersectTest2: any; + @intersect("firstName") intersectTest3: any; + @intersect("firstName", "lastName") intersectTest4: any; + + @lt ltTest1: boolean; // $ExpectError + @lt() ltTest2: boolean; // $ExpectError + @lt("firstName") ltTest3: boolean; // $ExpectError + @lt("firstName", 3) ltTest4: boolean; + + @lte lteTest1: boolean; // $ExpectError + @lte() lteTest2: boolean; // $ExpectError + @lte("firstName") lteTest3: boolean; // $ExpectError + @lte("firstName", 3) lteTest4: boolean; + + @map mapTest1: string[]; // $ExpectError + @map() mapTest2: string[]; // $ExpectError + @map("firstName") mapTest3: string[]; // $ExpectError + @map("firstName", x => x) mapTest4: string[]; + + @mapBy mapByTest1: any[]; // $ExpectError + @mapBy() mapByTest2: any[]; // $ExpectError + @mapBy("firstName") mapByTest3: any[]; // $ExpectError + @mapBy("firstName", "id") mapByTest4: any[]; + + @match matchTest1: boolean; // $ExpectError + @match() matchTest2: boolean; // $ExpectError + @match("firstName") matchTest3: boolean; // $ExpectError + @match("firstName", "abc") matchTest4: boolean; // $ExpectError + @match("firstName", /\s+/) matchTest5: boolean; + + @max maxTest1: number; // $ExpectError + @max() maxTest2: number; // $ExpectError + @max("values") maxTest3: number; + @max("values", "a") maxTest4: number; // $ExpectError + + @min minTest1: number; // $ExpectError + @min() minTest2: number; // $ExpectError + @min("values") minTest3: number; + @min("values", "a") minTest4: number; // $ExpectError + + @none noneTest1: number; // $ExpectError + @none() noneTest2: number; // $ExpectError + @none("values") noneTest3: number; + @none("values", "a") noneTest4: number; // $ExpectError + + @not notTest1: number; // $ExpectError + @not() notTest2: number; // $ExpectError + @not("values") notTest3: number; + @not("values", "a") notTest4: number; // $ExpectError + + @notEmpty notEmptyTest1: boolean; // $ExpectError + @notEmpty() notEmptyTest2: boolean; // $ExpectError + @notEmpty("firstName") notEmptyTest3: boolean; + @notEmpty("firstName", "a") notEmptyTest4: boolean; // $ExpectError + + @oneWay oneWayTest1: boolean; // $ExpectError + @oneWay() oneWayTest2: boolean; // $ExpectError + @oneWay("firstName") oneWayTest3: boolean; + @oneWay("firstName", "b") oneWayTest4: boolean; // $ExpectError + + @or orTest1: boolean; // $ExpectError + @or() orTest2: boolean; + @or("firstName") orTest3: boolean; + @or("firstName", "lastName") orTest4: boolean; + + @readOnly readOnlyTest1: boolean; // $ExpectError + @readOnly() readOnlyTest2: boolean; // $ExpectError + @readOnly("firstName") readOnlyTest3: boolean; + + @reads readsTest1: boolean; // $ExpectError + @reads() readsTest2: boolean; // $ExpectError + @reads("firstName") readsTest3: boolean; + @reads("firstName", "a") readsTest4: boolean; // $ExpectError + + @setDiff setDiffTest1: number; // $ExpectError + @setDiff() setDiffTest2: number; // $ExpectError + @setDiff("values") setDiffTest3: number; // $ExpectError + @setDiff("values", "otherThing") setDiffTest4: number; + @setDiff("values", "otherThing", "a") setDiffTest5: number; // $ExpectError + + @sort sortTest1: number; // $ExpectError + @sort() sortTest2: number; // $ExpectError + @sort("values") sortTest3: number; // $ExpectError + @sort("values", "id") sortTest4: number; + @sort("values", "id", "a") sortTest5: number; // $ExpectError + @sort("values", (a, b) => a - b) sortTest6: number; + + @sum sumTest1: number; // $ExpectError + @sum() sumTest2: number; // $ExpectError + @sum("values") sumTest3: number; + + @union unionTest1: any; // $ExpectError + @union() unionTest2: any; + @union("firstName") unionTest3: any; + @union("firstName", "lastName") unionTest4: any; + + @uniq uniqTest1: number; // $ExpectError + @uniq() uniqTest2: number; // $ExpectError + @uniq("values") uniqTest3: number; + + @uniqBy uniqByTest1: number; // $ExpectError + @uniqBy() uniqByTest2: number; // $ExpectError + @uniqBy("values") uniqByTest3: number; // $ExpectError + @uniqBy("values", "id") uniqByTest4: number; +} diff --git a/types/ember__object/tsconfig.json b/types/ember__object/tsconfig.json index deeb128e7b..5f6af3fbda 100644 --- a/types/ember__object/tsconfig.json +++ b/types/ember__object/tsconfig.json @@ -11,6 +11,7 @@ "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", + "experimentalDecorators": true, "typeRoots": [ "../" ], @@ -49,6 +50,7 @@ "test/extend.ts", "test/object.ts", "test/observable.ts", + "test/octane.ts", "test/proxy.ts", "test/reopen.ts" ] diff --git a/types/ember__service/ember__service-tests.ts b/types/ember__service/ember__service-tests.ts deleted file mode 100644 index ee2e39823c..0000000000 --- a/types/ember__service/ember__service-tests.ts +++ /dev/null @@ -1,38 +0,0 @@ -import Service, { inject } from "@ember/service"; -import EmberObject from "@ember/object"; - -class FirstSvc extends Service { - foo = 'bar'; - first() { return ''; } -} -const SecondSvc = Service.extend({ - foo: 'bar', - second() { return ''; } -}); - -class ThirdSvc extends Service.extend({ - foo: 'bar', - third() { return ''; } -}) { } - -declare module '@ember/service' { - interface Registry { - first: FirstSvc; - second: InstanceType; - third: ThirdSvc; - } -} - -const ServiceTriplet = EmberObject.extend({ - sFirst: inject('first'), - sSecond: inject('second'), - sThird: inject('third'), - unknownService: inject() -}); - -const obj = ServiceTriplet.create(); - -obj.get('sFirst'); // $ExpectType FirstSvc -obj.get('sSecond').second(); // $ExpectType "" -obj.get('sThird'); // $ExpectType ThirdSvc -obj.get('unknownService'); // $ExpectType Service diff --git a/types/ember__service/index.d.ts b/types/ember__service/index.d.ts index 45918f4bbb..416d705940 100644 --- a/types/ember__service/index.d.ts +++ b/types/ember__service/index.d.ts @@ -12,10 +12,9 @@ export default class Service extends EmberObject {} * Creates a property that lazily looks up a service in the container. There * are no restrictions as to what objects a service can be injected into. */ -export function inject(): ComputedProperty; -export function inject( - name: K -): ComputedProperty; +export function inject(): PropertyDecorator & ComputedProperty; // @inject() foo, foo: inject() +export function inject(target: object, propertyKey: string | symbol): void; // @inject foo +export function inject(name: K): PropertyDecorator & ComputedProperty; // @inject('store') foo @inject() foo // A type registry for Ember `Service`s. Meant to be declaration-merged so // string lookups resolve to the correct type. diff --git a/types/ember__service/test/main.ts b/types/ember__service/test/main.ts new file mode 100644 index 0000000000..862f499b89 --- /dev/null +++ b/types/ember__service/test/main.ts @@ -0,0 +1,44 @@ +import Service, { inject } from "@ember/service"; +import EmberObject from "@ember/object"; + +class FirstSvc extends Service { + foo = "bar"; + first() { + return ""; + } +} +const SecondSvc = Service.extend({ + foo: "bar", + second() { + return ""; + } +}); + +class ThirdSvc extends Service.extend({ + foo: "bar", + third() { + return ""; + } +}) {} + +declare module "@ember/service" { + interface Registry { + first: FirstSvc; + second: InstanceType; + third: ThirdSvc; + } +} + +const ServiceTriplet = EmberObject.extend({ + sFirst: inject("first"), + sSecond: inject("second"), + sThird: inject("third"), + unknownService: inject() +}); + +const obj = ServiceTriplet.create(); + +obj.get("sFirst"); // $ExpectType FirstSvc +obj.get("sSecond").second(); // $ExpectType "" +obj.get("sThird"); // $ExpectType ThirdSvc +obj.get("unknownService"); // $ExpectType Service diff --git a/types/ember__service/test/octane.ts b/types/ember__service/test/octane.ts new file mode 100644 index 0000000000..c6971e98e4 --- /dev/null +++ b/types/ember__service/test/octane.ts @@ -0,0 +1,28 @@ +import Service, { inject } from "@ember/service"; +import EmberObject from "@ember/object"; + +class FirstSvc extends Service { + foo = "bar"; + first() { + return ""; + } +} +const SecondSvc = Service.extend({ + foo: "bar", + second() { + return ""; + } +}); + +declare module "@ember/service" { + interface Registry { + first: FirstSvc; + second: InstanceType; + } +} + +class Foo extends EmberObject { + @inject foo: FirstSvc; + @inject("first") baz: FirstSvc; + @inject() bar: FirstSvc; +} diff --git a/types/ember__service/tsconfig.json b/types/ember__service/tsconfig.json index f1cfe16ca1..1df951cc8a 100644 --- a/types/ember__service/tsconfig.json +++ b/types/ember__service/tsconfig.json @@ -10,6 +10,7 @@ "noImplicitThis": true, "strictNullChecks": true, "strictFunctionTypes": true, + "experimentalDecorators": true, "baseUrl": "../", "typeRoots": [ "../" @@ -25,6 +26,7 @@ }, "files": [ "index.d.ts", - "ember__service-tests.ts" + "test/main.ts", + "test/octane.ts" ] } diff --git a/types/express-serve-static-core/index.d.ts b/types/express-serve-static-core/index.d.ts index 773a1e065b..a6ec840ff4 100644 --- a/types/express-serve-static-core/index.d.ts +++ b/types/express-serve-static-core/index.d.ts @@ -507,8 +507,7 @@ export interface Response extends http.ServerResponse, Express.Response { * res.send(new Buffer('wahoo')); * res.send({ some: 'json' }); * res.send('

some html

'); - * res.send(404, 'Sorry, cant find that'); - * res.send(404); + * res.status(404).send('Sorry, cant find that'); */ send: Send; @@ -519,8 +518,8 @@ export interface Response extends http.ServerResponse, Express.Response { * * res.json(null); * res.json({ user: 'tj' }); - * res.json(500, 'oh noes!'); - * res.json(404, 'I dont have that'); + * res.status(500).json('oh noes!'); + * res.status(404).json('I dont have that'); */ json: Send; @@ -531,8 +530,8 @@ export interface Response extends http.ServerResponse, Express.Response { * * res.jsonp(null); * res.jsonp({ user: 'tj' }); - * res.jsonp(500, 'oh noes!'); - * res.jsonp(404, 'I dont have that'); + * res.status(500).jsonp('oh noes!'); + * res.status(404).jsonp('I dont have that'); */ jsonp: Send; diff --git a/types/fabric/fabric-impl.d.ts b/types/fabric/fabric-impl.d.ts index 4e7fec0258..5b2a7c13af 100644 --- a/types/fabric/fabric-impl.d.ts +++ b/types/fabric/fabric-impl.d.ts @@ -2144,12 +2144,6 @@ export class ActiveSelection { * active object. no events fired. */ toGroup(): Group; - /** - * If returns true, deselection is cancelled. - * @since 2.0.0 - * @return {Boolean} [cancel] - */ - onDeselect(): boolean; /** * Returns {@link fabric.ActiveSelection} instance from an object representation * @memberOf fabric.ActiveSelection @@ -3500,8 +3494,9 @@ export class Object { /** * This callback function is called every time _discardActiveObject or _setActiveObject * try to to deselect this object. If the function returns true, the process is cancelled + * @return {Boolean} true to cancel selection */ - onDeselect(): void; + onDeselect(options: { e?: Event, object?: Object }): boolean; /** * This callback function is called every time _discardActiveObject or _setActiveObject * try to to select this object. If the function returns true, the process is cancelled @@ -4137,7 +4132,6 @@ export class IText extends Text { * Initializes all the interactive behavior of IText */ initBehavior(): void; - onDeselect(): void; /** * Initializes "added" event handler */ diff --git a/types/filenamify-url/filenamify-url-tests.ts b/types/filenamify-url/filenamify-url-tests.ts deleted file mode 100644 index 2a575c9267..0000000000 --- a/types/filenamify-url/filenamify-url-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import filenamifyUrl = require("filenamify-url"); - -filenamifyUrl("http://sindresorhus.com/foo?bar=baz"); - -filenamifyUrl("http://sindresorhus.com/foo", { replacement: "🐴" }); - -filenamifyUrl.path("https://sindresorhus.com"); diff --git a/types/filenamify-url/index.d.ts b/types/filenamify-url/index.d.ts deleted file mode 100644 index 24dc581717..0000000000 --- a/types/filenamify-url/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -// Type definitions for filenamify-url 1.0 -// Project: https://github.com/sindresorhus/filenamify-url -// Definitions by: Carlos Precioso -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -import * as filenamifyUrl from "filenamify"; -export = filenamifyUrl; diff --git a/types/filenamify/filenamify-tests.ts b/types/filenamify/filenamify-tests.ts deleted file mode 100644 index 54c92cdd87..0000000000 --- a/types/filenamify/filenamify-tests.ts +++ /dev/null @@ -1,10 +0,0 @@ -import filenamify = require('filenamify'); - -filenamify(''); -// => 'foo!bar' - -filenamify('foo:"bar"', {replacement: '🐴'}); -// => 'foo🐴bar' - -filenamify.path('/some/!path'); -// => '/some/path' diff --git a/types/filenamify/index.d.ts b/types/filenamify/index.d.ts deleted file mode 100644 index 99eb7f89f7..0000000000 --- a/types/filenamify/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for filenamify 2.0 -// Project: https://github.com/sindresorhus/filenamify -// Definitions by: Junyoung Choi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function filenamify(input: string, options?: filenamify.Options): string; - -declare namespace filenamify { - interface Options { - replacement: string; - } - function path(input: string, options?: Options): string; -} - -export = filenamify; diff --git a/types/fkill/fkill-tests.ts b/types/fkill/fkill-tests.ts deleted file mode 100644 index 6e2b380a16..0000000000 --- a/types/fkill/fkill-tests.ts +++ /dev/null @@ -1,5 +0,0 @@ -import fkill = require('fkill'); - -fkill(1337); // $ExpectType Promise -fkill('Safari'); // $ExpectType Promise -fkill([1337, 'Safari', ':8080']); // $ExpectType Promise diff --git a/types/fkill/index.d.ts b/types/fkill/index.d.ts deleted file mode 100644 index 4b6663a10c..0000000000 --- a/types/fkill/index.d.ts +++ /dev/null @@ -1,40 +0,0 @@ -// Type definitions for fkill 5.3 -// Project: https://github.com/sindresorhus/fkill#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = fkill; - -/** - * Fabulously kill processes. Cross-platform. - * - * @param input One or more process IDs/names/ports to kill. - * To kill a port, prefix it with a colon. For example: `:8080`. - */ -declare function fkill( - input: number | string | Array, - options?: fkill.Options -): Promise; - -declare namespace fkill { - interface Options { - /** - * Force kill the process. - * @default false - */ - force?: boolean; - - /** - * Kill all child processes along with the parent process. *(Windows only)* - * @default true - */ - tree?: boolean; - - /** - * Ignore capitalization when killing a process. - * Note that the case is always ignored on Windows. - * @default false - */ - ignoreCase?: boolean; - } -} diff --git a/types/get-res/get-res-tests.ts b/types/get-res/get-res-tests.ts index d767a6d054..ccb060b0d6 100644 --- a/types/get-res/get-res-tests.ts +++ b/types/get-res/get-res-tests.ts @@ -1,3 +1,3 @@ import getRes = require('get-res'); -getRes(); // $ExpectType Promise +getRes(); // $ExpectType Promise diff --git a/types/get-res/index.d.ts b/types/get-res/index.d.ts index 36fb22d94c..223d451910 100644 --- a/types/get-res/index.d.ts +++ b/types/get-res/index.d.ts @@ -6,9 +6,14 @@ export = getRes; +interface Resolution { + item: string; + percent: string; +} + /** * Get ten most popular screen resolutions * * @returns An array with the details of ten most popular screen resolutions */ -declare function getRes(): Promise; +declare function getRes(): Promise; diff --git a/types/get-stream/get-stream-tests.ts b/types/get-stream/get-stream-tests.ts deleted file mode 100644 index 065c0a3c97..0000000000 --- a/types/get-stream/get-stream-tests.ts +++ /dev/null @@ -1,12 +0,0 @@ -import getStream = require("get-stream"); - -import * as fs from 'fs'; - -getStream(fs.createReadStream('foo')) - .then(str => str.toLowerCase()); - -getStream.array(fs.createReadStream('foo')) - .then(values => values.join(', ')); - -getStream.buffer(fs.createReadStream('foo')) - .then(buffer => buffer.byteLength); diff --git a/types/get-stream/index.d.ts b/types/get-stream/index.d.ts deleted file mode 100644 index 19c7c6067b..0000000000 --- a/types/get-stream/index.d.ts +++ /dev/null @@ -1,62 +0,0 @@ -// Type definitions for get-stream 3.0 -// Project: https://github.com/sindresorhus/get-stream#readme -// Definitions by: Douglas Duteil -// BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// - -import { Stream } from 'stream'; - -interface Options { - /** - * Encoding of the incoming stream. - * @default 'utf8' - */ - encoding?: BufferEncoding | 'buffer'; - /** - * Maximum length of the returned string. If it exceeds this value before - * the stream ends, the promise will be rejected. - * @default Infinity - */ - maxBuffer?: number; -} - -/** - * Get the stream as a string. - * The methods returns a promise that resolves when the end event fires on the - * stream, indicating that there is no more data to be read. - * The stream is switched to flowing mode. - */ -declare function getStream(stream: Stream, options?: Options): Promise; -declare namespace getStream { - /** - * Get the `stream` as an array of values. - * - * It honors both the `maxBuffer` and `encoding` options. - * The behavior changes slightly based on the encoding chosen: - * - * - When `encoding` is unset, it assumes an [object mode stream](https://nodesource.com/blog/understanding-object-streams/) - * and collects values emitted from `stream` unmodified. - * In this case `maxBuffer` refers to the number of items in the array - * (not the sum of their sizes). - * - * - When `encoding` is set to `buffer`, it collects an array of buffers. - * `maxBuffer` refers to the summed byte lengths of every buffer in the array. - * - * - When `encoding` is set to anything else, it collects an array of strings. - * `maxBuffer` refers to the summed character lengths of every string in the array. - * - */ - function array(stream: Stream, options?: Options): Promise; - - /** - * Get the stream as a buffer. - * - * It honors the maxBuffer option as above, but it refers to byte length - * rather than string length. - */ - function buffer(stream: Stream, options?: Options): Promise; -} - -export = getStream; diff --git a/types/get-stream/tsconfig.json b/types/get-stream/tsconfig.json deleted file mode 100644 index 7d3b35d42d..0000000000 --- a/types/get-stream/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "get-stream-tests.ts" - ] -} \ No newline at end of file diff --git a/types/get-stream/tslint.json b/types/get-stream/tslint.json deleted file mode 100644 index 71ee04c4e1..0000000000 --- a/types/get-stream/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-unnecessary-generics": false - } -} diff --git a/types/gravatar/gravatar-tests.ts b/types/gravatar/gravatar-tests.ts index f9a26bc561..9fa79a2d40 100644 --- a/types/gravatar/gravatar-tests.ts +++ b/types/gravatar/gravatar-tests.ts @@ -12,3 +12,5 @@ gravatar.url("email@example.com", { s: "200", r: "pg", default: "404" }, false); gravatar.url("email@example.com", { d: "404" }, false); gravatar.url("email@example.com", { forcedefault: "y" }, false); gravatar.url("email@example.com", { f: "y" }); +gravatar.url("email@example.com", { protocol: "https" }); +gravatar.url("email@example.com", { format: "xml" }); diff --git a/types/gravatar/index.d.ts b/types/gravatar/index.d.ts index 5c2c113ab8..161ba459af 100644 --- a/types/gravatar/index.d.ts +++ b/types/gravatar/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for gravatar v1.4.0 +// Type definitions for gravatar v1.8.0 // Project: https://github.com/emerleite/node-gravatar // Definitions by: Denis Sokolov // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped @@ -9,6 +9,8 @@ declare namespace GravatarModule { default?: string f?: string forcedefault?: string + format?: string + protocol?: string r?: string rating?: string s?: string diff --git a/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts index 155bb928e3..4df23a6955 100644 --- a/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts +++ b/types/hapi-auth-cookie/hapi-auth-cookie-tests.ts @@ -8,15 +8,17 @@ server.register({ }); const options: auth.Options = { - clearInvalid: true, - cookie: 'session', - domain: '.typescript.org', + cookie: { + clearInvalid: true, + name: 'session', + domain: '.typescript.org', + password: 'abcdef', + isSecure: true, + ttl: 259200000, + }, keepAlive: true, - password: 'abcdef', redirectTo: '/login', - isSecure: true, appendNext: false, - ttl: 259200000, validateFunc: async () => { return { valid: true }; }, diff --git a/types/hapi-auth-cookie/index.d.ts b/types/hapi-auth-cookie/index.d.ts index 8184ffd2fe..bcae2b3bdc 100644 --- a/types/hapi-auth-cookie/index.d.ts +++ b/types/hapi-auth-cookie/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for hapi-auth-cookie 9.1 +// Type definitions for hapi-auth-cookie 10.0 // Project: https://github.com/hapijs/hapi-auth-cookie // Definitions by: Silas Rech // Simon Schick @@ -32,51 +32,18 @@ declare module 'hapi' { declare namespace hapiAuthCookie { interface ValidateResponse { valid: boolean; credentials?: AuthCredentials; } type ValidateFunction = (request?: Request, session?: object) => Promise; - type RedirectToFunction = (request?: Request) => void; + type RedirectToFunction = (request?: Request) => string; /** * Options passed to 'hapi.auth.strategy' when this plugin is used */ interface Options { /** - * The cookie name. + * Cookie options. * - * @default 'sid' + * @default { name: 'sid', clearInvalid: false, isSameSite: 'Strict', isSecure: true, isHttpOnly: true } */ - cookie?: string; - - /** - * Used for Iron cookie encoding. - * Should be at least 32 characters long. - */ - password: string; - - /** - * Sets the cookie expires time in milliseconds. - * Required when 'keepAlive' is true. - * Defaults to single browser session (ends when browser closes). - */ - ttl?: number; - - /** - * Sets the cookie Domain value. - * Defaults to none. - */ - domain?: string; - - /** - * Sets the cookie path value. - * - * @default '/' - */ - path?: string; - - /** - * Any authentication cookie that fails validation will be marked as expired in the response and cleared. - * - * @default false - */ - clearInvalid?: boolean; + cookie?: ServerStateCookieOptions & { name: string }; /** * Automatically sets the session cookie after validation to extend the current session for a new TTL duration. @@ -85,28 +52,6 @@ declare namespace hapiAuthCookie { */ keepAlive?: boolean; - /** - * If false omitted. - * Other options Strict or Lax. - * - * @default 'Strict' - */ - isSameSite?: ServerStateCookieOptions['isSameSite']; - - /** - * If false, the cookie is allowed to be transmitted over insecure connections which exposes it to attacks. - * - * @default true - */ - isSecure?: boolean; - - /** - * If false, the cookie will not include the 'HttpOnly' flag. - * - * @default true - */ - isHttpOnly?: boolean; - /** * Login URI or function that returns a URI to redirect unauthenticated requests to. * Note that it will only trigger when the authentication mode is 'required'. diff --git a/types/has-yarn/has-yarn-tests.ts b/types/has-yarn/has-yarn-tests.ts deleted file mode 100644 index 925cfe3c43..0000000000 --- a/types/has-yarn/has-yarn-tests.ts +++ /dev/null @@ -1,4 +0,0 @@ -import hasYarn = require('has-yarn'); - -// $ExpectType boolean -hasYarn('foo'); diff --git a/types/has-yarn/index.d.ts b/types/has-yarn/index.d.ts deleted file mode 100644 index 378f1ee811..0000000000 --- a/types/has-yarn/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for has-yarn 1.0 -// Project: https://github.com/sindresorhus/has-yarn#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = hasYarn; - -declare function hasYarn(cwd?: string): boolean; diff --git a/types/has-yarn/tsconfig.json b/types/has-yarn/tsconfig.json deleted file mode 100644 index 824092017a..0000000000 --- a/types/has-yarn/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "has-yarn-tests.ts" - ] -} diff --git a/types/hasha/hasha-tests.ts b/types/hasha/hasha-tests.ts deleted file mode 100644 index d0054de81a..0000000000 --- a/types/hasha/hasha-tests.ts +++ /dev/null @@ -1,19 +0,0 @@ -import hasha = require('hasha'); - -let str: string | null; -let buf: Buffer | null; - -str = hasha('unicorn'); -str = hasha('unicorn', {algorithm: 'md5'}); -str = hasha('unicorn', {algorithm: 'md5', encoding: 'latin1'}); -buf = hasha('unicorn', {algorithm: 'md5', encoding: 'buffer'}); - -process.stdin.pipe(hasha.stream()).pipe(process.stdout); - -hasha.fromStream(process.stdin).then(hash => str = hash); -hasha.fromStream(process.stdin, {encoding: 'hex'}).then(hash => str = hash); -hasha.fromStream(process.stdin, {encoding: 'buffer'}).then(hash => buf = hash); - -hasha.fromFile('unicorn.png').then(hash => str = hash); -hasha.fromFile('unicorn.png', {encoding: 'base64'}).then(hash => str = hash); -hasha.fromFile('unicorn.png', {encoding: 'buffer'}).then(hash => buf = hash); diff --git a/types/hasha/index.d.ts b/types/hasha/index.d.ts deleted file mode 100644 index a158af88a3..0000000000 --- a/types/hasha/index.d.ts +++ /dev/null @@ -1,38 +0,0 @@ -// Type definitions for hasha 3.0 -// Project: https://github.com/sindresorhus/hasha -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -/// -import * as crypto from "crypto"; - -export = hasha; - -declare function hasha(input: hasha.HashaInput): string; -declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): string; -declare function hasha(input: hasha.HashaInput, options: hasha.HashaOptions): Buffer; - -declare namespace hasha { - type HashaInput = string | string[] | Buffer | Buffer[]; - type ToStringEncoding = 'hex' | 'base64' | 'latin1' | 'binary' | undefined; - type HashaEncoding = ToStringEncoding | 'buffer'; - - interface HashaOptions { - encoding?: E; - algorithm?: string; - } - - function stream(options?: HashaOptions): crypto.Hash; - - function fromStream(stream: NodeJS.ReadableStream): Promise; - function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; - function fromStream(stream: NodeJS.ReadableStream, options?: HashaOptions): Promise; - - function fromFile(filePath: string): Promise; - function fromFile(filePath: string, options: HashaOptions): Promise; - function fromFile(filePath: string, options: HashaOptions): Promise; - - function fromFileSync(filePath: string): string; - function fromFileSync(filePath: string, options: HashaOptions): string; - function fromFileSync(filePath: string, options: HashaOptions): Buffer; -} diff --git a/types/hasha/tsconfig.json b/types/hasha/tsconfig.json deleted file mode 100644 index fe359d64a5..0000000000 --- a/types/hasha/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "hasha-tests.ts" - ] -} \ No newline at end of file diff --git a/types/hasha/tslint.json b/types/hasha/tslint.json deleted file mode 100644 index 71ee04c4e1..0000000000 --- a/types/hasha/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-unnecessary-generics": false - } -} diff --git a/types/haversine/haversine-tests.ts b/types/haversine/haversine-tests.ts index 5c068ea4b3..de704573f1 100644 --- a/types/haversine/haversine-tests.ts +++ b/types/haversine/haversine-tests.ts @@ -33,6 +33,22 @@ const optionsShort: haversine.Options = { haversine(startShort, endShort, optionsShort); +const startLatLng: haversine.CoordinateLatLng = { + lat: 11.4017529, + lng: 48.1548256, +}; + +const endLatLng: haversine.CoordinateLatLng = { + lat: 13.1445551, + lng: 52.5065133, +}; + +const optionsLatLng: haversine.Options = { + format: '{lat,lng}' +}; + +haversine(startLatLng, endLatLng, optionsLatLng); + const startLatLon: haversine.LatLonTuple = [11.4017529, 48.1548256]; const endLatLon: haversine.LatLonTuple = [13.1445551, 52.5065133]; diff --git a/types/haversine/index.d.ts b/types/haversine/index.d.ts index 91123614b2..bd8e620457 100644 --- a/types/haversine/index.d.ts +++ b/types/haversine/index.d.ts @@ -14,6 +14,11 @@ declare namespace haversine { lat: number; } + interface CoordinateLatLng { + lat: number; + lng: number; + } + type LatLonTuple = [number, number]; interface GeoJSON { @@ -22,7 +27,7 @@ declare namespace haversine { }; } - type Coordinate = (CoordinateLongitudeLatitude | CoordinateLonLat | LatLonTuple | GeoJSON); + type Coordinate = (CoordinateLongitudeLatitude | CoordinateLonLat | CoordinateLatLng | LatLonTuple | GeoJSON); interface Options { /** @@ -36,7 +41,7 @@ declare namespace haversine { /** * Format of coordinate arguments. */ - format?: '[lat,lon]' | '[lon,lat]' | '{lon,lat}' | 'geojson'; + format?: '[lat,lon]' | '[lon,lat]' | '{lon,lat}' | '{lat,lng}' | 'geojson'; } } diff --git a/types/highcharts/index.d.ts b/types/highcharts/index.d.ts index 51028bd6af..b3900154cd 100644 --- a/types/highcharts/index.d.ts +++ b/types/highcharts/index.d.ts @@ -4,6 +4,7 @@ // Dan Lewi Harkestad // Albert Ozimek // Juliën Hanssens +// Johns Gresham // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 @@ -5964,6 +5965,10 @@ declare namespace Highcharts { * Define the visual z index of the series. */ zIndex?: number; + /** + * When using any indicators, Define the indicators name like 'candlesticksss'. + */ + linkedTo?: string; } interface SeriesOptions extends IndividualSeriesOptions, SeriesChart { } @@ -6018,7 +6023,11 @@ declare namespace Highcharts { * The id of a series in the drilldown.series array to use for a drilldown for this point. * @since 3.0.8 */ - drilldown?: string; + drilldown?: string; + /** + * The end value of the point. For gantt datetime axes, the end value is the timestamp in milliseconds since 1970. + */ + end?: number; /** * Individual point events */ @@ -6097,7 +6106,11 @@ declare namespace Highcharts { * Whether to display a slice offset from the center. * @default false */ - sliced?: boolean; + sliced?: boolean; + /** + * The start value of the point. For gantt datetime axes, the start value is the timestamp in milliseconds since 1970. + */ + start?: number; /** * The value of the point, resulting in a relative area of the point in the treemap. */ @@ -7256,7 +7269,11 @@ declare namespace Highcharts { * As Highcharts.Chart, but without need for the new keyword. * @since 4.2.0 */ - chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + chart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; + /** + * Highcharts ganttChart which doesn't require the new keyword. Required Highcharts Gantt module. + */ + ganttChart(renderTo: string | HTMLElement, options: Options, callback?: (chart: ChartObject) => void): ChartObject; /** * An array containing the current chart objects in the page. A chart's position in the array is preserved * throughout the page's lifetime. When a chart is destroyed, the array item becomes undefined. diff --git a/types/highcharts/test/index.ts b/types/highcharts/test/index.ts index 1474ee7e9c..9ac03d1f81 100644 --- a/types/highcharts/test/index.ts +++ b/types/highcharts/test/index.ts @@ -2856,3 +2856,33 @@ function test_WrapTooltipBehavior() { // Many prototype functions use this so arrow functions should only be used to replace behaviors. }); } + +// Tests Highcharts.ganttChart, which usings the Gantt module +function test_GanttChart() { + Highcharts.ganttChart('ganttChartContainer', { + xAxis: { + min: Date.UTC(2014, 9, 18), + max: Date.UTC(2014, 12, 20) + }, + series: [{ + name: 'Project 1', + data: [ + { + name: 'Lemon Tea', + start: Date.UTC(2014, 10, 18), + end: Date.UTC(2014, 11, 20) + }, + { + name: 'Stapler', + start: Date.UTC(2014, 11, 18), + end: Date.UTC(2014, 12, 20) + }, + { + name: 'Sierra', + start: Date.UTC(2014, 12, 18), + end: Date.UTC(2014, 12, 20) + }, + ], + }], + }); +} diff --git a/types/intersects/index.d.ts b/types/intersects/index.d.ts new file mode 100644 index 0000000000..1062b2fc6b --- /dev/null +++ b/types/intersects/index.d.ts @@ -0,0 +1,323 @@ +// Type definitions for intersects 2.5 +// Project: https://github.com/davidfig/intersects#readme +// Definitions by: Voxylu +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export function boxBox( + x1: number, + y1: number, + w1: number, + h1: number, + x2: number, + y2: number, + w2: number, + h2: number +): boolean; + +export function boxCircle( + xb: number, + yb: number, + wb: number, + hb: number, + xc: number, + yc: number, + rc: number +): boolean; + +export function boxEllipse( + xb: number, + yb: number, + wb: number, + hb: number, + xe: number, + ye: number, + rex: number, + rey: number +): boolean; + +export function boxLine( + xb: number, + yb: number, + wb: number, + hb: number, + x1: number, + y1: number, + x2: number, + y2: number +): boolean; + +export function boxPoint( + x1: number, + y1: number, + w1: number, + h1: number, + x2: number, + y2: number +): boolean; + +export function boxPolygon( + xb: number, + yb: number, + wb: number, + hb: number, + points: number[] +): boolean; + +export function circleBox( + xc: number, + yc: number, + rc: number, + xb: number, + yb: number, + wb: number, + hb: number +): boolean; + +export function circleCircle( + x1: number, + y1: number, + r1: number, + x2: number, + y2: number, + r2: number +): boolean; + +export function circleEllipse( + xc: number, + yc: number, + rc: number, + xe: number, + ye: number, + rex: number, + rey: number +): boolean; + +export function circleLine( + xc: number, + yc: number, + rc: number, + x1: number, + y1: number, + x2: number, + y2: number +): boolean; + +export function circlePoint( + x1: number, + y1: number, + r1: number, + x2: number, + y2: number +): boolean; + +export function circlePolygon( + xc: number, + yc: number, + rc: number, + points: number[] +): boolean; + +export function ellipseBox( + xe: number, + ye: number, + rex: number, + rey: number, + xb: number, + yb: number, + wb: number, + hb: number +): boolean; + +export function ellipseCircle( + xe: number, + ye: number, + rex: number, + rey: number, + xc: number, + yc: number, + rc: number +): boolean; + +export function ellipseEllipse( + x1: number, + y1: number, + r1x: number, + r1y: number, + x2: number, + y2: number, + r2x: number, + r2y: number +): boolean; + +export function ellipseLine( + xe: number, + ye: number, + rex: number, + rey: number, + x1: number, + y1: number, + x2: number, + y2: number +): boolean; + +export function ellipsePoint( + xe: number, + ye: number, + rex: number, + rey: number, + x1: number, + y1: number +): boolean; + +export function ellipsePolygon( + xe: number, + ye: number, + rex: number, + rey: number, + points: number[] +): boolean; + +export function lineBox( + x1: number, + y1: number, + x2: number, + y2: number, + xb: number, + yb: number, + wb: number, + hb: number +): boolean; + +export function lineCircle( + x1: number, + y1: number, + x2: number, + y2: number, + xc: number, + yc: number, + rc: number +): boolean; + +export function lineEllipse( + x1: number, + y1: number, + x2: number, + y2: number, + xe: number, + ye: number, + rex: number, + rey: number +): boolean; + +export function lineLine( + x1: number, + y1: number, + x2: number, + y2: number, + x3: number, + y3: number, + x4: number, + y4: number +): boolean; + +export function linePoint( + x1: number, + y1: number, + x2: number, + y2: number, + xp: number, + yp: number, + tolerance: number +): boolean; + +export function linePolygon( + x1: number, + y1: number, + x2: number, + y2: number, + points: number[], + tolerance: number +): boolean; + +export function pointBox( + x1: number, + y1: number, + xb: number, + yb: number, + wb: number, + hb: number +): boolean; + +export function pointCircle( + x1: number, + y1: number, + xc: number, + yc: number, + rc: number +): boolean; + +export function pointEllipse( + x1: number, + y1: number, + xe: number, + ye: number, + rex: number, + rey: number +): boolean; + +export function pointLine( + xp: number, + yp: number, + x1: number, + y1: number, + x2: number, + y2: number +): boolean; + +export function pointPolygon( + x1: number, + y1: number, + points: number[], + tolerance: number +): boolean; + +export function polygonBox( + points: number[], + x: number, + y: number, + w: number, + h: number +): boolean; + +export function polygonCircle( + points: number[], + xc: number, + yc: number, + rc: number +): boolean; + +export function polygonEllipse( + points: number[], + xe: number, + ye: number, + rex: number, + rey: number +): boolean; + +export function polygonLine( + points: number[], + x1: number, + y1: number, + x2: number, + y2: number, + tolerance: number +): boolean; + +export function polygonPoint( + points: number[], + x: number, + y: number, + tolerance: number +): boolean; + +export function polygonPolygon(points1: number[], points2: number[]): boolean; diff --git a/types/intersects/intersects-tests.ts b/types/intersects/intersects-tests.ts new file mode 100644 index 0000000000..e39d8a08ca --- /dev/null +++ b/types/intersects/intersects-tests.ts @@ -0,0 +1,12 @@ +import { polygonBox, pointLine, circleEllipse } from 'intersects'; + +const res = polygonBox([2, 0, 4, 2, 0, 2], 1, 1, 2, 2); +if (res) { + // do something +} + +if (pointLine(0, 8, -5, 4, 7, 6)) { + // do agian something +} + +const isGood = circleEllipse(0, 6, 9, 2, 4, 5, 1) ? 'yes' : 'no'; diff --git a/types/p-memoize/tsconfig.json b/types/intersects/tsconfig.json similarity index 88% rename from types/p-memoize/tsconfig.json rename to types/intersects/tsconfig.json index 0605de1be9..7c8a1b6d87 100644 --- a/types/p-memoize/tsconfig.json +++ b/types/intersects/tsconfig.json @@ -12,5 +12,5 @@ "forceConsistentCasingInFileNames": true, "strictFunctionTypes": true }, - "files": ["index.d.ts", "p-memoize-tests.ts"] + "files": ["index.d.ts", "intersects-tests.ts"] } diff --git a/types/dom-loaded/tslint.json b/types/intersects/tslint.json similarity index 100% rename from types/dom-loaded/tslint.json rename to types/intersects/tslint.json diff --git a/types/into-stream/index.d.ts b/types/into-stream/index.d.ts deleted file mode 100644 index f682ff10a7..0000000000 --- a/types/into-stream/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for into-stream 3.1 -// Project: https://github.com/sindresorhus/into-stream -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -/// - -export = intoStream; - -declare function intoStream(input: intoStream.Input | Promise): NodeJS.ReadableStream; - -declare namespace intoStream { - function obj(input: object | Iterable | Promise>): NodeJS.ReadableStream; - - type Input = Buffer | string | Iterable; -} diff --git a/types/into-stream/into-stream-tests.ts b/types/into-stream/into-stream-tests.ts deleted file mode 100644 index e1f3a9a7b0..0000000000 --- a/types/into-stream/into-stream-tests.ts +++ /dev/null @@ -1,27 +0,0 @@ -import intoStream = require('into-stream'); - -function iterableFrom(arr: any[]) { - return { - *[Symbol.iterator]() { - let i = 0; - while (i < arr.length) { - yield arr[i++]; - } - } - }; -} - -intoStream('unicorn').pipe(process.stdout); -intoStream('unicorn'.split('')).pipe(process.stdout); -intoStream(iterableFrom('unicorn'.split(''))).pipe(process.stdout); -intoStream(new Buffer('unicorn')).pipe(process.stdout); -intoStream(Promise.resolve('unicorn')).pipe(process.stdout); - -const f = {foo: true}; -const f2 = [{foo: true}, {bar: true}]; -intoStream.obj(f).pipe(process.stdout); -intoStream.obj(f2).pipe(process.stdout); -intoStream.obj(iterableFrom(f2)).pipe(process.stdout); -intoStream.obj(Promise.resolve(f)).pipe(process.stdout); -intoStream.obj(Promise.resolve(f2)).pipe(process.stdout); -intoStream.obj(Promise.resolve(iterableFrom(f2))).pipe(process.stdout); diff --git a/types/into-stream/tsconfig.json b/types/into-stream/tsconfig.json deleted file mode 100644 index cc8a2cfa00..0000000000 --- a/types/into-stream/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "into-stream-tests.ts" - ] -} \ No newline at end of file diff --git a/types/into-stream/tslint.json b/types/into-stream/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/into-stream/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/is-scoped/index.d.ts b/types/is-scoped/index.d.ts deleted file mode 100644 index 8c35dcdf9c..0000000000 --- a/types/is-scoped/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for is-scoped 1.0 -// Project: https://github.com/sindresorhus/is-scoped#readme -// Definitions by: Leo Friedrichs -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = isScoped; - -declare function isScoped(input: string): boolean; diff --git a/types/is-scoped/is-scoped-tests.ts b/types/is-scoped/is-scoped-tests.ts deleted file mode 100644 index 9fb34bc3d2..0000000000 --- a/types/is-scoped/is-scoped-tests.ts +++ /dev/null @@ -1,6 +0,0 @@ -import isScoped = require('is-scoped'); - -const tests: boolean[] = [ - isScoped('is-scoped'), - isScoped('@types/is-scoped'), -]; diff --git a/types/is-scoped/tsconfig.json b/types/is-scoped/tsconfig.json deleted file mode 100644 index 2b6374b9f0..0000000000 --- a/types/is-scoped/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "is-scoped-tests.ts" - ] -} \ No newline at end of file diff --git a/types/is-scoped/tslint.json b/types/is-scoped/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/is-scoped/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/jasmine/index.d.ts b/types/jasmine/index.d.ts index 1bc099bcad..56a9f879be 100644 --- a/types/jasmine/index.d.ts +++ b/types/jasmine/index.d.ts @@ -15,7 +15,7 @@ // TypeScript Version: 2.8 // For ddescribe / iit use : https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/karma-jasmine/karma-jasmine.d.ts -type ImplementationCallback = (() => Promise) | ((done: DoneFn) => void); +type ImplementationCallback = (() => PromiseLike) | ((done: DoneFn) => void); /** * Create a group of specs (often called a suite). @@ -134,7 +134,7 @@ declare function expect(): jasmine.NothingMatcher; * @checkReturnValue see https://tsetse.info/check-return-value * @param actual - Actual computed value to test expectations against. */ -declare function expectAsync(actual: Promise): jasmine.AsyncMatchers; +declare function expectAsync(actual: PromiseLike): jasmine.AsyncMatchers; /** * Explicitly mark a spec as failed. @@ -517,25 +517,25 @@ declare namespace jasmine { * Expect a promise to be resolved. * @param expectationFailOutput */ - toBeResolved(expectationFailOutput?: any): Promise; + toBeResolved(expectationFailOutput?: any): PromiseLike; /** * Expect a promise to be rejected. * @param expectationFailOutput */ - toBeRejected(expectationFailOutput?: any): Promise; + toBeRejected(expectationFailOutput?: any): PromiseLike; /** * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. * @param expected - Value that the promise is expected to resolve to. */ - toBeResolvedTo(expected: Expected): Promise; + toBeResolvedTo(expected: Expected): PromiseLike; /** * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. * @param expected - Value that the promise is expected to be rejected with. */ - toBeRejectedWith(expected: Expected): Promise; + toBeRejectedWith(expected: Expected): PromiseLike; /** * Add some context for an expect. diff --git a/types/jasmine/jasmine-tests.ts b/types/jasmine/jasmine-tests.ts index 66b98c4b0d..faa27b3894 100644 --- a/types/jasmine/jasmine-tests.ts +++ b/types/jasmine/jasmine-tests.ts @@ -176,10 +176,8 @@ describe("Included matchers:", () => { it("async matchers", async () => { const badness = new Error("badness"); await expectAsync(Promise.resolve()).toBeResolved(); - await expectAsync(Promise.resolve()).toBeResolved("good job"); await expectAsync(Promise.resolve(true)).toBeResolvedTo(true); await expectAsync(Promise.reject(badness)).toBeRejected(); - await expectAsync(Promise.reject(badness)).toBeRejected("bad mojo"); await expectAsync(Promise.reject(badness)).toBeRejectedWith(badness); await expectAsync(Promise.resolve()).withContext("additional info").toBeResolved(); }); diff --git a/types/jasmine/tslint.json b/types/jasmine/tslint.json index c540ba0129..d2f3f5698c 100644 --- a/types/jasmine/tslint.json +++ b/types/jasmine/tslint.json @@ -8,6 +8,7 @@ "no-unnecessary-generics": false, "no-var-keyword": false, "one-variable-per-declaration": false, - "only-arrow-functions": false + "only-arrow-functions": false, + "await-promise": [true, "PromiseLike"] } } diff --git a/types/kamailio-kemi/index.d.ts b/types/kamailio-kemi/index.d.ts new file mode 100644 index 0000000000..8afd79d533 --- /dev/null +++ b/types/kamailio-kemi/index.d.ts @@ -0,0 +1,1299 @@ +// Type definitions for non-npm package kamailio-kemi 5.3 +// Project: https://github.com/kamailio/kamailio/ +// Definitions by: bonan +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// Types and comments extracted from: +// https://kamailio.org/docs/tutorials/5.3.x/kamailio-kemi-framework/ + +export {}; +declare global { + const KSR: typeof KamailioKemi; +} + +declare namespace KamailioKemi { + // Allowed flags + type Flag = 0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|15|16|17|18|19|20|21|22|23|24|25|26|27|28|29|30|31; + + // Write a log message to DEBUG level + export function dbg(logStr: string): void; + + // Write a log message to ERROR level. + export function err(logStr: string): void; + + // Write a log message to INFO level. + export function info(logStr: string): void; + + // Set the internal flag to add rport parameter to local generated Via header. + export function add_local_rport(): boolean; + + // Adds a tcp port alias for the current connection (if tcp). Useful if you want to send all the trafic to + // port_alias through the same connection this request came from (it could help for firewall or nat traversal). + // When the aliased connection is closed (e.g. it is idle for too much time), all the port aliases are removed. + export function add_tcp_alias(port: number): void; + + // Adds the port from the message via as an alias to TCP connection. See add_tcp_alias(int port) for more details. + export function add_tcp_alias_via(): number; + + // Set the flag for "rport" handling (send the reply based on source address instead of Via header). + export function force_rport(): boolean; + + // Return true if the value of the parameter matches the method type of the SIP message. + export function is_method(method: string): boolean; + + /* + * Return true if SIP method of the currently processed message is matching + * one of the corresponding characters given as parameter. + * Matching the method is done based on corresponding characters: + * + * I - INVITE + * A - ACK + * B - BYE + * C - CANCEL + * R - REGISTER + * M - MESSAGE + * O - OPTIONS + * S - SUBSCRIBE + * P - PUBLISH + * N - NOTIFY + * U - UPDATE + * K - KDMQ + * G - GET + * T - POST + * V - PUT + * D - DELETE + */ + export function is_method_in(method: string): boolean; + + // Helpers for common methods + export function is_INVITE(): boolean; + export function is_ACK(): boolean; + export function is_BYE(): boolean; + export function is_CANCEL(): boolean; + export function is_REGISTER(): boolean; + export function is_MESSAGE(): boolean; + export function is_SUBSCRIBE(): boolean; + export function is_PUBLISH(): boolean; + export function is_NOTIFY(): boolean; + export function is_OPTIONS(): boolean; + export function is_INFO(): boolean; + export function is_UPDATE(): boolean; + export function is_PRACK(): boolean; + + // Return true of the URI address provided as parameter matches a local socket (IP) or local domain. + export function is_myself(uri: string): boolean; + + // Return true if the URI in From header matches a local socket (IP) or local domain. + export function is_myself_furi(): boolean; + + // Return true if the R-URI matches a local socket (IP) or local domain. + export function is_myself_ruri(): boolean; + + // Return true if the URI in To header matches a local socket (IP) or local domain. + export function is_myself_turi(): boolean; + + // Write a log message specifying the level value. + export function log(level: "dbg"|"info"|"warn"|"crit"|"err", msg: string): void; + + // Set the SIP message/transaction flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. + export function setflag(flag: Flag): boolean; + + // Reset the SIP message/transaction flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. + export function resetflag(flag: Flag): boolean; + + // Return true if the message/transaction flag at the index provided by the parameter is set (the bit has value 1). + export function isflagset(flag: Flag): boolean; + + // Set the branch flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. + export function setbflag(flag: Flag): boolean; + + // Reset the branch flag at the index provided by the parameter. The flag parameter has to be a number from 0 to 31. + export function resetbflag(flag: Flag): boolean; + + // Return true if the branch flag at the index provided by the parameter is set (the bit has value 1). + export function isbflagset(flag: Flag): boolean; + + // Set the flag at the index provided by the first parameter to the branch number specified by the second parameter. + // The flag parameter has to be a number from 0 to 31. + // The branch parameter should be between 0 and 12 (a matter of max_branches global parameter). + export function setbiflag(flag: Flag, branch: number): boolean; + + // Reset a branch flag by position and branch index. + export function resetbiflag(flag: Flag, branch: number): boolean; + + // Test if a branch flag is set by position and branch index. + export function isbiflagset(flag: Flag, branch: number): boolean; + + // Set a script flag + export function setsflag(flag: Flag): boolean; + + // Reset a script flag + export function resetsflag(flag: Flag): boolean; + + // Test if a script flag is set + export function issflagset(flag: Flag): boolean; + + // Set request URI + export function seturi(uri: string): boolean; + + // Set request user + export function setuser(usr: string): boolean; + + // Set request host + export function sethost(host: string): boolean; + + // Set destination URI + export function setdsturi(uri: string): boolean; + + // Reset the destination URI (aka: outbound proxy address, dst_uri, $du). + export function resetdsturi(): boolean; + + // Test if destination URI is set. + export function isdsturiset(): boolean; + + // Set the DROP flag, so at the end of KEMI script execution, the SIP request branch or the SIP response is not forwarded. + export function set_drop(): void; + export function set_advertised_address(addr: string): number; + export function set_advertised_port(port: string): number; + export function set_forward_close(): boolean; + export function set_forward_no_connect(): boolean; + export function set_reply_close(): boolean; + export function set_reply_no_connect(): boolean; + + // Forward the SIP request in stateless mode to the address set in destination URI ($du), or, + // if this is not set, to the address in request URI ($ru). + export function forward(): number; + + // Forward the SIP request in stateless mode to the address provided in the SIP URI parameter. + export function forward_uri(uri: string): number; + + // Special declaration of debugger and enum to avoid using reserved words + namespace _debugger { + function dbg_pv_dump(): number; + function dbg_pv_dump_ex(mask: number, level: number): number; + } + + namespace _enum { + function enum_i_query_suffix(vsuffix: string): number; + function enum_pv_query(ve164: string): number; + function enum_pv_query_suffix(ve164: string, vsuffix: string): number; + function enum_pv_query_suffix_service(ve164: string, vsuffix: string, vservice: string): number; + function enum_query(): number; + function enum_query_suffix(vsuffix: string): number; + function enum_query_suffix_service(vsuffix: string, vservice: string): number; + function i_enum_query(): number; + function i_enum_query_suffix_service(vsuffix: string, vservice: string): number; + function is_from_user_enum(): number; + function is_from_user_enum_suffix(vsuffix: string): number; + function is_from_user_enum_suffix_service(vsuffix: string, vservice: string): number; + } + + // noinspection ReservedWordAsName + // TypeScript Version: 2.2 + export { + _debugger as debugger, + _enum as enum + }; + + export namespace pv { + // Return the value of pseudo-variable `pvname`. + // The returned value can be string or integer + function get(pvname: string): string|number|null; + + // Same as get(), but returns empty string on null + function gete(pvname: string): string|number; + + // Same as get(), but returns `vn` on null + function getvn(pvname: string, vn: number): string|number; + + // Return the value of pseudo-variable pvname if it is different than $null or + // the parameter vs if the variable is having the $null value. + function getvs(pvname: string, vn: number): string|number; + + // Return the value of pseudo-variable pvname if it is different than $null or the string <> if the + // variable is having the $null value. This should be used instead of KSR.pv.get(...) in the scripting + // languages that throw and error when attempting to print a NULL (or NIL) value. + function getw(pvname: string): string|number; + + // Set the value of pseudo-variable pvname to integer value provided by parameter val. + function seti(pvname: string, val: number): void; + + // Set the value of pseudo-variable pvname to string value provided by parameter val. + function sets(pvname: string, val: string): void; + + // Set the value of pseudo-variable pvname to $null. + function unset(pvname: string): void; + + // Return true if pseudo-variable pvname is $null. + function is_null(pvname: string): boolean; + } + + export namespace hdr { + // Append header to current SIP message (request or reply). It will be added after the last header. + function append(hdr: string): number; + + // Append header to current SIP message (request or reply). + // It will be added after the first header matching the name hdrName. + function append_after(hdr: string, hdrName: string): number; + + // Insert header to current SIP message (request or reply). + // It will be added before the first header. + function insert(hdr: string): number; + + // Insert header to current SIP message (request or reply). + // It will be added before the header matching the name hdrName. + function insert_before(hdr: string, hdrName: string): number; + + // Remove all the headers with the name hdrName. + function remove(hdrName: string): number; + + // Return greater than 0 if a header with the name hdrName exists and less than 0 if there is no such header. + function is_present(hdrName: string): number; + + // Add a header to the SIP response to be generated by Kamailio for the current SIP request. + function append_to_reply(hdr: string): number; + } + + export namespace x { + // Execute a function (specified by fname) exported by a Kamailio module. Additional parameters must be string + // and they are passed to the Kamailio module function. + function modf(name: string, ...params: string[]): number; + + // Equivalent of exit from native kamailio.cfg scripting language, stop the execution of the SIP routing script. + function exit(): void; + + // Equivalent of drop from native kamailio.cfg scripting language, stop the execution of the SIP routing script + // and drop routing further the SIP request branch or response. + function drop(): void; + } + + export namespace acc { + // Equivalent of native kamailio.cfg function: acc_db_request("comment", "dbtable"). + function acc_db_request(comment: string, dbtable: string): number; + // Equivalent of native kamailio.cfg function: acc_log_request("comment"). + function acc_log_request(comment: string): number; + // Equivalent of native kamailio.cfg function: acc_request("comment", "dbtable"). + function acc_request(comment: string, dbtable: string): number; + } + + export namespace acc_radius { + function request(comment: string): number; + } + + export namespace alias_db { + function lookup(stable: string): number; + function lookup_ex(stable: string, sflags: string): number; + } + + export namespace app_jsdt { + function dofile(script: string): number; + function dostring(script: string): number; + function run(func: string): number; + function run_p1(func: string, p1: string): number; + function run_p2(func: string, p1: string, p2: string): number; + function run_p3(func: string, p1: string, p2: string, p3: string): number; + function runstring(script: string): number; + } + + export namespace app_lua { + function dofile(script: string): number; + function dostring(script: string): number; + function run(func: string): number; + function run_p1(func: string, p1: string): number; + function run_p2(func: string, p1: string, p2: string): number; + function run_p3(func: string, p1: string, p2: string, p3: string): number; + function runstring(script: string): number; + } + + export namespace app_python { + function exec(method: string): number; + function exec_p1(method: string, p1: string): number; + } + + export namespace app_python3 { + function exec(method: string): number; + function exec_p1(method: string, p1: string): number; + } + + export namespace app_ruby { + function run(func: string): number; + function run_p1(func: string, p1: string): number; + function run_p2(func: string, p1: string, p2: string): number; + function run_p3(func: string, p1: string, p2: string, p3: string): number; + } + + export namespace app_sqlang { + function dofile(script: string): number; + function dostring(script: string): number; + function run(func: string): number; + function run_p1(func: string, p1: string): number; + function run_p2(func: string, p1: string, p2: string): number; + function run_p3(func: string, p1: string, p2: string, p3: string): number; + function runstring(script: string): number; + } + + export namespace async { + function route(rn: string, s: number): number; + function task_route(rn: string): number; + } + + export namespace auth { + function auth_challenge(realm: string, flags: number): number; + function consume_credentials(): number; + function has_credentials(srealm: string): number; + function pv_auth_check(srealm: string, spasswd: string, vflags: number, vchecks: number): number; + } + + export namespace auth_db { + function auth_check(srealm: string, stable: string, iflags: number): number; + function is_subscriber(suri: string, stable: string, iflags: number): number; + } + + export namespace auth_ephemeral { + function autheph_authenticate(susername: string, spassword: string): number; + function autheph_check(srealm: string): number; + function autheph_proxy(srealm: string): number; + function autheph_www(srealm: string): number; + function autheph_www_method(srealm: string, smethod: string): number; + } + + export namespace auth_radius { + function proxy_authorize(srealm: string): number; + function proxy_authorize_user(srealm: string, suser: string): number; + function www_authorize(srealm: string): number; + function www_authorize_user(srealm: string, suser: string): number; + } + + export namespace auth_xkeys { + function auth_xkeys_add(shdr: string, skey: string, salg: string, sdata: string): number; + function auth_xkeys_check(shdr: string, skey: string, salg: string, sdata: string): number; + } + + export namespace benchmark { + function bm_log_timer(tname: string): number; + function bm_start_timer(tname: string): number; + } + + export namespace blst { + function blst_add(t: number): number; + function blst_add_default(): number; + function blst_add_retry_after(t_min: number, t_max: number): number; + function blst_clear_ignore(mask: number): number; + function blst_clear_ignore_all(): number; + function blst_del(): number; + function blst_is_blacklisted(): number; + function blst_rpl_clear_ignore(mask: number): number; + function blst_rpl_clear_ignore_all(): number; + function blst_rpl_set_ignore(mask: number): number; + function blst_rpl_set_ignore_all(): number; + function blst_set_ignore(mask: number): number; + function blst_set_ignore_all(): number; + } + + export namespace call_control { + function call_control(): number; + } + + export namespace cfgutils { + function abort(): number; + function core_hash(s1: string, s2: string, sz: number): number; + function lock(lkey: string): number; + function pkg_status(): number; + function pkg_summary(): number; + function rand_event(): number; + function rand_get_prob(): number; + function rand_reset_prob(): number; + function rand_set_prob(percent_par: number): number; + function shm_status(): number; + function shm_summary(): number; + function trylock(lkey: string): number; + function unlock(lkey: string): number; + } + + export namespace cnxcc { + function get_channel_count(sclient: string, pvname: string): number; + function set_max_channels(sclient: string, max_chan: number): number; + function set_max_credit(sclient: string, scredit: string, scps: string, initp: number, finishp: number): number; + function set_max_time(sclient: string, max_secs: number): number; + function terminate_all(sclient: string): number; + function update_max_time(sclient: string, secs: number): number; + } + + export namespace corex { + function append_branch(): number; + function append_branch_uri(uri: string): number; + function append_branch_uri_q(uri: string, q: string): number; + function has_ruri_user(): number; + function has_user_agent(): number; + function isxflagset(fval: number): number; + function resetxflag(fval: number): number; + function send_data(uri: string, data: string): number; + function sendx(uri: string, sock: string, data: string): number; + function set_recv_socket(ssock: string): number; + function set_send_socket(ssock: string): number; + function set_source_address(saddr: string): number; + function setxflag(fval: number): number; + function via_add_srvid(fval: number): number; + function via_add_xavp_params(fval: number): number; + function via_use_xavp_fields(fval: number): number; + } + + export namespace counters { + function add(sname: string, v: number): number; + function inc(sname: string): number; + function reset(sname: string): number; + } + + export namespace crypto { + function aes_decrypt(ins: string, keys: string, dpv: string): number; + function aes_encrypt(ins: string, keys: string, dpv: string): number; + } + + export namespace dialog { + function dlg_bye(side: string): number; + function dlg_db_load_callid(callid: string): number; + function dlg_db_load_extra(): number; + function dlg_get(sc: string, sf: string, st: string): number; + function dlg_isflagset(val: number): number; + function dlg_manage(): number; + function dlg_resetflag(val: number): number; + function dlg_set_property(pval: string): number; + function dlg_set_timeout(to: number): number; + function dlg_set_timeout_id(to: number, he: number, hi: number): number; + function dlg_setflag(val: number): number; + function get_profile_size(sprofile: string, svalue: string, spv: string): number; + function get_profile_size_static(sprofile: string, spv: string): number; + function is_in_profile(sprofile: string, svalue: string): number; + function is_in_profile_static(sprofile: string): number; + function is_known_dlg(): number; + function set_dlg_profile(sprofile: string, svalue: string): number; + function set_dlg_profile_static(sprofile: string): number; + function unset_dlg_profile(sprofile: string, svalue: string): number; + function unset_dlg_profile_static(sprofile: string): number; + } + + export namespace dialplan { + function dp_match(dpid: number, src: string): number; + function dp_replace(dpid: number, src: string, dst: string): number; + } + + export namespace dispatcher { + function ds_is_from_list(group: number): number; + function ds_is_from_list_mode(vset: number, vmode: number): number; + function ds_is_from_list_uri(vset: number, vmode: number, vuri: string): number; + function ds_is_from_lists(): number; + function ds_list_exists(set: number): number; + function ds_load_unset(): number; + function ds_load_update(): number; + function ds_mark_dst(): number; + function ds_mark_dst_state(sval: string): number; + function ds_next_domain(): number; + function ds_next_dst(): number; + function ds_reload(): number; + function ds_select(set: number, alg: number): number; + function ds_select_domain(set: number, alg: number): number; + function ds_select_domain_limit(set: number, alg: number, limit: number): number; + function ds_select_dst(set: number, alg: number): number; + function ds_select_dst_limit(set: number, alg: number, limit: number): number; + function ds_select_limit(set: number, alg: number, limit: number): number; + function ds_select_routes(srules: string, smode: string): number; + function ds_select_routes_limit(srules: string, smode: string, rlimit: number): number; + function ds_set_domain(): number; + function ds_set_dst(): number; + } + + export namespace diversion { + function add_diversion(reason: string): number; + function add_diversion_uri(reason: string, uri: string): number; + } + + export namespace dmq { + function bcast_message(peer_str: string, body_str: string, ct_str: string): number; + function handle_message(): number; + function handle_message_rc(returnval: number): number; + function is_from_node(): number; + function send_message(peer_str: string, to_str: string, body_str: string, ct_str: string): number; + function t_replicate(): number; + function t_replicate_mode(mode: number): number; + } + + export namespace domain { + function is_domain_local(sdomain: string): number; + function is_from_local(): number; + function is_uri_host_local(): number; + function lookup_domain(_sdomain: string): number; + function lookup_domain_prefix(_sdomain: string, _sprefix: string): number; + } + + export namespace drouting { + function do_routing(grp_id: number): number; + function do_routing_furi(): number; + function goes_to_gw(): number; + function goes_to_gw_type(type: number): number; + function is_from_gw(): number; + function is_from_gw_type(type: number): number; + function is_from_gw_type_flags(type: number, flags: number): number; + function next_routing(): number; + function use_next_gw(): number; + } + + export namespace evapi { + function async_relay(sdata: string): number; + function close(): number; + function relay(sdata: string): number; + function relay_multicast(sdata: string, stag: string): number; + function relay_unicast(sdata: string, stag: string): number; + function set_tag(stag: string): number; + } + + export namespace exec { + function exec_avp(cmd: string): number; + function exec_dset(cmd: string): number; + function exec_msg(cmd: string): number; + } + + export namespace geoip { + function match(tomatch: string, pvclass: string): number; + } + + export namespace geoip2 { + function match(tomatch: string, pvclass: string): number; + } + + export namespace group { + function is_user_in(uri: string, grp: string): number; + } + + export namespace htable { + function sht_has_name(sname: string, sop: string, sval: string): number; + function sht_has_str_value(sname: string, sop: string, sval: string): number; + function sht_iterator_end(iname: string): number; + function sht_iterator_next(iname: string): number; + function sht_iterator_start(iname: string, hname: string): number; + function sht_lock(htname: string, skey: string): number; + function sht_reset(hname: string): number; + function sht_rm(hname: string, iname: string): number; + function sht_rm_name(sname: string, sop: string, sval: string): number; + function sht_rm_name_re(htname: string, rexp: string): number; + function sht_rm_value(sname: string, sop: string, sval: string): number; + function sht_rm_value_re(htname: string, rexp: string): number; + function sht_setex(htname: string, itname: string, itval: number): number; + function sht_seti(htname: string, itname: string, itval: number): number; + function sht_sets(htname: string, itname: string, itval: string): number; + function sht_setxi(htname: string, itname: string, itval: number, exval: number): number; + function sht_setxs(htname: string, itname: string, itval: string, exval: number): number; + function sht_unlock(htname: string, skey: string): number; + } + + export namespace http_async_client { + function query(sdata: string, rn: string): number; + } + + export namespace http_client { + function curl_connect(con: string, url: string, dpv: string): number; + function curl_connect_post(con: string, url: string, ctype: string, data: string, dpv: string): number; + function query(url: string, dpv: string): number; + function query_post(url: string, post: string, dpv: string): number; + function query_post_hdrs(url: string, post: string, hdrs: string, dpv: string): number; + } + + export namespace imc { + function imc_manager(): number; + } + + export namespace ipops { + function compare_ips(_sval1: string, _sval2: string): number; + function compare_pure_ips(_sval1: string, _sval2: string): number; + function detailed_ip_type(_sval: string, _dpv: string): number; + function detailed_ipv4_type(_sval: string, _dpv: string): number; + function detailed_ipv6_type(_sval: string, _dpv: string): number; + function dns_int_match_ip(vhn: string, vip: string): number; + function dns_query(naptrname: string, pvid: string): number; + function dns_sys_match_ip(vhn: string, vip: string): number; + function ip_is_in_subnet(_sval1: string, _sval2: string): number; + function ip_type(sval: string): number; + function is_in_subnet(_sval1: string, _sval2: string): number; + function is_ip(sval: string): number; + function is_ip4(sval: string): number; + function is_ip6(sval: string): number; + function is_ip6_reference(sval: string): number; + function is_ip_rfc1918(sval: string): number; + function is_pure_ip(sval: string): number; + function naptr_query(naptrname: string, pvid: string): number; + function srv_query(naptrname: string, pvid: string): number; + } + + export namespace jansson { + function get(spath: string, sdoc: string, spv: string): number; + } + + export namespace jsonrpcs { + function exec(scmd: string): number; + } + + export namespace keepalive { + function is_alive(dest: string): number; + } + + export namespace kex { + function resetdebug(): number; + function setdebug(lval: number): number; + } + + export namespace lcr { + function defunct_gw(defunct_period: number): number; + function from_any_gw(): number; + function from_any_gw_addr(addr_str: string, transport: number): number; + function from_gw(lcr_id: number): number; + function from_gw_addr(lcr_id: number, addr_str: string, transport: number): number; + function inactivate_gw(): number; + function load_gws(lcr_id: number): number; + function load_gws_furi(lcr_id: number, ruri_user: string, from_uri: string): number; + function load_gws_ruser(lcr_id: number, ruri_user: string): number; + function next_gw(): number; + function to_any_gw(): number; + function to_any_gw_addr(addr_str: string, transport: number): number; + function to_gw(lcr_id: number): number; + function to_gw_addr(lcr_id: number, addr_str: string, transport: number): number; + } + + export namespace log_custom { + function log_udp(txt: string): number; + } + + export namespace log_systemd { + function sd_journal_print(slev: string, stxt: string): number; + function sd_journal_send_xvap(xname: string): number; + } + + export namespace maxfwd { + function is_maxfwd_lt(limit: number): number; + function process_maxfwd(limit: number): number; + } + + export namespace mediaproxy { + function end_media_session(): number; + function engage_media_proxy(): number; + function use_media_proxy(): number; + } + + export namespace misc_radius { + function does_uri_exist(): number; + function does_uri_exist_uval(suri: string): number; + function does_uri_user_exist(): number; + function does_uri_user_exist_uval(user: string): number; + function is_user_in(user: string, group: string): number; + function load_callee_avps(user: string): number; + function load_caller_avps(user: string): number; + } + + export namespace mqueue { + function mq_add(mq: string, key: string, val: string): number; + function mq_fetch(mq: string): number; + function mq_pv_free(mq: string): number; + function mq_size(mq: string): number; + } + + export namespace msilo { + function mdump(): number; + function mdump_uri(owner_s: string): number; + function mstore(): number; + function mstore_uri(owner_s: string): number; + } + + export namespace msrp { + function cmap_lookup(): number; + function cmap_save(): number; + function is_reply(): number; + function is_request(): number; + function relay(): number; + function relay_flags(rtflags: number): number; + function reply(rcode: string, rtext: string, rhdrs: string): number; + function reply_flags(rtflags: number): number; + function set_dst(rtaddr: string, rfsock: string): number; + } + + export namespace mtree { + function mt_match(tname: string, tomatch: string, mval: number): number; + } + + export namespace nat_traversal { + function client_nat_test(tests: number): number; + function fix_contact(): number; + function nat_keepalive(): number; + } + + export namespace nathelper { + function add_contact_alias(): number; + function add_contact_alias_addr(ip_str: string, port_str: string, proto_str: string): number; + function add_rcv_param(upos: number): number; + function fix_nated_contact(): number; + function fix_nated_register(): number; + function fix_nated_sdp(level: number): number; + function fix_nated_sdp_ip(level: number, ip: string): number; + function handle_ruri_alias(): number; + function is_rfc1918(address: string): number; + function nat_uac_test(tests: number): number; + function set_contact_alias(): number; + } + + export namespace ndb_mongodb { + function exec(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; + function exec_simple(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; + function find(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; + function find_one(ssrv: string, sdname: string, scname: string, scmd: string, sres: string): number; + function free_reply(name: string): number; + function next_reply(name: string): number; + } + + export namespace ndb_redis { + function redis_cmd(srv: string, rcmd: string, sres: string): number; + function redis_cmd_p1(srv: string, rcmd: string, p1: string, sres: string): number; + function redis_cmd_p2(srv: string, rcmd: string, p1: string, p2: string, sres: string): number; + function redis_cmd_p3(srv: string, rcmd: string, p1: string, p2: string, p3: string, sres: string): number; + function redis_free(name: string): number; + } + + export namespace path { + function add_path(): number; + function add_path_received(): number; + function add_path_received_user(_user: string): number; + function add_path_received_user_params(_user: string, _params: string): number; + function add_path_user(_user: string): number; + function add_path_user_params(_user: string, _params: string): number; + } + + export namespace pdt { + function pd_translate(sd: string, md: number): number; + function pprefix2domain(m: number, s: number): number; + } + + export namespace permissions { + function allow_address(addr_group: number, ips: string, port: number): number; + function allow_address_group(_addr: string, _port: number): number; + function allow_source_address(addr_group: number): number; + function allow_source_address_group(): number; + } + + export namespace phonenum { + function match(tomatch: string, pvclass: string): number; + } + + export namespace pike { + function pike_check_req(): number; + } + + export namespace pipelimit { + function pl_check(pipeid: string): number; + function pl_check_limit(pipeid: string, alg: string, limit: number): number; + function pl_drop(): number; + function pl_drop_range(rmin: number, rmax: number): number; + function pl_drop_retry(rafter: number): number; + } + + export namespace prefix_route { + function prefix_route(ruser: string): number; + function prefix_route_uri(): number; + } + + export namespace presence { + function handle_publish(): number; + function handle_publish_uri(sender_uri: string): number; + function handle_subscribe(): number; + function handle_subscribe_uri(wuri: string): number; + function pres_auth_status(watcher_uri: string, presentity_uri: string): number; + function pres_has_subscribers(pres_uri: string, wevent: string): number; + function pres_refresh_watchers(pres: string, event: string, type: number): number; + function pres_refresh_watchers_file(pres: string, event: string, type: number, file_uri: string, filename: string): number; + function pres_update_watchers(pres_uri: string, event: string): number; + } + + export namespace presence_xml { + function pres_check_activities(pres_uri: string, activity: string): number; + function pres_check_basic(pres_uri: string, status: string): number; + } + + export namespace pua { + function pua_set_publish(): number; + function pua_update_contact(): number; + } + + export namespace pvx { + function evalx(dst: string, fmt: string): number; + function pv_var_to_xavp(varname: string, xname: string): number; + function pv_xavp_print(): number; + function pv_xavp_to_var(xname: string): number; + function sbranch_append(): number; + function sbranch_reset(): number; + function sbranch_set_ruri(): number; + function xavp_params_explode(sparams: string, sxname: string): number; + function xavp_params_implode(sxname: string, svname: string): number; + } + + export namespace rabbitmq { + function publish(exchange: string, routingkey: string, contenttype: string, messagebody: string): number; + function publish_consume(exchange: string, routingkey: string, contenttype: string, messagebody: string, dpv: string): number; + } + + export namespace regex { + function pcre_match(string: string, regex: string): number; + function pcre_match_group(string: string, num_pcre: number): number; + } + + export namespace registrar { + function add_sock_hdr(hdr_name: string): number; + function lookup(table: string): number; + function lookup_branches(_dtable: string): number; + function lookup_to_dset(table: string, uri: string): number; + function lookup_uri(table: string, uri: string): number; + function reg_fetch_contacts(dtable: string, uri: string, profile: string): number; + function reg_free_contacts(profile: string): number; + function registered(table: string): number; + function registered_action(_dtable: string, _uri: string, _f: number, _aflags: number): number; + function registered_flags(_dtable: string, _uri: string, _f: number): number; + function registered_uri(_dtable: string, _uri: string): number; + function save(table: string, flags: number): number; + function save_uri(table: string, flags: number, uri: string): number; + function set_q_override(new_q: string): number; + function unregister(_dtable: string, _uri: string): number; + function unregister_ruid(_dtable: string, _uri: string, _ruid: string): number; + } + + export namespace rls { + function handle_notify(): number; + function handle_subscribe(): number; + function handle_subscribe_uri(wuri: string): number; + function update_subs(uri: string, event: string): number; + } + + export namespace rr { + function add_rr_param(sparam: string): number; + function check_route_param(sre: string): number; + function is_direction(dir: string): number; + function loose_route(): number; + function record_route(): number; + function record_route_params(params: string): number; + function remove_record_route(): number; + } + + export namespace rtjson { + function init_routes(rdoc: string): number; + function next_route(): number; + function push_routes(): number; + function update_branch(): number; + } + + export namespace rtpengine { + function rtpengine_answer(flags: string): number; + function rtpengine_answer0(): number; + function rtpengine_delete(flags: string): number; + function rtpengine_delete0(): number; + function rtpengine_manage(flags: string): number; + function rtpengine_manage0(): number; + function rtpengine_offer(flags: string): number; + function rtpengine_offer0(): number; + function set_rtpengine_set(r1: number): number; + // This function is the sibling function to set_rtpengine_set(). + // The original module function is declared as set_rtpengine_set(setid[, setid2]). + // In KEMI set_rtpengine_set() takes only the first parameter and set_rtpengine_set2() allows for the second optional parameter to be passed. + // Please review the documentation for set_rtpengine_set() for more information. + function set_rtpengine_set2(r1: number, r2: number): number; + function start_recording(): number; + function stop_recording(): number; + } + + export namespace rtpproxy { + function rtpproxy_answer(flags: string): number; + function rtpproxy_answer0(): number; + function rtpproxy_answer_ip(flags: string, mip: string): number; + function rtpproxy_destroy(flags: string): number; + function rtpproxy_destroy0(): number; + function rtpproxy_manage(flags: string): number; + function rtpproxy_manage0(): number; + function rtpproxy_manage_ip(flags: string, mip: string): number; + function rtpproxy_offer(flags: string): number; + function rtpproxy_offer0(): number; + function rtpproxy_offer_ip(flags: string, mip: string): number; + function rtpproxy_stop_stream2uac(): number; + function rtpproxy_stop_stream2uas(): number; + function rtpproxy_stream2uac(pname: string, count: number): number; + function rtpproxy_stream2uas(pname: string, count: number): number; + function set_rtpproxy_set(rset: number): number; + function start_recording(): number; + } + + export namespace sanity { + function sanity_check(mflags: number, uflags: number): number; + function sanity_check_defaults(): number; + function sanity_reply(): number; + } + + export namespace sca { + function call_info_update(update_mask: number, uri_to: string, uri_from: string): number; + function call_info_update_default(): number; + function call_info_update_mask(umask: number): number; + function call_info_update_turi(umask: number, sto: string): number; + function handle_subscribe(): number; + } + + export namespace sdpops { + function keep_codecs_by_id(codecs: string, media: string): number; + function keep_codecs_by_name(codecs: string, media: string): number; + function remove_codecs_by_id(codecs: string, media: string): number; + function remove_codecs_by_name(codecs: string, media: string): number; + function remove_line_by_prefix(prefix: string, media: string): number; + function remove_media(media: string): number; + function sdp_content(): number; + function sdp_content_flags(flags: number): number; + function sdp_get(avp: string): number; + function sdp_get_line_startswith(aname: string, sline: string): number; + function sdp_print(llevel: number): number; + function sdp_transport(avp: string): number; + function sdp_with_active_media(media: string): number; + function sdp_with_ice(): number; + function sdp_with_media(media: string): number; + } + + export namespace sipcapture { + function float2int(_val: string, _coof: string): number; + function report_capture(_table: string): number; + function report_capture_cid(_table: string, _cid: string): number; + function report_capture_data(_table: string, _cid: string, _data: string): number; + function sip_capture(): number; + function sip_capture_forward(puri: string): number; + function sip_capture_mode(_table: string, _cmdata: string): number; + function sip_capture_table(_table: string): number; + } + + export namespace sipdump { + function send(stag: string): number; + } + + export namespace sipjson { + function sj_serialize(smode: string, pvn: string): number; + } + + export namespace siptrace { + function hlog(message: string): number; + function hlog_cid(correlationid: string, message: string): number; + function sip_trace(): number; + function sip_trace_dst(duri: string): number; + function sip_trace_dst_cid(duri: string, cid: string): number; + } + + export namespace siputils { + function has_totag(): number; + function is_alphanum(tval: string): number; + function is_alphanumex(tval: string, eset: string): number; + function is_first_hop(): number; + function is_numeric(tval: string): number; + function is_reply(): number; + function is_request(): number; + function is_tel_number(tval: string): number; + function is_uri(suri: string): number; + function is_user(suser: string): number; + function uri_param(sparam: string): number; + function uri_param_value(sparam: string, svalue: string): number; + } + + export namespace sl { + function send_reply(code: number, reason: string): number; + function sl_forward_reply(code: string, reason: string): number; + function sl_reply_error(): number; + function sl_send_reply(code: number, reason: string): number; + } + + export namespace speeddial { + function lookup(stable: string): number; + function lookup_owner(stable: string, sowner: string): number; + } + + export namespace sqlops { + function sql_is_null(sres: string, i: number, j: number): number; + function sql_num_columns(sres: string): number; + function sql_num_rows(sres: string): number; + function sql_query(scon: string, squery: string, sres: string): number; + function sql_query_async(scon: string, squery: string): number; + function sql_result_free(sres: string): number; + function sql_xquery(scon: string, squery: string, xavp: string): number; + } + + export namespace ss7ops { + function isup_to_json(proto: number): number; + } + + export namespace sst { + function sst_check_min(flag: number): number; + } + + export namespace statistics { + function reset_stat(sname: string): number; + function update_stat(sname: string, sval: number): number; + } + + export namespace statsc { + function statsc_reset(): number; + } + + export namespace statsd { + function statsd_decr(key: string): number; + function statsd_gauge(key: string, val: string): number; + function statsd_incr(key: string): number; + function statsd_set(key: string, val: string): number; + function statsd_start(key: string): number; + function statsd_stop(key: string): number; + } + + export namespace tcpops { + function tcp_conid_alive(i_conid: number): number; + function tcp_conid_state(i_conid: number): number; + function tcp_enable_closed_event(): number; + function tcp_enable_closed_event_cid(i_conid: number): number; + function tcp_keepalive_disable(): number; + function tcp_keepalive_disable_cid(i_con: number): number; + function tcp_keepalive_enable(i_idle: number, i_cnt: number, i_intvl: number): number; + function tcp_keepalive_enable_cid(i_con: number, i_idle: number, i_cnt: number, i_intvl: number): number; + function tcp_set_connection_lifetime(i_time: number): number; + function tcp_set_connection_lifetime_cid(i_conid: number, i_time: number): number; + } + + export namespace textops { + function append_body_part(txt: string, ct: string): number; + function append_body_part_cd(txt: string, ct: string, cd: string): number; + function append_body_part_hex(txt: string, ct: string): number; + function append_body_part_hex_cd(htxt: string, ct: string, cd: string): number; + function cmp_istr(s1: string, s2: string): number; + function cmp_str(s1: string, s2: string): number; + function filter_body(content_type: string): number; + function get_body_part(ctype: string, pvname: string): number; + function get_body_part_raw(ctype: string, pvname: string): number; + function has_body(): number; + function has_body_type(ctype: string): number; + function in_list(subject: string, list: string, vsep: string): number; + function in_list_prefix(subject: string, list: string, vsep: string): number; + function is_audio_on_hold(): number; + function is_present_hf(hname: string): number; + function is_present_hf_re(ematch: string): number; + function is_privacy(privacy: string): number; + function remove_body_part(content_type: string): number; + function remove_hf_exp(ematch: string, eskip: string): number; + function remove_hf_re(ematch: string): number; + function replace(sre: string, sval: string): number; + function replace_all(sre: string, sval: string): number; + function replace_body(sre: string, sval: string): number; + function replace_body_all(sre: string, sval: string): number; + function replace_body_atonce(sre: string, sval: string): number; + function replace_body_str(mkey: string, rval: string, rmode: string): number; + function replace_hdrs(sre: string, sval: string): number; + function replace_hdrs_str(mkey: string, rval: string, rmode: string): number; + function replace_str(mkey: string, rval: string, rmode: string): number; + function search(sre: string): number; + function search_append(ematch: string, val: string): number; + function search_append_body(ematch: string, val: string): number; + function search_body(sre: string): number; + function search_hf(hname: string, sre: string, flags: string): number; + function set_body(nb: string, nc: string): number; + function set_body_multipart(nbody: string, ctype: string, boundary: string): number; + function set_body_multipart_boundary(boundary: string): number; + function set_body_multipart_content(nbody: string, ctype: string): number; + function set_body_multipart_mode(): number; + function set_reply_body(nb: string, nc: string): number; + function starts_with(s1: string, s2: string): number; + function subst(subst: string): number; + function subst_body(subst: string): number; + function subst_hf(hname: string, subst: string, flags: string): number; + function subst_uri(subst: string): number; + function subst_user(subst: string): number; + } + + export namespace textopsx { + function append_hf_value(hexp: string, val: string): number; + function assign_hf_value(hexp: string, val: string): number; + function assign_hf_value2(hexp: string, val: string): number; + function change_reply_status(code: number, reason: string): number; + function exclude_hf_value(hexp: string, val: string): number; + function fnmatch(val: string, match: string): number; + function fnmatch_ex(val: string, match: string, flags: string): number; + function hf_value_exists(hexp: string, val: string): number; + function include_hf_value(hexp: string, val: string): number; + function insert_hf_value(hexp: string, val: string): number; + function keep_hf(): number; + function keep_hf_re(sre: string): number; + function msg_apply_changes(): number; + function msg_set_buffer(obuf: string): number; + function remove_body(): number; + function remove_hf_value(hexp: string): number; + function remove_hf_value2(hexp: string, val: string): number; + } + + export namespace tls { + function is_peer_verified(): number; + } + + export namespace tm { + function t_any_replied(): number; + function t_any_timeout(): number; + function t_branch_replied(): number; + function t_branch_timeout(): number; + function t_check_status(sexp: string): number; + function t_check_trans(): number; + function t_drop_replies(mode: string): number; + function t_drop_replies_all(): number; + function t_grep_status(code: number): number; + function t_is_canceled(): number; + function t_is_expired(): number; + function t_is_retr_async_reply(): number; + function t_is_set(target: string): number; + function t_load_contacts(): number; + function t_lookup_cancel(): number; + function t_lookup_cancel_flags(flags: number): number; + function t_lookup_request(): number; + function t_newtran(): number; + function t_next_contact_flow(): number; + function t_next_contacts(): number; + function t_on_branch(rname: string): number; + function t_on_branch_failure(rname: string): number; + function t_on_failure(rname: string): number; + function t_on_reply(rname: string): number; + function t_relay(): number; + function t_release(): number; + function t_replicate(suri: string): number; + function t_reply(code: number, reason: string): number; + function t_reset_fr(): number; + function t_reset_max_lifetime(): number; + function t_reset_retr(): number; + function t_retransmit_reply(): number; + function t_save_lumps(): number; + function t_send_reply(code: number, reason: string): number; + function t_set_auto_inv_100(state: number): number; + function t_set_disable_6xx(state: number): number; + function t_set_disable_failover(state: number): number; + function t_set_disable_internal_reply(state: number): number; + function t_set_fr(fr_inv: number, fr: number): number; + function t_set_fr_inv(fr_inv: number): number; + function t_set_max_lifetime(t1: number, t2: number): number; + function t_set_no_e2e_cancel_reason(state: number): number; + function t_set_retr(t1: number, t2: number): number; + function t_uac_send(method: string, ruri: string, nexthop: string, ssock: string, hdrs: string, body: string): number; + function t_use_uac_headers(): number; + } + + export namespace tmrec { + function is_leap_year(y: number): number; + function is_leap_year_now(): number; + function match(rv: string): number; + function match_timestamp(rv: string, ti: number): number; + function time_period_match(period: string): number; + function time_period_match_timestamp(period: string, ti: number): number; + } + + export namespace tmx { + function t_cancel_branches(mode: string): number; + function t_cancel_callid(callid_s: string, cseq_s: string, fl: number): number; + function t_cancel_callid_reason(callid_s: string, cseq_s: string, fl: number, rcode: number): number; + function t_continue(tindex: number, tlabel: number, cbname: string): number; + function t_flush_flags(): number; + function t_flush_xflags(): number; + function t_is_branch_route(): number; + function t_is_failure_route(): number; + function t_is_reply_route(): number; + function t_is_request_route(): number; + function t_precheck_trans(): number; + function t_reply_callid(callid_s: string, cseq_s: string, code: number, status_s: string): number; + function t_reuse_branch(): number; + function t_suspend(): number; + } + + export namespace tsilo { + function ts_append(_table: string, _ruri: string): number; + function ts_append_to(tindex: number, tlabel: number, _table: string): number; + function ts_append_to_uri(tindex: number, tlabel: number, _table: string, _uri: string): number; + function ts_store(): number; + function ts_store_uri(puri: string): number; + } + + export namespace uac { + function uac_auth(): number; + function uac_reg_disable(attr: string, val: string): number; + function uac_reg_enable(attr: string, val: string): number; + function uac_reg_lookup(userid: string, sdst: string): number; + function uac_reg_refresh(l_uuid: string): number; + function uac_reg_request_to(userid: string, imode: number): number; + function uac_reg_status(sruuid: string): number; + function uac_replace_from(pdsp: string, puri: string): number; + function uac_replace_from_uri(puri: string): number; + function uac_replace_to(pdsp: string, puri: string): number; + function uac_replace_to_uri(puri: string): number; + function uac_req_send(): number; + function uac_restore_from(): number; + function uac_restore_to(): number; + } + + export namespace uac_redirect { + function get_redirects(max_c: number, max_b: number): number; + function get_redirects_acc(max_c: number, max_b: number, reason: string): number; + function get_redirects_all(): number; + } + + export namespace uri_db { + function check_from(): number; + function check_to(): number; + function check_uri(suri: string): number; + function check_uri_realm(suri: string, susername: string, srealm: string): number; + function does_uri_exist(): number; + } + + export namespace userblacklist { + function check_user_blacklist(suser: string, sdomain: string): number; + function check_user_blacklist_number(suser: string, sdomain: string, snumber: string): number; + function check_user_blacklist_table(suser: string, sdomain: string, snumber: string, stable: string): number; + function check_user_whitelist(suser: string, sdomain: string): number; + function check_user_whitelist_number(suser: string, sdomain: string, snumber: string): number; + function check_user_whitelist_table(suser: string, sdomain: string, snumber: string, stable: string): number; + } + + export namespace utils { + function xcap_auth_status(watcher_uri: string, presentity_uri: string): number; + } + + export namespace websocket { + function close(): number; + function close_conid(status: number, reason: string, con: number): number; + function close_reason(status: number, reason: string): number; + function handle_handshake(): number; + } + + export namespace xcap_server { + function xcaps_del(uri: string, path: string): number; + function xcaps_get(uri: string, path: string): number; + function xcaps_put(uri: string, path: string, pbody: string): number; + } + + export namespace xhttp { + function xhttp_reply(code: number, reason: string, ctype: string, body: string): number; + } + + export namespace xhttp_pi { + function dispatch(): number; + } + + export namespace xhttp_rpc { + function dispatch(): number; + } + + export namespace xlog { + function xalert(lmsg: string): number; + function xcrit(lmsg: string): number; + function xdbg(lmsg: string): number; + function xerr(lmsg: string): number; + function xinfo(lmsg: string): number; + function xlog(slevel: string, lmsg: string): number; + function xnotice(lmsg: string): number; + function xwarn(lmsg: string): number; + } + + export namespace xmlrpc { + function dispatch_rpc(): number; + function xmlrpc_reply(rcode: number, reason: string): number; + } +} diff --git a/types/kamailio-kemi/kamailio-kemi-tests.ts b/types/kamailio-kemi/kamailio-kemi-tests.ts new file mode 100644 index 0000000000..fc4b7e16e3 --- /dev/null +++ b/types/kamailio-kemi/kamailio-kemi-tests.ts @@ -0,0 +1,31 @@ +function ksr_request_route() { + if (KSR.maxfwd.process_maxfwd(16) < 0) { + KSR.sl.send_reply(483, "Too Many Hops"); + return; + } + const reqURI = KSR.pv.get('$ru'); + const reqMethod = KSR.pv.get('$rm'); + + if (KSR.isflagset(31)) { + KSR.hdr.append_to_reply("Retry-After: 60"); + KSR.sl.send_reply(503, "Service Unavailable"); + return; + } + + if (KSR.is_OPTIONS()) { + KSR.sl.send_reply(200, "OK"); + return; + } + + KSR.dbg(`IN ksr_request_route(): ${reqMethod} ${reqURI}`); + + KSR.pv.sets('$du', "sip:127.0.0.1:5080;transport=tcp"); + + KSR.tm.t_on_branch("ksr_branch_route"); + KSR.tm.t_on_reply("ksr_onreply_route"); + KSR.tm.t_on_failure("ksr_failure_route"); + + if (KSR.tm.t_relay() < 0) { + KSR.sl.send_reply(500, "Server error"); + } +} diff --git a/types/p-progress/tsconfig.json b/types/kamailio-kemi/tsconfig.json similarity index 93% rename from types/p-progress/tsconfig.json rename to types/kamailio-kemi/tsconfig.json index 1cd7ff1976..f8fc5ffaa7 100644 --- a/types/p-progress/tsconfig.json +++ b/types/kamailio-kemi/tsconfig.json @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "p-progress-tests.ts" + "kamailio-kemi-tests.ts" ] } diff --git a/types/element-ready/tslint.json b/types/kamailio-kemi/tslint.json similarity index 100% rename from types/element-ready/tslint.json rename to types/kamailio-kemi/tslint.json diff --git a/types/latest-version/index.d.ts b/types/latest-version/index.d.ts deleted file mode 100644 index 5127714c15..0000000000 --- a/types/latest-version/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for latest-version 4.0 -// Project: https://github.com/sindresorhus/latest-version#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = latestVersion; - -declare function latestVersion(name: string, options?: latestVersion.Options): Promise; - -declare namespace latestVersion { - interface Options { - version?: string; - } -} diff --git a/types/latest-version/latest-version-tests.ts b/types/latest-version/latest-version-tests.ts deleted file mode 100644 index 2cbd29b61f..0000000000 --- a/types/latest-version/latest-version-tests.ts +++ /dev/null @@ -1,4 +0,0 @@ -import latestVersion = require('latest-version'); - -latestVersion('ava'); // $ExpectType Promise -latestVersion('npm', { version: 'latest-5' }); // $ExpectType Promise diff --git a/types/latest-version/tsconfig.json b/types/latest-version/tsconfig.json deleted file mode 100644 index a62d14b69d..0000000000 --- a/types/latest-version/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "latest-version-tests.ts" - ] -} diff --git a/types/latest-version/tslint.json b/types/latest-version/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/latest-version/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/leven/index.d.ts b/types/leven/index.d.ts deleted file mode 100644 index bd7e0ba4aa..0000000000 --- a/types/leven/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for leven 2.1 -// Project: https://github.com/sindresorhus/leven -// Definitions by: Jan Alonzo -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare function leven(a: string, b: string): number; - -export = leven; diff --git a/types/leven/leven-tests.ts b/types/leven/leven-tests.ts deleted file mode 100644 index 4ca0406529..0000000000 --- a/types/leven/leven-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import leven = require('leven'); - -leven('baz', 'bar'); -// => "1" - -leven('foo', 'bar'); -// => "3" diff --git a/types/leven/tsconfig.json b/types/leven/tsconfig.json deleted file mode 100644 index 14d505d892..0000000000 --- a/types/leven/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "leven-tests.ts" - ] -} \ No newline at end of file diff --git a/types/leven/tslint.json b/types/leven/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/leven/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/license-checker/index.d.ts b/types/license-checker/index.d.ts index 4ae2995ea0..1d28fc7fb3 100644 --- a/types/license-checker/index.d.ts +++ b/types/license-checker/index.d.ts @@ -1,6 +1,8 @@ -// Type definitions for license-checker 15.0 +// Type definitions for license-checker 25.0 // Project: https://github.com/davglass/license-checker -// Definitions by: Rogier Schouten , Daniel Perez Alvarez +// Definitions by: Rogier Schouten , +// Daniel Perez Alvarez , +// Alec Custer // Definitions: https://github.com/borisyankov/DefinitelyTyped /** @@ -28,7 +30,23 @@ export interface InitOpts { */ onlyunknown?: boolean; /** - * to add a custom Format file in JSON + * Output in json format + */ + json?: boolean; + /** + * Output in csv format + */ + csv?: boolean; + /** + * Prefix column for component in csv format. + */ + csvComponentPrefix?: string; + /** + * Write the data to a specific file. + */ + out?: string; + /** + * To add a custom Format file in JSON */ customPath?: string | ModuleInfo; /** @@ -44,13 +62,29 @@ export interface InitOpts { */ summary?: boolean; /** - * Fail (exit with code 1) on the first occurrence of the licenses of the comma-separated list + * Fail (exit with code 1) on the first occurrence of the licenses of the semicolon-separated list */ - failOn?: string[]; + failOn?: string; /** - * Use chalk to colorize the licenses member of each returned module info. Unknown licenses become red. + * Fail (exit with code 1) on the first occurrence of the licenses not in the semicolon-separated list */ - color?: boolean; + onlyAllow?: string; + /** + * Restrict output to the packages (package@version) in the semicolon-separated list + */ + packages?: string; + /** + * Restrict output to the packages (package@version) not in the semicolon-separated list + */ + excludePackages?: string; + /** + * Restrict output to not include any package marked as private + */ + excludePrivatePackages?: boolean; + /** + * Look for direct dependencies only + */ + direct?: boolean; } /** diff --git a/types/license-checker/license-checker-tests.ts b/types/license-checker/license-checker-tests.ts index ab9039837f..408e6ea972 100644 --- a/types/license-checker/license-checker-tests.ts +++ b/types/license-checker/license-checker-tests.ts @@ -8,7 +8,17 @@ checker.init( production: true, customPath: { licenseText: "" - } + }, + json: false, + csv: false, + csvComponentPrefix: "prefixColumn", + out: "/write/to/specific/file", + failOn: "impermissible;licenses", + onlyAllow: "permissible;licenses", + packages: "packages;to;check", + excludePackages: "packages;to;exclude", + excludePrivatePackages: false, + direct: false }, (err: Error, json: checker.ModuleInfos): void => { if (err) { diff --git a/types/mem/index.d.ts b/types/mem/index.d.ts deleted file mode 100644 index 94ea5137ec..0000000000 --- a/types/mem/index.d.ts +++ /dev/null @@ -1,17 +0,0 @@ -// Type definitions for mem 1.1 -// Project: https://github.com/sindresorhus/mem -// Definitions by: Sam Verschueren -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -interface Options { - maxAge?: number; - cacheKey?(...args: any[]): string; - cache?: any; -} - -declare const mem: { - any>(fn: F, options?: Options): F; - clear any>(fn: F): void; -}; - -export = mem; diff --git a/types/mem/mem-tests.ts b/types/mem/mem-tests.ts deleted file mode 100644 index b184cf263b..0000000000 --- a/types/mem/mem-tests.ts +++ /dev/null @@ -1,10 +0,0 @@ -import mem = require('mem'); - -let i = 0; -const memoized = mem((arg: string) => ++i); -const ret1: number = memoized('foo'); - -// Clear the memoized data -mem.clear(memoized); - -const ret2: Promise = mem(() => Promise.resolve('foo'))(); diff --git a/types/mem/tsconfig.json b/types/mem/tsconfig.json deleted file mode 100644 index 3545985694..0000000000 --- a/types/mem/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "mem-tests.ts" - ] -} \ No newline at end of file diff --git a/types/mem/tslint.json b/types/mem/tslint.json deleted file mode 100644 index 71ee04c4e1..0000000000 --- a/types/mem/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-unnecessary-generics": false - } -} diff --git a/types/mui-datatables/index.d.ts b/types/mui-datatables/index.d.ts index c177e7b50d..2b1135d60f 100644 --- a/types/mui-datatables/index.d.ts +++ b/types/mui-datatables/index.d.ts @@ -103,6 +103,7 @@ export interface MUIDataTableColumnOptions { sort?: boolean; searchable?: boolean; sortDirection?: 'asc' | 'desc'; + print?: boolean; download?: boolean; hint?: string; customHeadRender?: (columnMeta: MUIDataTableCustomHeadRenderer, updateDirection: (params: any) => any) => string; @@ -153,7 +154,7 @@ export interface MUIDataTableOptions { onRowsSelect?: (currentRowsSelected: any[], rowsSelected: any[]) => void; onRowsDelete?: (rowsDeleted: any[]) => void; onRowClick?: (rowData: string[], rowMeta: { dataIndex: number; rowIndex: number }) => void; - onCellClick?: (colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number }) => void; + onCellClick?: (colData: any, cellMeta: { colIndex: number, rowIndex: number, dataIndex: number, event: React.MouseEvent }) => void; onChangePage?: (currentPage: number) => void; onChangeRowsPerPage?: (numberOfRows: number) => void; onSearchChange?: (searchText: string) => void; diff --git a/types/next/document.d.ts b/types/next/document.d.ts index f89e5d71e0..161f28625e 100644 --- a/types/next/document.d.ts +++ b/types/next/document.d.ts @@ -111,6 +111,7 @@ export type DocumentComponentType

= Nex C >; +export class Html extends React.Component> {} export class Head extends React.Component {} export class Main extends React.Component {} export class NextScript extends React.Component {} diff --git a/types/next/error.d.ts b/types/next/error.d.ts index 8ad2226f07..d22fa2b260 100644 --- a/types/next/error.d.ts +++ b/types/next/error.d.ts @@ -1,5 +1,5 @@ import * as React from "react"; -import { NextContext } from "."; +import { GetInitialProps, NextContext } from "."; /** * Initial props returned from base Error class. @@ -10,5 +10,5 @@ export interface DefaultErrorIProps { } export default class Error

extends React.Component

{ - static getInitialProps(context: NextContext): Promise | DefaultErrorIProps; + static getInitialProps: GetInitialProps; } diff --git a/types/next/index.d.ts b/types/next/index.d.ts index 0f491675ce..f12c7cf9d6 100644 --- a/types/next/index.d.ts +++ b/types/next/index.d.ts @@ -14,8 +14,8 @@ 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 { 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"; @@ -131,8 +131,16 @@ declare namespace next { * @template C Context passed to getInitialProps. */ interface NextStaticLifecycle { - getInitialProps?: (ctx: C) => Promise | IP; + getInitialProps?: GetInitialProps; } + + /** + * Next.js getInitialProps type. + * + * @template IP Initial props returned from getInitialProps and passed to the component. + * @template C Context passed to getInitialProps. + */ + type GetInitialProps = (ctx: C) => Promise | IP; } declare function next(options?: next.ServerOptions & { dev: true }): next.DevServer; diff --git a/types/next/test/next-document-tests.tsx b/types/next/test/next-document-tests.tsx index 7c50a03930..9fcb18869c 100644 --- a/types/next/test/next-document-tests.tsx +++ b/types/next/test/next-document-tests.tsx @@ -1,6 +1,7 @@ import Document, { DocumentProps, Enhancer, + Html, Head, Main, NextScript, @@ -21,7 +22,7 @@ class MyDocumentDefault extends Document { render() { return ( - + @@ -29,7 +30,7 @@ class MyDocumentDefault extends Document {

- + ); } } diff --git a/types/node-forge/index.d.ts b/types/node-forge/index.d.ts index ad15411714..4a366deab7 100644 --- a/types/node-forge/index.d.ts +++ b/types/node-forge/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for node-forge 0.7.6 +// Type definitions for node-forge 0.8.1 // Project: https://github.com/digitalbazaar/forge // Definitions by: Seth Westphal // Kay Schecker @@ -10,6 +10,7 @@ // timhwang21 // supaiku0 // Anders Kaseorg +// Sascha Zarhuber // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.6 @@ -56,23 +57,19 @@ declare module "node-forge" { type PEM = string; type PublicKey = rsa.PublicKey | ed25519.Key; type PrivateKey = rsa.PrivateKey | ed25519.Key; + type EncryptionOptions = { + algorithm?: 'aes128' | 'aes192' | 'aes256' | '3des'; + count?: number; + saltSize?: number; + prfAlgorithm?: 'sha1' | 'sha224' | 'sha256' | 'sha384' | 'sha512'; + legacy?: boolean; + }; interface KeyPair { publicKey: PublicKey; privateKey: PrivateKey; } - function pemToDer(pem: PEM): util.ByteStringBuffer; - 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(certs?: ReadonlyArray): CAStore; - function verifyCertificateChain(caStore: CAStore, chain: Certificate[], customVerifyCallback?: (verified: boolean | string, depth: number, chain: Certificate[]) => boolean): boolean; - interface oids { [key: string]: string; } @@ -270,9 +267,51 @@ declare module "node-forge" { function createCertificationRequest(): Certificate; - function publicKeyToAsn1(publicKey: PublicKey): any; + function certificateToPem(cert: Certificate, maxline?: number): PEM; + + function certificateFromPem(pem: PEM, computeHash?: boolean, strict?: boolean): Certificate; + + function createCaStore(certs?: ReadonlyArray): CAStore; + + function verifyCertificateChain(caStore: CAStore, chain: Certificate[], customVerifyCallback?: (verified: boolean | string, depth: number, chain: Certificate[]) => boolean): boolean; + + function pemToDer(pem: PEM): util.ByteStringBuffer; + + function privateKeyToPem(key: PrivateKey, maxline?: number): PEM; + + function privateKeyInfoToPem(key: asn1.Asn1, maxline?: number): PEM; + + function publicKeyToPem(key: PublicKey, maxline?: number): PEM; + + function publicKeyFromPem(pem: PEM): PublicKey; + + function privateKeyFromPem(pem: PEM): PrivateKey; + + function decryptPrivateKeyInfo(obj: asn1.Asn1, password: string): asn1.Asn1; + + function encryptPrivateKeyInfo(obj: asn1.Asn1, password: string, options?: EncryptionOptions): asn1.Asn1; + + function encryptedPrivateKeyFromPem(pem: PEM): asn1.Asn1; + + function encryptedPrivateKeyToPem(obj: asn1.Asn1): PEM; + + function decryptRsaPrivateKey(pem: PEM, password: string): PrivateKey; + + function encryptRsaPrivateKey(privateKey: PrivateKey, password: string, options?: EncryptionOptions): PEM; + + function privateKeyFromAsn1(privateKey: asn1.Asn1): PrivateKey; + + function privateKeyToAsn1(privateKey: PrivateKey): asn1.Asn1; + + function publicKeyFromAsn1(publicKey: asn1.Asn1): PublicKey; + + function publicKeyToAsn1(publicKey: PublicKey): asn1.Asn1; function publicKeyToRSAPublicKey(publicKey: PublicKey): any; + + function setRsaPublicKey(n: jsbn.BigInteger, e: jsbn.BigInteger): PublicKey; + + function wrapRsaPrivateKey(privateKey: asn1.Asn1): asn1.Asn1; } namespace random { @@ -548,6 +587,7 @@ declare module "node-forge" { } namespace md { + interface MessageDigest { update(msg: string, encoding?: Encoding): MessageDigest; digest(): util.ByteStringBuffer; @@ -561,6 +601,10 @@ declare module "node-forge" { function create(): MessageDigest; } + namespace sha384 { + function create(): MessageDigest; + } + namespace sha512 { function create(): MessageDigest; } @@ -568,6 +612,23 @@ declare module "node-forge" { namespace md5 { function create(): MessageDigest; } + + namespace hmac { + } + } + + namespace hmac { + + type Algorithm = "sha1" | "md5" | "sha256"; + + interface HMAC { + digest(): util.ByteBuffer; + getMact(): util.ByteBuffer; + start(md: Algorithm, key: string | util.ByteBuffer | null): void; + update(bytes: string | util.ByteBuffer | Buffer): void; + } + + function create(): HMAC; } namespace cipher { diff --git a/types/node/test/util.ts b/types/node/test/util.ts index 3af024972e..14500161fd 100644 --- a/types/node/test/util.ts +++ b/types/node/test/util.ts @@ -89,14 +89,14 @@ import { readFile } from 'fs'; } static test(): void { - const cfn = util.callbackify(this.fn); - const cfnE = util.callbackify(this.fnE); - const cfnT1 = util.callbackify(this.fnT1); - const cfnT1E = util.callbackify(this.fnT1E); - const cfnTResult = util.callbackify(this.fnTResult); - const cfnTResultE = util.callbackify(this.fnTResultE); - const cfnT1TResult = util.callbackify(this.fnT1TResult); - const cfnT1TResultE = util.callbackify(this.fnT1TResultE); + const cfn = util.callbackify(callbackifyTest.fn); + const cfnE = util.callbackify(callbackifyTest.fnE); + const cfnT1 = util.callbackify(callbackifyTest.fnT1); + const cfnT1E = util.callbackify(callbackifyTest.fnT1E); + const cfnTResult = util.callbackify(callbackifyTest.fnTResult); + const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); + const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); + const cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); diff --git a/types/node/v10/node-tests.ts b/types/node/v10/node-tests.ts index 6ae1c52bde..789b87b600 100644 --- a/types/node/v10/node-tests.ts +++ b/types/node/v10/node-tests.ts @@ -882,14 +882,14 @@ function bufferTests() { } static test(): void { - const cfn = util.callbackify(this.fn); - const cfnE = util.callbackify(this.fnE); - const cfnT1 = util.callbackify(this.fnT1); - const cfnT1E = util.callbackify(this.fnT1E); - const cfnTResult = util.callbackify(this.fnTResult); - const cfnTResultE = util.callbackify(this.fnTResultE); - const cfnT1TResult = util.callbackify(this.fnT1TResult); - const cfnT1TResultE = util.callbackify(this.fnT1TResultE); + const cfn = util.callbackify(callbackifyTest.fn); + const cfnE = util.callbackify(callbackifyTest.fnE); + const cfnT1 = util.callbackify(callbackifyTest.fnT1); + const cfnT1E = util.callbackify(callbackifyTest.fnT1E); + const cfnTResult = util.callbackify(callbackifyTest.fnTResult); + const cfnTResultE = util.callbackify(callbackifyTest.fnTResultE); + const cfnT1TResult = util.callbackify(callbackifyTest.fnT1TResult); + const cfnT1TResultE = util.callbackify(callbackifyTest.fnT1TResultE); cfn((err: NodeJS.ErrnoException, ...args: string[]) => assert(err === null && args.length === 1 && args[0] === undefined)); cfnE((err: NodeJS.ErrnoException, ...args: string[]) => assert(err.message === 'fail' && args.length === 0)); diff --git a/types/npm-email/index.d.ts b/types/npm-email/index.d.ts deleted file mode 100644 index 055a68f8af..0000000000 --- a/types/npm-email/index.d.ts +++ /dev/null @@ -1,14 +0,0 @@ -// Type definitions for npm-email 3.0 -// Project: https://github.com/sindresorhus/npm-email#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = npmEmail; - -/** - * Get the email of an npm user. - * - * @param username npm username to look up. - * @returns A promise for the user's email address. - */ -declare function npmEmail(username: string): Promise; diff --git a/types/npm-email/npm-email-tests.ts b/types/npm-email/npm-email-tests.ts deleted file mode 100644 index b0640c73e3..0000000000 --- a/types/npm-email/npm-email-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ -import npmEmail = require('npm-email'); - -npmEmail('sindresorhus'); // $ExpectType Promise diff --git a/types/npm-email/tsconfig.json b/types/npm-email/tsconfig.json deleted file mode 100644 index 985ed0472a..0000000000 --- a/types/npm-email/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "npm-email-tests.ts" - ] -} diff --git a/types/npm-email/tslint.json b/types/npm-email/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/npm-email/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/npm-keyword/index.d.ts b/types/npm-keyword/index.d.ts deleted file mode 100644 index 94c8af9f13..0000000000 --- a/types/npm-keyword/index.d.ts +++ /dev/null @@ -1,44 +0,0 @@ -// Type definitions for npm-keyword 5.0 -// Project: https://github.com/sindresorhus/npm-keyword#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = npmKeyword; - -/** - * Get a list of npm packages with a certain keyword. - * - * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` - * @returns A promise for a list of packages having the specified keyword in their package.json `keyword` property. - */ -declare function npmKeyword( - keyword: string | string[], - options?: npmKeyword.Options -): Promise; - -declare namespace npmKeyword { - /** - * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` - * @returns A promise for a list of package names. Use this if you don't need the description as it's faster. - */ - function names(keyword: string | string[], options?: Options): Promise; - - /** - * @param keyword One or more keywords. Only matches packages that have *all* the given keywords. Example: `['string', 'camelcase']` - * @returns A promise for the count of packages. - */ - function count(keyword: string | string[]): Promise; - - interface Options { - /** - * Limits the amount of results. - * @default 250 - */ - size?: number; - } - - interface PackageDescriptor { - name: string; - description: string; - } -} diff --git a/types/npm-keyword/npm-keyword-tests.ts b/types/npm-keyword/npm-keyword-tests.ts deleted file mode 100644 index 17418bdb04..0000000000 --- a/types/npm-keyword/npm-keyword-tests.ts +++ /dev/null @@ -1,7 +0,0 @@ -import npmKeyword = require('npm-keyword'); - -npmKeyword('gulpplugin'); // $ExpectType Promise -npmKeyword('gulpplugin', { size: 10 }); // $ExpectType Promise -npmKeyword.names('gulpplugin'); // $ExpectType Promise -npmKeyword.names('gulpplugin', { size: 10 }); // $ExpectType Promise -npmKeyword.count('gulpplugin'); // $ExpectType Promise diff --git a/types/npm-keyword/tsconfig.json b/types/npm-keyword/tsconfig.json deleted file mode 100644 index b0c0fed33d..0000000000 --- a/types/npm-keyword/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "npm-keyword-tests.ts" - ] -} diff --git a/types/npm-keyword/tslint.json b/types/npm-keyword/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/npm-keyword/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/npm-user/index.d.ts b/types/npm-user/index.d.ts deleted file mode 100644 index 2d03c12c0c..0000000000 --- a/types/npm-user/index.d.ts +++ /dev/null @@ -1,18 +0,0 @@ -// Type definitions for npm-user 3.0 -// Project: https://github.com/sindresorhus/npm-user#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = npmUser; - -declare function npmUser(name: string): Promise; - -declare namespace npmUser { - interface UserData { - name: string | null; - avatar: string | null; - email: string | null; - github: string | null; - twitter: string | null; - } -} diff --git a/types/npm-user/npm-user-tests.ts b/types/npm-user/npm-user-tests.ts deleted file mode 100644 index 1d63de27ef..0000000000 --- a/types/npm-user/npm-user-tests.ts +++ /dev/null @@ -1,11 +0,0 @@ -import npmUser = require('npm-user'); - -npmUser('sindresorhus').then(user => { - user; // $ExpectType UserData - - user.name; // $ExpectType string | null - user.avatar; // $ExpectType string | null - user.email; // $ExpectType string | null - user.github; // $ExpectType string | null - user.twitter; // $ExpectType string | null -}); diff --git a/types/npm-user/tsconfig.json b/types/npm-user/tsconfig.json deleted file mode 100644 index 1e5c1d464f..0000000000 --- a/types/npm-user/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "npm-user-tests.ts" - ] -} diff --git a/types/npm-user/tslint.json b/types/npm-user/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/npm-user/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/openpgp/common/index.d.ts b/types/openpgp/common/index.d.ts deleted file mode 100644 index 88796dea9d..0000000000 --- a/types/openpgp/common/index.d.ts +++ /dev/null @@ -1,5 +0,0 @@ -export class HKP { - constructor(keyServerUrl?: string); - lookup(options: {keyId?: string, query?: string }): Promise; - upload(publicKeyArmored: string): Promise; -} diff --git a/types/openpgp/index.d.ts b/types/openpgp/index.d.ts index 636d83faff..5d8c4a2cb6 100644 --- a/types/openpgp/index.d.ts +++ b/types/openpgp/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for openpgp 4.4.8 -// Project: http://openpgpjs.org/ +// Type definitions for openpgp v4.4.10 +// Project: https://openpgpjs.org // Definitions by: Guillaume Lacasa // Errietta Kostala // Daniel Montesinos @@ -8,1042 +8,5155 @@ // SardineFIsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.2 +import BN = require("bn.js"); +import stream = require("stream") -export as namespace openpgp; +export { } -export * from './common'; +// Declare to fix type issue +type NodeStream = stream; +type Integer = number; +type Infinity = any; +type ReadableStream = any; -export interface UserId { - name?: string, - email?: string, -} - -export interface SessionKey { - data: Uint8Array, - algorithm: string -} - -export interface EncryptOptions { - message: message.Message - publicKeys?: key.Key | key.Key[], - privateKeys?: key.Key | key.Key[], - passwords?: string | string[], - sessionKey?: SessionKey, - compression?: enums.compression, - armor?: boolean, - streaming?: 'web' | 'node' | false - detached?: boolean, - signature?: Signature, - returnSessionKey?: boolean, - wildcard?: boolean, - date?: Date, - fromUserId?: UserId, - toUserId?: UserId, -} - -export interface EncryptedMessage { - data?: string, - message?: message.Message, - signature?: string | ReadableStream | Signature // TODO add NodeStream - sessionKey?: SessionKey -} - -export interface DecryptOptions { - message: message.Message, - privateKeys?: key.Key | key.Key[], - passwords?: string | string[], - sessionKeys?: SessionKey | SessionKey[], - publicKeys?: key.Key | key.Key[], - format?: string, - streaming?: 'web' | 'node' | false, - signature?: Signature, - date?: Date, -} - -export interface SignOptions { - message: message.Message, - privateKeys?: key.Key | key.Key[], - armor?: boolean, - streaming?: 'web' | 'node' | false, - detached?: boolean - date?: Date, - fromUserIds?: UserId[] -} - -export interface SignedMessage { - signature?: string | ReadableStream | Signature, // TODO add NodeStream - data?: string | ReadableStream, // TODO add NodeStream - message?: message.Message -} - -export interface KeyContainer { - key: key.Key, -} - -export interface KeyPair extends KeyContainer { - privateKeyArmored: string, - publicKeyArmored: string, - revocationCertificate: string -} - -export interface KeyOptions { - userIds?: UserId[], - passphrase?: string, - numBits?: number, - keyExpirationTime?: number, - curve?: string, - date?: Date, - subkeys?: KeyOptions[] -} - -export interface Keyid { - bytes: string, -} - -export interface Signature { - keyid: Keyid, - valid: boolean, - verified?: boolean -} - -export interface VerifyOptions { - message: message.Message, - publicKeys: key.Key | key.Key[], - streaming?: 'web' | 'node' | false, - signature?: Signature, - date?: Date -} - -export interface VerifiedMessage { - data: Uint8Array | string | ReadableStream, // TODO add NodeStream - signatures: Array, -} - -export interface DecryptedMessage { - data: Uint8Array | string | ReadableStream, // TODO add NodeStream - signatures: Array, - filename: string -} - -export interface OpenPGPWorker { - randomCallback(): void; - configure(config: any): void; - seedRandom(buffer: ArrayBuffer): void; - delegate(id: number, method: string, options: any): void; - response(event: any): void; -} - -export interface WorkerOptions { - path?: string, - n?: number, - workers?: OpenPGPWorker[], - config?: any -} - -export class AsyncProxy { - constructor(options: WorkerOptions); - getId(): number; - seedRandom(workerId: number, size: number): Promise; - terminate(): void; - delegate(method: string, options: any): void; - - workers: OpenPGPWorker[]; -} - -/** - * Set the path for the web worker script and create an instance of the async proxy - * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js' - * @param {Number} n number of workers to initialize - * @param {Array} workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' - */ -export function initWorker(options: WorkerOptions): boolean; - -/** - * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() - * @returns {module:worker/async_proxy.AsyncProxy|null} the async proxy or null if not initialized - */ -export function getWorker(): AsyncProxy; - -/** - * Cleanup the current instance of the web worker. - */ -export function destroyWorker(): void; - -/** - * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords - * must be specified. If private keys are specified, those will be used to sign the message. - * @param {Message} message message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary - * @param {Key|Array} publicKeys (optional) array of keys or single key, used to encrypt the message - * @param {Key|Array} privateKeys (optional) private keys for signing. If omitted message will not be signed - * @param {String|Array} passwords (optional) array of passwords or a single password to encrypt the message - * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config - * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object) - * @param {Signature} signature (optional) a detached signature to add to the encrypted message - * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object - * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param {Date} date (optional) override the creation date of the message signature - * @param {Object} fromUserId (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' } - * @param {Object} toUserId (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' } - * @returns {Promise} Object containing encrypted (and optionally signed) message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message, (if `armor` was false) - * signature: String|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) - * signature: Signature (if `detached` was true and `armor` was false) - * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) - * } - * @async - * @static - */ -export function encrypt(options: EncryptOptions): Promise; - -/** - * Decrypts a message with the user's private key, a session key or a password. Either a private key, - * a session key or a password must be specified. - * @param {Message} message the message object with the encrypted data - * @param {Key|Array} privateKeys (optional) private keys with decrypted secret key data or session key - * @param {String|Array} passwords (optional) passwords to decrypt the message - * @param {Object|Array} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String } - * @param {Key|Array} publicKeys (optional) array of public keys or single key, to verify signatures - * @param {String} format (optional) return data format either as 'utf8' or 'binary' - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Signature} signature (optional) detached signature for verification - * @param {Date} date (optional) use the given date for verification instead of the current time - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if format was 'utf8', the default) - * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: Boolean (if streaming was false) - * }, ... - * ] - * } - * @async - * @static - */ -export function decrypt(options: DecryptOptions): Promise; - -/** - * Signs a cleartext message. - * @param {CleartextMessage|Message} message (cleartext) message to be signed - * @param {Key|Array} privateKeys array of keys or single key with decrypted secret key data to sign cleartext - * @param {Boolean} armor (optional) if the return value should be ascii armored or the message object - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Boolean} detached (optional) if the return value should contain a detached signature - * @param {Date} date (optional) override the creation date of the signature - * @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns {Promise} Object containing signed message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message (if `armor` was false) - * } - * - * Or, if `detached` was true: - * - * { - * signature: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * signature: Signature (if `armor` was false) - * } - * @async - * @static - */ -export function sign(options: SignOptions): Promise; - -/** - * Verifies signatures of cleartext signed message - * @param {Key|Array} publicKeys array of publicKeys or single key, to verify signatures - * @param {CleartextMessage|Message} message (cleartext) message object with signatures - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Signature} signature (optional) detached signature for verification - * @param {Date} date (optional) use the given date for verification instead of the current time - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `message` was a CleartextMessage) - * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: Boolean (if `streaming` was false) - * }, ... - * ] - * } - * @async - * @static - */ -export function verify(options: VerifyOptions): Promise; - -/** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. - * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key - * @param {Number} numBits (optional) number of bits for RSA keys: 2048 or 4096. - * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param {String} curve (optional) elliptic curve for ECC keys: - * curve25519, p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. - * @param {Date} date (optional) override the creation date of the key and the key signatures - * @param {Array} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise} The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - * @async - * @static - */ -export function generateKey(options: KeyOptions): Promise; - -/** - * Reformats signature packets for a key and rewraps key object. - * @param {Key} privateKey private key to reformat - * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key - * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key - * @returns {Promise} The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - * @async - * @static - */ -export function reformatKey(options: { - privateKey: key.Key, - userIds?: UserId[], - passphrase?: string, - keyExpirationTime?: number, - revocationCertificate?: boolean -}): Promise; - -/** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. - * @param {Key} key (optional) public or private key to revoke - * @param {String} revocationCertificate (optional) revocation certificate to revoke the key with - * @param {Object} reasonForRevocation (optional) object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation - * @param {String} reasonForRevocation.string (optional) string explaining the reason for revocation - * @returns {Promise} The revoked key object in the form: - * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } - * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) - * @static - */ -export function revokeKey(options: { - key?: key.Key, - revocationCertificate?: string - reasonForRevocation?: { - flag: enums.reasonForRevocation, - 'string': string - }, -}): Promise; - -/** - * Unlock a private key with your passphrase. - * @param {Key} privateKey the private key that is to be decrypted - * @param {String|Array} passphrase the user's passphrase(s) chosen during key generation - * @returns {Promise} the unlocked key object in the form: { key:Key } - * @async - */ -export function decryptKey(options: { - privateKey: key.Key, - passphrase?: string | string[], -}): Promise; - -/** - * Lock a private key with your passphrase. - * @param {Key} privateKey the private key that is to be decrypted - * @param {String|Array} passphrase the user's passphrase(s) chosen during key generation - * @returns {Promise} the locked key object in the form: { key:Key } - * @async - */ -export function encryptKey(options: { - privateKey: key.Key, - passphrase?: string | string[], -}): Promise; - -// TODO add typings for encryptSessionKey and decryptSessionKeys - -export namespace armor { - /** Armor an OpenPGP binary packet block - - @param messagetype type of the message - @param body - @param partindex - @param parttotal - */ - function armor(messagetype: enums.armor, body: Object, partindex: number, parttotal: number): string; - - /** DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes - - @param text OpenPGP armored message - */ - function dearmor(text: string): Object; -} - -export namespace cleartext { - /** Class that represents an OpenPGP cleartext signed message. - */ - interface CleartextMessage { - /** Returns ASCII armored text of cleartext signed message +export namespace openpgp { + namespace cleartext { + /** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} */ - armor(): string; + class CleartextMessage { + /** + * @param text The cleartext of the signed message + * @param signature The detached signature or an empty signature for unsigned messages + */ + constructor(text: string, signature: signature.Signature); - /** Returns the key IDs of the keys that signed the cleartext message - */ - getSigningKeyIds(): Array; + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; - /** Get cleartext - */ - getText(): string; + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new cleartext message with signed content + */ + sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - /** Sign the cleartext message - @param privateKeys private keys with decrypted secret key data for signing - */ - sign(privateKeys: Array): void; + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - /** Verify signatures of cleartext signed message - @param keys array of keys to verify signatures + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date: Date): Promise>; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], date: Date): Promise>; + + /** + * Get cleartext + * @returns cleartext of message + */ + getText(): string; + + /** + * Returns ASCII armored text of cleartext signed message + * @returns ASCII armor + */ + armor(): string | ReadableStream; + } + + /** + * reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param armoredText text to be parsed + * @returns new cleartext message object */ - verify(keys: Array): Array; + function readArmored(armoredText: string | ReadableStream): CleartextMessage; + + /** + * Creates a new CleartextMessage object from text + * @param text + */ + function fromText(text: string): void; } - /** creates new message object from text - @param text + /** + * @see module:config/config */ - function fromText(text: string): CleartextMessage; + namespace config { + var prefer_hash_algorithm: any; - function readArmored(armoredText: string): Promise; -} + var encryption_cipher: any; -export namespace config { - var prefer_hash_algorithm: enums.hash; - var encryption_cipher: enums.symmetric; - var compression: enums.compression; - var show_version: boolean; - var show_comment: boolean; - var integrity_protect: boolean; - var keyserver: string; - var debug: boolean; -} + var compression: any; -export namespace crypto { - interface Mpi { - data: number, - read(input: string): number, - write(): string, + var deflate_level: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + */ + var aead_protect: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. + * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. + * Note that this determines how AEAD packets are parsed even when aead_protect is set to false + */ + var aead_protect_version: any; + + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aead_protect is set to true. + */ + var aead_mode: any; + + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aead_protect is set to true. + * Must be an integer value from 0 to 56. + */ + var aead_chunk_size_byte: any; + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: + * Iteration Count Byte for S2K (String to Key) + */ + var s2k_iteration_count_byte: any; + + /** + * Use integrity protection for symmetric encryption + */ + var integrity_protect: any; + + var ignore_mdc_error: any; + + var allow_unauthenticated_stream: any; + + var checksum_required: any; + + var rsa_blinding: any; + + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + */ + var password_collision_check: any; + + var revocations_expire: any; + + var use_native: any; + + var min_bytes_for_web_crypto: any; + + var zero_copy: any; + + var debug: any; + + var tolerant: any; + + var show_version: any; + + var show_comment: any; + + var versionstring: any; + + var commentstring: any; + + var keyserver: any; + + var node_store: any; + + /** + * Max userid string length (used for parsing) + */ + var max_userid_length: any; + + namespace localStorage { + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; + } + } } - /** Generating a session key for the specified symmetric algorithm - @param algo Algorithm to use - */ - function generateSessionKey(algo: enums.symmetric): string; + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); - /** generate random byte prefix as string for the specified algorithm - @param algo Algorithm to use - */ - function getPrefixRandom(algo: enums.symmetric): string; + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; - /** Returns the number of integers comprising the private key of an algorithm - @param algo The public key algorithm - */ - function getPrivateMpiCount(algo: enums.symmetric): number; - - /** Decrypts data using the specified public key multiprecision integers of the private key, the specified secretMPIs of the private key and the specified algorithm. - @param algo Algorithm to be used - @param publicMPIs Algorithm dependent multiprecision integers of the public key part of the private key - @param secretMPIs Algorithm dependent multiprecision integers of the private key used - @param data Data to be encrypted as MPI - */ - function publicKeyDecrypt(algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: Mpi): Mpi; - - /** Encrypts data using the specified public key multiprecision integers and the specified algorithm. - @param algo Algorithm to be used - @param publicMPIs Algorithm dependent multiprecision integers - @param data Data to be encrypted as MPI - */ - function publicKeyEncrypt(algo: enums.publicKey, publicMPIs: Array, data: Mpi): Array; - - - namespace cfb { - /** This function decrypts a given plaintext using the specified blockcipher to decrypt a message - @param cipherfn the algorithm cipher class to decrypt data in one block_size encryption - @param key binary string representation of key to be used to decrypt the ciphertext. This will be passed to the cipherfn - @param ciphertext to be decrypted provided as a string - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Decryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function decrypt(cipherfn: string, key: string, ciphertext: string, resync: boolean): string; - - /** This function encrypts a given with the specified prefixrandom using the specified blockcipher to encrypt a message - @param prefixrandom random bytes of block_size length provided as a string to be used in prefixing the data - @param cipherfn the algorithm cipher class to encrypt data in one block_size encryption - @param plaintext data to be encrypted provided as a string - @param key binary string representation of key to be used to encrypt the plaintext. This will be passed to the cipherfn - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Encryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function encrypt(prefixrandom: string, cipherfn: string, plaintext: string, key: string, resync: boolean): string; - - /** Decrypts the prefixed data for the Modification Detection Code (MDC) computation - @param cipherfn cipherfn.encrypt Cipher function to use - @param key binary string representation of key to be used to check the mdc This will be passed to the cipherfn - @param ciphertext The encrypted data - */ - function mdc(cipherfn: Object, key: string, ciphertext: string): string; + /** + * Writes the config to HTML5 local storage + */ + write(): void; } - namespace hash { - /** Create a hash on the specified data using the specified algorithm - @param algo Hash algorithm type - @param data Data to be hashed - */ - function digest(algo: enums.hash, data: string): string; - /** Returns the hash size in bytes of the specified hash algorithm type - @param algo Hash algorithm type + + /** + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + */ + namespace crypto { + /** + * @see module:crypto/public_key/elliptic/ecdh + */ + namespace aes_kw { + /** + * AES key wrap + * @param key + * @param data + * @returns + */ + function wrap(key: string, data: string): Uint8Array; + + /** + * AES key unwrap + * @param key + * @param data + * @returns + * @throws + */ + function unwrap(key: string, data: string): Uint8Array; + } + + namespace cfb { + function encrypt(algo: any, key: any, plaintext: any, iv: any): any + function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise + } + + namespace cipher { + /** + * AES-128 encryption and decryption (ID 7) + * @param key 128-bit key + * @see + * @see + * @returns + */ + function aes128(key: string): object; + + /** + * AES-128 Block Cipher (ID 8) + * @param key 192-bit key + * @see + * @see + * @returns + */ + function aes192(key: string): object; + + /** + * AES-128 Block Cipher (ID 9) + * @param key 256-bit key + * @see + * @see + * @returns + */ + function aes256(key: string): object; + + /** + * Triple DES Block Cipher (ID 2) + * @param key 192-bit key + * @see + * @returns + */ + function tripledes(key: string): object; + + /** + * CAST-128 Block Cipher (ID 3) + * @param key 128-bit key + * @see + * @returns + */ + function cast5(key: string): object; + + /** + * Twofish Block Cipher (ID 10) + * @param key 256-bit key + * @see + * @returns + */ + function twofish(key: string): object; + + /** + * Blowfish Block Cipher (ID 4) + * @param key 128-bit key + * @see + * @returns + */ + function blowfish(key: string): object; + + /** + * Not implemented + * @throws + */ + function idea(): void; + } + + namespace cmac { + /** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ + const blockLength: any; + + /** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param data + * @param padding + */ + function rightXorMut(data: Uint8Array, padding: Uint8Array): void; + } + + namespace crypto { + /** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param pub_params Algorithm-specific public key parameters + * @param data Data to be encrypted as MPI + * @param fingerprint Recipient fingerprint + * @returns encrypted session key parameters + */ + function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; + + /** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param key_params Algorithm-specific public, private key parameters + * @param data_params encrypted session key parameters + * @param fingerprint Recipient fingerprint + * @returns An MPI containing the decrypted data + */ + function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; + + /** + * Returns the types comprising the private key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPrivKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the public key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPubKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the encrypted session key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getEncSessionKeyParamTypes(algo: string): any[]; + + /** + * Generate algorithm-specific key parameters + * @param algo The public key algorithm + * @param bits Bit length for RSA keys + * @param oid Object identifier for ECC keys + * @returns The array of parameters + */ + function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; + + /** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + */ + function getPrefixRandom(algo: enums.symmetric): Uint8Array; + + /** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes as a string to be used as a key + */ + function generateSessionKey(algo: enums.symmetric): Uint8Array; + } + + namespace eax { + /** + * Class to en/decrypt using EAX mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function EAX(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to verify + * @returns The plaintext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + namespace gcm { + /** + * Class to en/decrypt using GCM mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function GCM(cipher: string, key: Uint8Array): void; + } + + /** + * @see + * @see + */ + namespace hash { + /** + * @see module:md5 + */ + var md5: any; + + /** + * @see asmCrypto + */ + var sha1: any; + + /** + * @see hash.js + */ + var sha224: any; + + /** + * @see asmCrypto + */ + var sha256: any; + + /** + * @see hash.js + */ + var sha384: any; + + /** + * @see asmCrypto + */ + var sha512: any; + + /** + * @see hash.js + */ + var ripemd: any; + + /** + * Create a hash on the specified data using the specified algorithm + * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param data Data to be hashed + * @returns hash value + */ + function digest(algo: enums.hash, data: Uint8Array): Promise; + + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns Size in bytes of the resulting hash + */ + function getHashByteLength(algo: enums.hash): Integer; + } + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs5 { + /** + * Add pkcs5 padding to a text. + * @param msg Text to add padding + * @returns Text with padding added + */ + function encode(msg: string): string; + + /** + * Remove pkcs5 padding from a string. + * @param msg Text to remove padding from + * @returns Text with padding removed + */ + function decode(msg: string): string; + } + + namespace ocb { + /** + * Class to en/decrypt using OCB mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function OCB(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + /** + * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/ecdh + * @see module:packet.PublicKeyEncryptedSessionKey */ - function getHashByteLength(algo: enums.hash): number; + namespace pkcs1 { + namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; + + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; + } + + namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; + } + + /** + * ASN1 object identifiers for hashes + * @see + */ + const hash_headers: any; + } + + namespace public_key { + namespace dsa { + /** + * DSA Sign function + * @param hash_algo + * @param hashed + * @param g + * @param p + * @param q + * @param x + * @returns + */ + function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; + + /** + * DSA Verify function + * @param hash_algo + * @param r + * @param s + * @param hashed + * @param g + * @param p + * @param q + * @param y + * @returns BN + */ + function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; + } + + namespace elgamal { + /** + * ElGamal Encryption function + * @param m + * @param p + * @param g + * @param y + * @returns + */ + function encrypt(m: BN, p: BN, g: BN, y: BN): object; + + /** + * ElGamal Encryption function + * @param c1 + * @param c2 + * @param p + * @param x + * @returns BN + */ + function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; + } + + /** + * @see module:crypto/public_key/elliptic/curve + * @see module:crypto/public_key/elliptic/ecdh + * @see module:crypto/public_key/elliptic/ecdsa + * @see module:crypto/public_key/elliptic/eddsa + */ + namespace elliptic { + namespace curve { + class Curve { + } + } + + namespace ecdh { + /** + * Generate ECDHE ephemeral key and secret from public key + * @param curve Elliptic curve object + * @param Q Recipient public key + * @returns Returns public part of ephemeral key and generated ephemeral secret + */ + function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; + + /** + * Encrypt and wrap a session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param m Value derived from session key (RFC 6637) + * @param Q Recipient public key + * @param fingerprint Recipient fingerprint + * @returns Returns public part of ephemeral key and encoded session key + */ + function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; + + /** + * Generate ECDHE secret from private key and public part of ephemeral key + * @param curve Elliptic curve object + * @param V Public part of ephemeral key + * @param d Recipient private key + * @returns Generated ephemeral secret + */ + function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; + + /** + * Decrypt and unwrap the value derived from session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param V Public part of ephemeral key + * @param C Encrypted and wrapped value derived from session key + * @param d Recipient private key + * @param fingerprint Recipient fingerprint + * @returns Value derived from session + */ + function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; + } + + namespace ecdsa { + /** + * Sign a message using the provided key + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign the message + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; + + /** + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns + */ + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace eddsa { + /** + * Sign a message using the provided keygit + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; + + /** + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify the message + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns + */ + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace key { + class KeyPair { + } + } + } + + namespace prime { + /** + * Probabilistic random number generator + * @param bits Bit length of the prime + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns BN + */ + function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; + + /** + * Probabilistic primality testing + * @param n Number to test + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns + */ + function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + + /** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n === 1. + * @param n Number to test + * @param b Optional Fermat test base + * @returns + */ + function fermat(n: BN, b: Integer): boolean; + + /** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n Number to test + * @param k Optional number of iterations of Miller-Rabin test + * @param rand Optional function to generate potential witnesses + * @returns + */ + function millerRabin(n: BN, k: Integer, rand: Function): boolean; + } + + namespace rsa { + /** + * Create signature + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @returns RSA Signature + */ + function sign(m: BN, n: BN, e: BN, d: BN): BN; + + /** + * Verify signature + * @param s signature + * @param n RSA public modulus + * @param e RSA public exponent + * @returns + */ + function verify(s: BN, n: BN, e: BN): BN; + + /** + * Encrypt message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @returns RSA Ciphertext + */ + function encrypt(m: BN, n: BN, e: BN): BN; + + /** + * Decrypt RSA message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @param p RSA private prime p + * @param q RSA private prime q + * @param u RSA private inverse of prime q + * @returns RSA Plaintext + */ + function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; + + /** + * Generate a new random private key B bits long with public exponent E. + * When possible, webCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param B RSA bit length + * @param E RSA public exponent in hex string + * @returns RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = q ** -1 mod p + */ + function generate(B: Integer, E: string): object; + } + } + + namespace random { + /** + * Retrieve secure random byte array of the specified length + * @param length Length in bytes to generate + * @returns Random byte array + */ + function getRandomBytes(length: Integer): Uint8Array; + + /** + * Create a secure random MPI that is greater than or equal to min and less than max. + * @param min Lower bound, included + * @param max Upper bound, excluded + * @returns Random MPI + */ + function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; + + /** + * Buffer for secure random numbers + */ + function RandomBuffer(): void; + } + + namespace signature { + /** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param msg_MPIs Algorithm-specific signature parameters + * @param pub_MPIs Algorithm-specific public key parameters + * @param data Data for which the signature was created + * @param hashed The hashed data + * @returns True if signature is valid + */ + function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; + + /** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param key_params Algorithm-specific public and private key parameters + * @param data Data to be signed + * @param hashed The hashed data + * @returns Signature + */ + function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; + } } - namespace random { - /** Create a secure random big integer of bits length - @param bits Bit length of the MPI to create - */ - function getRandomBigInteger(bits: number): number; + namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; - /** Retrieve secure random byte string of the specified length - @param length Length in bytes to generate - */ - function getRandomBytes(length: number): string; + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; + } - /** Helper routine which calls platform specific crypto random generator - @param buf - */ - function getRandomValues(buf: Uint8Array): void; + namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; + } - /** Return a secure random number in the specified range - @param from Min of the random number - @param to Max of the random number (max 32bit) + namespace encoding { + namespace armor { + /** + * Add additional information to the armor version of an OpenPGP binary + * packet block. + * @author Alex + * @version 2011-12-16 + * @param customComment (optional) additional comment to add to the armored string + * @returns The header information + */ + function addheader(customComment: string): string; + + /** + * Calculates a checksum over the given data and returns it base64 encoded + * @param data Data to create a CRC-24 checksum for + * @returns Base64 encoded checksum + */ + function getCheckSum(data: string | ReadableStream): string | ReadableStream; + + /** + * Internal function to calculate a CRC-24 checksum over a given string (data) + * @param data Data to create a CRC-24 checksum for + * @returns The CRC-24 checksum + */ + function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Splits a message into two parts, the body and the checksum. This is an internal function + * @param text OpenPGP armored message part + * @returns An object with attribute "body" containing the body + * and an attribute "checksum" containing the checksum. + */ + function splitChecksum(text: string): object; + + /** + * DeArmor an OpenPGP armored message; verify the checksum and return + * the encoded bytes + * @param text OpenPGP armored message + * @returns An object with attribute "text" containing the message text, + * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type + */ + function dearmor(text: string): Promise; + + /** + * Armor an OpenPGP binary packet block + * @param messagetype type of the message + * @param body + * @param partindex + * @param parttotal + * @param customComment (optional) additional comment to add to the armored string + * @returns Armored text + */ + function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; + } + + namespace base64 { + /** + * Convert binary array to radix-64 + * @param t Uint8Array to convert + * @param u if true, output is URL-safe + * @returns radix-64 version of input string + */ + function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; + + /** + * Convert radix-64 to binary array + * @param t radix-64 string to convert + * @param u if true, input is interpreted as URL-safe + * @returns binary array version of input string + */ + function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; + } + } + + + + namespace enums { + /** + * Maps curve names under various standards to one + * @see */ - function getSecureRandom(from: number, to: number): number; + type curve = "p256" | "p384" | "p251" | "secp256k1" | "ed25519" | "curve25519" | "brainpoolP256r1" | "brainpoolP384r1" | "brainpoolP512r1"; + + /** + * A string to key specifier type + */ + enum s2k { + simple = 0, + salted = 1, + iterated = 3, + gnu = 101, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} + */ + enum publicKey { + /** + * RSA (Encrypt or Sign) [HAC] + */ + rsa_encrypt_sign = 1, + /** + * RSA (Encrypt only) [HAC] + */ + rsa_encrypt = 2, + /** + * RSA (Sign only) [HAC] + */ + rsa_sign = 3, + /** + * Elgamal (Encrypt only) [ELGAMAL] [HAC] + */ + elgamal = 16, + /** + * DSA (Sign only) [FIPS186] [HAC] + */ + dsa = 17, + /** + * ECDH (Encrypt only) [RFC6637] + */ + ecdh = 18, + /** + * ECDSA (Sign only) [RFC6637] + */ + ecdsa = 19, + /** + * EdDSA (Sign only) + * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] + */ + eddsa = 22, + /** + * Reserved for AEDH + */ + aedh = 23, + /** + * Reserved for AEDSA + */ + aedsa = 24, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + */ + enum symmetric { + plaintext = 0, + /** + * Not implemented! + */ + idea = 1, + "3des" = 2, + tripledes = 2, + cast5 = 3, + blowfish = 4, + aes128 = 7, + aes192 = 8, + aes256 = 9, + twofish = 10, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + */ + enum compression { + uncompressed = 0, + /** + * RFC1951 + */ + zip = 1, + /** + * RFC1950 + */ + zlib = 2, + bzip2 = 3, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + */ + enum hash { + md5 = 1, + sha1 = 2, + ripemd = 3, + sha256 = 8, + sha384 = 9, + sha512 = 10, + sha224 = 11, + } + + /** + * A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + */ + enum webHash { + "SHA-1" = 2, + "SHA-256" = 8, + "SHA-384" = 9, + "SHA-512" = 10, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} + */ + enum aead { + eax = 1, + ocb = 2, + experimental_gcm = 100, + } + + /** + * A list of packet types and numeric tags associated with them. + */ + enum packet { + publicKeyEncryptedSessionKey = 1, + signature = 2, + symEncryptedSessionKey = 3, + onePassSignature = 4, + secretKey = 5, + publicKey = 6, + secretSubkey = 7, + compressed = 8, + symmetricallyEncrypted = 9, + marker = 10, + literal = 11, + trust = 12, + userid = 13, + publicSubkey = 14, + userAttribute = 17, + symEncryptedIntegrityProtected = 18, + modificationDetectionCode = 19, + symEncryptedAEADProtected = 20, + } + + /** + * Data types in the literal packet + */ + enum literal { + /** + * Binary data 'b' + */ + binary = 98, + /** + * Text data 't' + */ + text = 116, + /** + * Utf8 data 'u' + */ + utf8 = 117, + /** + * MIME message body part 'm' + */ + mime = 109, + } + + /** + * One pass signature packet type + */ + enum signature { + /** + * 0x00: Signature of a binary document. + */ + binary = 0, + /** + * 0x01: Signature of a canonical text document. + * Canonicalyzing the document by converting line endings. + */ + text = 1, + /** + * 0x02: Standalone signature. + * This signature is a signature of only its own subpacket contents. + * It is calculated identically to a signature over a zero-lengh + * binary document. Note that it doesn't make sense to have a V3 + * standalone signature. + */ + standalone = 2, + /** + * 0x10: Generic certification of a User ID and Public-Key packet. + * The issuer of this certification does not make any particular + * assertion as to how well the certifier has checked that the owner + * of the key is in fact the person described by the User ID. + */ + cert_generic = 16, + /** + * 0x11: Persona certification of a User ID and Public-Key packet. + * The issuer of this certification has not done any verification of + * the claim that the owner of this key is the User ID specified. + */ + cert_persona = 17, + /** + * 0x12: Casual certification of a User ID and Public-Key packet. + * The issuer of this certification has done some casual + * verification of the claim of identity. + */ + cert_casual = 18, + /** + * 0x13: Positive certification of a User ID and Public-Key packet. + * The issuer of this certification has done substantial + * verification of the claim of identity. + * Most OpenPGP implementations make their "key signatures" as 0x10 + * certifications. Some implementations can issue 0x11-0x13 + * certifications, but few differentiate between the types. + */ + cert_positive = 19, + /** + * 0x30: Certification revocation signature + * This signature revokes an earlier User ID certification signature + * (signature class 0x10 through 0x13) or direct-key signature + * (0x1F). It should be issued by the same key that issued the + * revoked signature or an authorized revocation key. The signature + * is computed over the same data as the certificate that it + * revokes, and should have a later creation date than that + * certificate. + */ + cert_revocation = 48, + /** + * 0x18: Subkey Binding Signature + * This signature is a statement by the top-level signing key that + * indicates that it owns the subkey. This signature is calculated + * directly on the primary key and subkey, and not on any User ID or + * other packets. A signature that binds a signing subkey MUST have + * an Embedded Signature subpacket in this binding signature that + * contains a 0x19 signature made by the signing subkey on the + * primary key and subkey. + */ + subkey_binding = 24, + /** + * 0x19: Primary Key Binding Signature + * This signature is a statement by a signing subkey, indicating + * that it is owned by the primary key and subkey. This signature + * is calculated the same way as a 0x18 signature: directly on the + * primary key and subkey, and not on any User ID or other packets. + * When a signature is made over a key, the hash data starts with the + * octet 0x99, followed by a two-octet length of the key, and then body + * of the key packet. (Note that this is an old-style packet header for + * a key packet with two-octet length.) A subkey binding signature + * (type 0x18) or primary key binding signature (type 0x19) then hashes + * the subkey using the same format as the main key (also using 0x99 as + * the first octet). + */ + key_binding = 25, + /** + * 0x1F: Signature directly on a key + * This signature is calculated directly on a key. It binds the + * information in the Signature subpackets to the key, and is + * appropriate to be used for subpackets that provide information + * about the key, such as the Revocation Key subpacket. It is also + * appropriate for statements that non-self certifiers want to make + * about the key itself, rather than the binding between a key and a + * name. + */ + key = 31, + /** + * 0x20: Key revocation signature + * The signature is calculated directly on the key being revoked. A + * revoked key is not to be used. Only revocation signatures by the + * key being revoked, or by an authorized revocation key, should be + * considered valid revocation signatures.a + */ + key_revocation = 32, + /** + * 0x28: Subkey revocation signature + * The signature is calculated directly on the subkey being revoked. + * A revoked subkey is not to be used. Only revocation signatures + * by the top-level signature key that is bound to this subkey, or + * by an authorized revocation key, should be considered valid + * revocation signatures. + * Key revocation signatures (types 0x20 and 0x28) + * hash only the key being revoked. + */ + subkey_revocation = 40, + /** + * 0x40: Timestamp signature. + * This signature is only meaningful for the timestamp contained in + * it. + */ + timestamp = 64, + /** + * 0x50: Third-Party Confirmation signature. + * This signature is a signature over some other OpenPGP Signature + * packet(s). It is analogous to a notary seal on the signed data. + * A third-party signature SHOULD include Signature Target + * subpacket(s) to give easy identification. Note that we really do + * mean SHOULD. There are plausible uses for this (such as a blind + * party that only sees the signature, not the key or source + * document) that cannot include a target subpacket. + */ + third_party = 80, + } + + /** + * Signature subpacket type + */ + enum signatureSubpacket { + signature_creation_time = 2, + signature_expiration_time = 3, + exportable_certification = 4, + trust_signature = 5, + regular_expression = 6, + revocable = 7, + key_expiration_time = 9, + placeholder_backwards_compatibility = 10, + preferred_symmetric_algorithms = 11, + revocation_key = 12, + issuer = 16, + notation_data = 20, + preferred_hash_algorithms = 21, + preferred_compression_algorithms = 22, + key_server_preferences = 23, + preferred_key_server = 24, + primary_user_id = 25, + policy_uri = 26, + key_flags = 27, + signers_user_id = 28, + reason_for_revocation = 29, + features = 30, + signature_target = 31, + embedded_signature = 32, + issuer_fingerprint = 33, + preferred_aead_algorithms = 34, + } + + /** + * Key flags + */ + enum keyFlags { + /** + * 0x01 - This key may be used to certify other keys. + */ + certify_keys = 1, + /** + * 0x02 - This key may be used to sign data. + */ + sign_data = 2, + /** + * 0x04 - This key may be used to encrypt communications. + */ + encrypt_communication = 4, + /** + * 0x08 - This key may be used to encrypt storage. + */ + encrypt_storage = 8, + /** + * 0x10 - The private component of this key may have been split + * by a secret-sharing mechanism. + */ + split_private_key = 16, + /** + * 0x20 - This key may be used for authentication. + */ + authentication = 32, + /** + * 0x80 - The private component of this key may be in the + * possession of more than one person. + */ + shared_private_key = 128, + } + + /** + * Key status + */ + enum keyStatus { + invalid = 0, + expired = 1, + revoked = 2, + valid = 3, + no_self_cert = 4, + } + + /** + * Armor type + */ + enum armor { + multipart_section = 0, + multipart_last = 1, + signed = 2, + message = 3, + public_key = 4, + private_key = 5, + signature = 6, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} + */ + enum reasonForRevocation { + /** + * No reason specified (key revocations or cert revocations) + */ + no_reason = 0, + /** + * Key is superseded (key revocations) + */ + key_superseded = 1, + /** + * Key material has been comPromised (key revocations) + */ + key_comPromised = 2, + /** + * Key is retired and no longer used (key revocations) + */ + key_retired = 3, + /** + * User ID information is no longer valid (cert revocations) + */ + userid_invalid = 32, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} + */ + enum features { + /** + * 0x01 - Modification Detection (packets 18 and 19) + */ + modification_detection = 1, + /** + * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 + * Symmetric-Key Encrypted Session Key Packets (packet 3) + */ + aead = 2, + /** + * 0x04 - Version 5 Public-Key Packet format and corresponding new + * fingerprint format + */ + v5_keys = 4, + } + + /** + * Asserts validity and converts from string/integer to integer. + */ + function write(): void; + + /** + * Converts from an integer to string. + */ + function read(): void; + } + + namespace hkp { + class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; + } + } + + class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; + } + + namespace key { + /** + * Class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + */ + class Key { + /** + * @param packetlist The packets that form this key + */ + constructor(packetlist: packet.List); + + /** + * Transforms packetlist to structured key data + * @param packetlist The packets that form a key + */ + packetlist2structure(packetlist: packet.List): void; + + /** + * Transforms structured key data to packetlist + * @returns The packets that form a key + */ + toPacketlist(): packet.List; + + /** + * Returns an array containing all public or private subkeys matching keyId; + * If keyId is not present, returns all subkeys. + * @param keyId + * @returns + */ + getSubkeys(keyId: type.keyid.Keyid): any[]; + + /** + * Returns an array containing all public or private keys matching keyId. + * If keyId is not present, returns all keys starting with the primary key. + * @param keyId + * @returns + */ + getKeys(keyId: type.keyid.Keyid): any[]; + + /** + * Returns key IDs of all keys + * @returns + */ + getKeyIds(): any[]; + + /** + * Returns userids + * @returns array of userids + */ + getUserIds(): any[]; + + /** + * Returns true if this is a public key + * @returns + */ + isPublic(): boolean; + + /** + * Returns true if this is a private key + * @returns + */ + isPrivate(): boolean; + + /** + * Returns key as public key (shallow copy) + * @returns new public Key + */ + toPublic(): Key; + + /** + * Returns ASCII armored text of key + * @returns ASCII armor + */ + armor(): ReadableStream; + + /** + * Returns last created key or key by given keyId that is available for signing and verification + * @param keyId, optional + * @param date (optional) use the given date for verification instead of the current time + * @param userId, optional user ID + * @returns key or null if no signing key has been found + */ + getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; + + /** + * Returns last created key or key by given keyId that is available for encryption or decryption + * @param keyId, optional + * @param date, optional + * @param userId, optional + * @returns key or null if no encryption key has been found + */ + getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; + + /** + * Encrypts all secret key and subkey packets matching keyId + * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt + * @param keyId + * @returns + */ + encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; + + /** + * Decrypts all secret key and subkey packets matching keyId + * @param passphrases + * @param keyId + * @returns true if all matching key and subkey packets decrypted successfully + */ + decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; + + /** + * Checks if a signature on a key is revoked + * @param + * @param signature The signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; + + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns The status of the primary key + */ + verifyPrimaryKey(date?: Date, userId?: object): Promise; + + /** + * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. + * When `capabilities` is null, defaults to returning the expiry date of the primary key. + * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + * Returns Infinity if the key doesn't expire. + * @param {encrypt | sign | encrypt_sign} capabilities, optional + * @param keyId, optional + * @param userId, optional user ID + * @returns + */ + getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; + + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns The primary user and the self signature + */ + getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; + + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * If the specified key is a private key and the destination key is public, + * the destination key is transformed to a private key. + * @param key Source key to merge + * @returns + */ + update(key: Key): Promise; + + /** + * Revokes the key + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new key with revocation signature + */ + revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @returns armored revocation certificate + */ + getRevocationCertificate(): Promise; + + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param revocationCertificate armored revocation certificate + * @returns new revoked key + */ + applyRevocationCertificate(revocationCertificate: string): Promise; + + /** + * Signs primary user of key + * @param privateKey decrypted private keys for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns new public key with new certificate signature + */ + signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; + + /** + * Signs all users of key + * @param privateKeys decrypted private keys for signing + * @returns new public key with new certificate signature + */ + signAllUsers(privateKeys: any[]): Promise; + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns List of signer's keyid and validity of signature + */ + verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @returns list of userid, signer's keyid and validity of signature + */ + verifyAllUsers(keys: any[]): Promise>; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param signatures List of signatures + * @param date Use the given date instead of the current time + * @returns The latest valid signature + */ + function getLatestValidSignature(signatures: any[], date: Date): Promise; + + /** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ + class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + } + + /** + * Create signature packet + * @param dataToSign Contains packets to be signed + * @param signingKeyPacket secret key packet for signing + * @param signatureProperties (optional) properties to write on the signature packet before signing + * @param date (optional) override the creationtime of the signature + * @param userId (optional) user ID + * @returns signature packet + */ + function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; + + /** + * Class that represents a subkey packet and the relevant signatures. + */ + class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * Reads an unarmored OpenPGP key list and returns one or multiple key objects + * @param data to be parsed + * @returns result object with key and error arrays + */ + function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; + + interface KeyResult { keys: Array, err: Array | null } + + /** + * Reads an OpenPGP armored text and returns one or multiple key objects + * @param armoredText text to be parsed + * @returns result object with key and error arrays + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * Generates a new OpenPGP key. Supports RSA and ECC keys. + * Primary and subkey will be of same type. + * @param options.keyType To indicate what type of key to make. + * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} + * @param options.numBits number of bits for the key creation. + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param curve (optional) elliptic curve for ECC keys + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns + */ + function generate(options: KeyOptions): Promise; + + /** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param options.privateKey The private key to reformat + * @param options.keyType + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * @returns + */ + function reformat(date: Date, subkeys: any[]): Promise; + + /** + * Checks if a given certificate or binding signature is revoked + * @param primaryKey The primary key packet + * @param dataToVerify The data to check + * @param revocations The revocation signatures to check + * @param signature The certificate or signature to check + * @param key, optional The key packet to check the signature + * @param date Use the given date instead of the current time + * @returns True if the signature revokes the data + */ + function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Check if signature has revocation key sub packet (not supported by OpenPGP.js) + * and throw error if found + * @param signature The certificate or signature to check + * @param keyId Check only certificates or signatures from a certain issuer key ID + */ + function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; + + /** + * Returns the preferred signature hash algorithm of a key + * @param key (optional) the key to get preferences from + * @param keyPacket key packet used for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns + */ + function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + + /** + * Returns the preferred symmetric/aead algorithm for a set of keys + * @param {symmetric | aead} type Type of preference to return + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns Preferred symmetric algorithm + */ + function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + + /** + * Returns whether aead is supported by all keys in the set + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns + */ + function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; + } + + interface revoke_reasonForRevocation { + /** + * optional, flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * optional, string explaining the reason for revocation + */ + string: string; + } + + /** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ + class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + } + + /** + * Class that represents a subkey packet and the relevant signatures. + */ + class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * @see module:keyring/keyring + * @see module:keyring/localstore + */ + namespace keyring { + namespace keyring { + class Keyring { + /** + * Initialization routine for the keyring. + * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods + */ + constructor(storeHandler?: localstore.LocalStore); + + /** + * Calls the storeHandler to load the keys + */ + load(): void; + + /** + * Calls the storeHandler to save the keys + */ + store(): void; + + /** + * Clear the keyring - erase all the keys + */ + clear(): void; + + /** + * Searches the keyring for keys having the specified key id + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @param deep if true search also in subkeys + * @returns keys found or null + */ + getKeysForId(keyId: string, deep: boolean): any[] | null; + + /** + * Removes keys having the specified key id from the keyring + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @returns keys found or null + */ + removeKeysForId(keyId: string): any[] | null; + + /** + * Get all public and private keys + * @returns all keys + */ + getAllKeys(): any[]; + } + + /** + * Array of keys + * @param keys The keys to store in this array + */ + function KeyArray(keys: any[]): void; + } + + namespace localstore { + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; + } + } + } + + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; + } + + namespace message { + /** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + */ + class Message { + packets: packet.List; + + /** + * @param packetlist The packets that form this message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + constructor(packetlist: packet.List); + + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns array of keyid objects + */ + getEncryptionKeyIds(): any[]; + + /** + * Returns the key IDs of the keys that signed the message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; + + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param streaming (optional) whether to process data as a stream + * @returns new message with decrypted content + */ + decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; + + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @returns array of object with potential sessionKey, algorithm pairs + */ + decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; + + /** + * Get literal data that is the body of the message + * @returns literal body of the message as Uint8Array + */ + getLiteralData(): Uint8Array | null; + + /** + * Get filename from literal data packet + * @returns filename of literal data packet as string + */ + getFilename(): string | null; + + /** + * Get literal data as text + * @returns literal body of the message interpreted as text + */ + getText(): string | null; + + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param keys (optional) public key(s) for message encryption + * @param passwords (optional) password(s) for message encryption + * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the creation date of the literal package + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param streaming (optional) whether to process data as a stream + * @returns new message with encrypted content + */ + encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; + + /** + * Sign the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to add to the message + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new message with signed content + */ + sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param compression compression algorithm to be used + * @returns new message with compressed content + */ + compress(compression: enums.compression): Message; + + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Verify message signatures + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param streaming (optional) whether to process data as a stream + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date?: Date, streaming?: boolean): Promise>; + + /** + * Verify detached message signature + * @param keys array of keys to verify signatures + * @param signature + * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; + + /** + * Unwrap compressed message + * @returns message Content of compressed message + */ + unwrapCompressed(): Message; + + /** + * Append signature to unencrypted message object + * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature + */ + appendSignature(detachedSignature: string | Uint8Array): void; + + /** + * Returns ASCII armored text of message + * @returns ASCII armor + */ + armor(): ReadableStream; + } + + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param sessionKey session key for encryption + * @param symAlgo session key algorithm + * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) public key(s) for message encryption + * @param passwords (optional) for message encryption + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @returns new message with encrypted content + */ + function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + + /** + * Create signature packets for the message + * @param literalDataPacket the literal data packet to sign + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to append + * @param date (optional) override the creationtime of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns list of signature packets + */ + function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Create object containing signer's keyid and validity of signature + * @param signature signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * Create list of objects containing signer's keyid and validity of signature + * @param signatureList array of signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * reads an OpenPGP armored message and returns a message object + * @param armoredText text to be parsed + * @returns new message object + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * reads an OpenPGP message as byte array and returns a message object + * @param input binary message + * @param fromStream whether the message was created from a Stream + * @returns new message object + */ + function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + + /** + * creates new message object from text + * @param text + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; + + /** + * creates new message object from binary data + * @param bytes + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; + } + + interface revokeKey_reasonForRevocation { + /** + * (optional) flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * (optional) string explaining the reason for revocation + */ + string: string; + } + + /** + * @see module:packet/all_packets + * @see module:packet/clone + * @see module:packet.List + */ + namespace packet { + /** + * Allocate a new packet + * @param tag property name from {@link module:enums.packet} + * @returns new packet object with type based on tag + */ + function newPacketFromTag(tag: string): object; + + /** + * Allocate a new packet from structured packet clone + * @see + * @param packetClone packet clone + * @returns new packet object with data from packet clone + */ + function fromStructuredClone(packetClone: object): object; + + class Compressed { + /** + * Implementation of the Compressed Data Packet (Tag 8) + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * List of packets + */ + packets: List; + + /** + * Compression algorithm + * @type {compression} + */ + algorithm: any; + + /** + * Compressed packet data + */ + compressed: Uint8Array | ReadableStream; + + /** + * Parsing function for the packet. + * @param bytes Payload of a tag 8 packet + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Return the compressed packet. + * @returns binary compressed packet + */ + write(): Uint8Array | ReadableStream; + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + */ + decompress(): void; + + /** + * Compress the packet data (member decompressedData) + */ + compress(): void; + } + + class Literal { + /** + * Implementation of the Literal Data Packet (Tag 11) + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. + * @param date the creation date of the literal package + */ + constructor(date: Date); + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param text Any native javascript string + * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes + */ + setText(text: string | ReadableStream, format: any): void; + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns literal data as text + */ + getText(clone: boolean): string | ReadableStream; + + /** + * Set the packet data to value represented by the provided string of bytes. + * @param bytes The string of bytes + * @param {utf8 | binary | text | mime} format The format of the string of bytes + */ + setBytes(bytes: Uint8Array | ReadableStream, format: any): void; + + /** + * Get the byte sequence representing the literal packet data + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns A sequence of bytes + */ + getBytes(clone: boolean): Uint8Array | ReadableStream; + + /** + * Sets the filename of the literal packet data + * @param filename Any native javascript string + */ + setFilename(filename: string): void; + + /** + * Get the filename of the literal packet data + * @returns filename + */ + getFilename(): string; + + /** + * Parsing function for a literal data packet (tag 11). + * @param input Payload of a tag 11 packet + * @returns object representation + */ + read(input: Uint8Array | ReadableStream): Literal; + + /** + * Creates a string representation of the packet + * @returns Uint8Array representation of the packet + */ + write(): Uint8Array | ReadableStream; + } + + class Marker { + /** + * Implementation of the strange "Marker packet" (Tag 10) + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * Such a packet MUST be ignored when received. + */ + constructor(); + + /** + * Parsing function for a literal data packet (tag 10). + * @param input Payload of a tag 10 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: string, position: Integer, len: Integer): Marker; + } + + class OnePassSignature { + /** + * Implementation of the One-Pass Signature Packets (Tag 4) + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * A one-octet version number. The current version is 3. + */ + version: any; + + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + */ + signatureType: any; + + /** + * A one-octet number describing the hash algorithm used. + * @see + */ + hashAlgorithm: any; + + /** + * A one-octet number describing the public-key algorithm used. + * @see + */ + publicKeyAlgorithm: any; + + /** + * An eight-octet number holding the Key ID of the signing key. + */ + issuerKeyId: any; + + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + flags: any; + + /** + * parsing function for a one-pass signature packet (tag 4). + * @param bytes payload of a tag 4 packet + * @returns object representation + */ + read(bytes: Uint8Array): OnePassSignature; + + /** + * creates a string representation of a one-pass signature packet + * @returns a Uint8Array representation of a one-pass signature packet + */ + write(): Uint8Array; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class List { + /** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + */ + constructor(); + + /** + * The number of packets contained within the list. + */ + readonly length: Integer; + + /** + * Reads a stream of binary data and interprents it as a list of packets. + * @param A Uint8Array of bytes. + */ + read(A: Uint8Array | ReadableStream): void; + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns A Uint8Array containing valid openpgp packets. + */ + write(): Uint8Array; + + /** + * Adds a packet to the list. This is the only supported method of doing so; + * writing to packetlist[i] directly will result in an error. + * @param packet Packet to push + */ + push(packet: object): void; + + /** + * Creates a new PacketList with all packets from the given types + */ + filterByTag(): void; + + /** + * Traverses packet tree and returns first matching packet + * @param type The packet type + * @returns + */ + findPacket(type: enums.packet): List | undefined; + + /** + * Returns array of found indices by tag + */ + indexOfTag(): void; + + /** + * Concatenates packetlist or array of packets + */ + concat(): void; + + /** + * Allocate a new packetlist from structured packetlist clone + * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} + * @param packetClone packetlist clone + * @returns new packetlist object with data from packetlist clone + */ + static fromStructuredClone(packetClone: object): object; + } + + class PublicKey { + /** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicKeyEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + encrypted: any[]; + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey + + /** + * Create a string representation of a tag 1 packet + * @returns The Uint8Array representation + */ + write(): Uint8Array; + + /** + * Encrypt session key packet + * @param key Public key + * @returns + */ + encrypt(key: PublicKey): Promise; + + /** + * Decrypts the session key (only for public key encrypted session key + * packets (tag 1) + * @param key Private key with secret params unlocked + * @returns + */ + decrypt(key: SecretKey): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicSubkey { + /** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SecretKey { + /** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class SecretSubkey { + /** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class Signature { + /** + * Implementation of the Signature Packet (Tag 2) + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + * @param date the creation date of the signature + */ + constructor(date: Date); + + /** + * parsing function for a signature packet (tag 2). + * @param bytes payload of a tag 2 packet + * @param position position to start reading from the bytes string + * @param len length of the packet or the remaining length of bytes at position + * @returns object representation + */ + read(bytes: string, position: Integer, len: Integer): Signature; + + /** + * Signs provided data. This needs to be done prior to serialization. + * @param key private key used to sign the message. + * @param data Contains packets to be signed. + * @returns + */ + sign(key: SecretKey, data: object): Promise; + + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_hashed_sub_packets(): Uint8Array; + + /** + * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_unhashed_sub_packets(): Uint8Array; + + /** + * verifys the signature packet. Note: not signature types are implemented + * @param key the public key to verify the signature + * @param signatureType expected signature type + * @param data data which on the signature applies + * @returns True if message is verified, else false. + */ + verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; + + /** + * Verifies signature expiration date + * @param date (optional) use the given date for verification instead of the current time + * @returns true if expired + */ + isExpired(date: Date): boolean; + + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns expiration time + */ + getExpirationTime(): Date; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymEncryptedAEADProtected { + /** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ + constructor(); + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param bytes + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns The encrypted payload + */ + write(): Uint8Array | ReadableStream; + + /** + * Decrypt the encrypted payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; + + /** + * Encrypt the packet list payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; + + /** + * En/decrypt the payload. + * @param {encrypt | decrypt} fn Whether to encrypt or decrypt + * @param key The session key used to en/decrypt the payload + * @param data The data to en/decrypt + * @param streaming Whether the top-level function will return a stream + * @returns + */ + crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; + } + + class SymEncryptedIntegrityProtected { + /** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ + constructor(); + + /** + * The encrypted payload. + */ + encrypted: any; + + /** + * If after decrypting the packet this is set to true, + * a modification has been detected and thus the contents + * should be discarded. + */ + modification: boolean; + + /** + * Encrypt the payload in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to set this.encrypted to a stream + * @returns + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + + /** + * Decrypts the encrypted data contained in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to read this.encrypted as a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + } + + class SymEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; + + /** + * Decrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Encrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymmetricallyEncrypted { + /** + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Decrypted packets contained within. + */ + packets: List; + + /** + * When true, decrypt fails if message is not integrity protected + * @see module:config.ignore_mdc_error + */ + ignore_mdc_error: any; + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + } + + class Trust { + /** + * Implementation of the Trust Packet (Tag 12) + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ + constructor(); + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + * @param byptes payload of a tag 12 packet + */ + read(byptes: string): void; + } + + class UserAttribute { + /** + * Implementation of the User Attribute Packet (Tag 17) + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ + constructor(); + + /** + * parsing function for a user attribute packet (tag 17). + * @param input payload of a tag 17 packet + */ + read(input: Uint8Array): void; + + /** + * Creates a binary representation of the user attribute packet + * @returns string representation + */ + write(): Uint8Array; + + /** + * Compare for equality + * @param usrAttr + * @returns true if equal + */ + equals(usrAttr: UserAttribute): boolean; + } + + class Userid { + /** + * Implementation of the User ID Packet (Tag 13) + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ + constructor(); + + /** + * A string containing the user id. Usually in the form + * John Doe + */ + userid: string; + + /** + * Parsing function for a user id packet (tag 13). + * @param input payload of a tag 13 packet + */ + read(input: Uint8Array): void; + + /** + * Parse userid string, e.g. 'John Doe ' + */ + parse(): void; + + /** + * Creates a binary representation of the user id packet + * @returns binary representation + */ + write(): Uint8Array; + + /** + * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } + */ + format(): void; + } + + namespace all_packets { + /** + * @see module:packet.Compressed + */ + var Compressed: any; + + /** + * @see module:packet.SymEncryptedIntegrityProtected + */ + var SymEncryptedIntegrityProtected: any; + + /** + * @see module:packet.SymEncryptedAEADProtected + */ + var SymEncryptedAEADProtected: any; + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + var PublicKeyEncryptedSessionKey: any; + + /** + * @see module:packet.SymEncryptedSessionKey + */ + var SymEncryptedSessionKey: any; + + /** + * @see module:packet.Literal + */ + var Literal: any; + + /** + * @see module:packet.PublicKey + */ + var PublicKey: any; + + /** + * @see module:packet.SymmetricallyEncrypted + */ + var SymmetricallyEncrypted: any; + + /** + * @see module:packet.Marker + */ + var Marker: any; + + /** + * @see module:packet.PublicSubkey + */ + var PublicSubkey: any; + + /** + * @see module:packet.UserAttribute + */ + var UserAttribute: any; + + /** + * @see module:packet.OnePassSignature + */ + var OnePassSignature: any; + + /** + * @see module:packet.SecretKey + */ + var SecretKey: any; + + /** + * @see module:packet.Userid + */ + var Userid: any; + + /** + * @see module:packet.SecretSubkey + */ + var SecretSubkey: any; + + /** + * @see module:packet.Signature + */ + var Signature: any; + + /** + * @see module:packet.Trust + */ + var Trust: any; + } + + namespace clone { + /** + * Create a packetlist from the correspoding object types. + * @param options the object passed to and from the web worker + * @returns a mutated version of the options optject + */ + function clonePackets(options: object): object; + + /** + * Creates an object with the correct prototype from a corresponding packetlist. + * @param options the object passed to and from the web worker + * @param method the public api function name to be delegated to the worker + * @returns a mutated version of the options optject + */ + function parseClonedPackets(options: object, method: string): object; + } + + namespace packet { + /** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * @param length The length to encode + * @returns String with openpgp length representation + */ + function writeSimpleLength(length: Integer): Uint8Array; + + /** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeHeader(tag_type: Integer, length: Integer): string; + + /** + * Writes a packet header Version 3 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeOldHeader(tag_type: Integer, length: Integer): string; + + /** + * Whether the packet type supports partial lengths per RFC4880 + * @param tag_type Tag type + * @returns String of the header + */ + function supportsStreaming(tag_type: Integer): boolean; + + /** + * Generic static Packet Parser function + * @param input Input stream as string + * @param callback Function to call with the parsed packet + * @returns Returns false if the stream was empty and parsing is done, and true otherwise. + */ + function read(input: Uint8Array | ReadableStream, callback: Function): boolean; + } + } + + + namespace polyfills { } namespace signature { - /** Create a signature on data using the specified algorithm - @param hash_algo hash Algorithm to use - @param algo Asymmetric cipher algorithm to use - @param publicMPIs Public key multiprecision integers of the private key - @param secretMPIs Private key multiprecision integers which is used to sign the data - @param data Data to be signed - */ - function sign(hash_algo: enums.hash, algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: string): Mpi; + /** + * Class that represents an OpenPGP signature. + */ + class Signature { + /** + * @param packetlist The signature packets + */ + constructor(packetlist: packet.List); + + /** + * Returns ASCII armored text of signature + * @returns ASCII armor + */ + armor(): ReadableStream; + } /** - @param algo public Key algorithm - @param hash_algo Hash algorithm - @param msg_MPIs Signature multiprecision integers - @param publickey_MPIs Public key multiprecision integers - @param data Data on where the signature was computed on + * reads an OpenPGP armored signature and returns a signature object + * @param armoredText text to be parsed + * @returns new signature object + */ + function readArmored(armoredText: string | ReadableStream): Signature; + + /** + * reads an OpenPGP signature as byte array and returns a signature object + * @param input binary signature + * @returns new signature object + */ + function read(input: Uint8Array | ReadableStream): Signature; + } + + namespace type { + /** + * Encoded symmetric key for ECDH + */ + namespace ecdh_symkey { + class ECDHSymmetricKey { + constructor(); + + /** + * Read an ECDHSymmetricKey from an Uint8Array + * @param input Where to read the encoded symmetric key from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns An array containing the value + */ + write(): Uint8Array; + } + } + + /** + * Implementation of type KDF parameters + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + */ + namespace kdf_params { + class KDFParams { + /** + * @param hash Hash algorithm + * @param cipher Symmetric algorithm + */ + constructor(hash: enums.hash, cipher: enums.symmetric); + + /** + * Read KDFParams from an Uint8Array + * @param input Where to read the KDFParams from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Write KDFParams to an Uint8Array + * @returns Array with the KDFParams value + */ + write(): Uint8Array; + } + } + + /** + * Implementation of type key id + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ + namespace keyid { + class Keyid { + constructor(); + + /** + * Parsing method for a key id + * @param input Input to read the key id from + */ + read(input: Uint8Array): void; + + /** + * Checks equality of Key ID's + * @param keyid + * @param matchWildcard Indicates whether to check if either keyid is a wildcard + */ + equals(keyid: Keyid, matchWildcard: boolean): void; + } + } + + /** + * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) + * Multiprecision integers (also called MPIs) are unsigned integers used + * to hold large integers such as the ones used in cryptographic + * calculations. + * An MPI consists of two pieces: a two-octet scalar that is the length + * of the MPI in bits followed by a string of octets that contain the + * actual integer. + */ + namespace mpi { + class MPI { + constructor(); + + /** + * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). + * @param input Payload of MPI data + * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian + * @returns Length of data read + */ + read(input: Uint8Array, endian: string): Integer; + + /** + * Converts the mpi object to a bytes as specified in + * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} + * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian + * @param length Length of the data part of the MPI + * @returns mpi Byte representation + */ + write(endian: string, length: Integer): Uint8Array; + } + } + + /** + * Wrapper to an OID value + * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: + * The sequence of octets in the third column is the result of applying + * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier + * with subsequent truncation. The truncation removes the two fields of + * encoded Object Identifier. The first omitted field is one octet + * representing the Object Identifier tag, and the second omitted field + * is the length of the Object Identifier body. For example, the + * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A + * 86 48 CE 3D 03 01 07", from which the first entry in the table above + * is constructed by omitting the first two octets. Only the truncated + * sequence of octets is the valid representation of a curve OID. + */ + namespace oid { + class OID { + constructor(); + + /** + * Method to read an OID object + * @param input Where to read the OID from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Serialize an OID object + * @returns Array with the serialized value the OID + */ + write(): Uint8Array; + + /** + * Serialize an OID object as a hex string + * @returns String with the hex value of the OID + */ + toHex(): string; + + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns String with the canonical name of the curve + */ + getName(): string; + } + } + + /** + * Implementation of the String-to-key specifier + * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: + * String-to-key (S2K) specifiers are used to convert passphrase strings + * into symmetric-key encryption/decryption keys. They are used in two + * places, currently: to encrypt the secret part of private keys in the + * private keyring, and to convert passphrases to encryption keys for + * symmetrically encrypted messages. + */ + namespace s2k { + class S2K { + constructor(); + + algorithm: enums.hash; + + type: enums.s2k; + + c: Integer; + + /** + * Eight bytes of salt in a binary string. + */ + salt: string; + + /** + * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param input Payload of string-to-key specifier + * @returns Actual length of the object + */ + read(input: string): Integer; + + /** + * Serializes s2k information + * @returns binary representation of s2k + */ + write(): Uint8Array; + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param passphrase Passphrase containing user input + * @returns Produced key with a length corresponding to + * hashAlgorithm hash length + */ + produce_key(passphrase: string): Uint8Array; + } + } + } + + /** + * This object contains utility functions + */ + namespace util { + /** + * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) + * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage + * Also, convert ReadableStreams to MessagePorts + * @param obj the options object to be passed to the web worker + * @returns an array of binary data to be passed + */ + function getTransferables(obj: object): any[]; + + /** + * Convert MessagePorts back to ReadableStreams + * @param obj + * @returns + */ + function restoreStreams(obj: object): object; + + /** + * Create hex string from a binary + * @param str String to convert + * @returns String containing the hexadecimal values + */ + function str_to_hex(str: string): string; + + /** + * Create binary string from a hex encoded string + * @param str Hex string to convert + * @returns + */ + function hex_to_str(str: string): string; + + /** + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * Note: the output is **not** an MPI object. + * @see + * @see + * @param bin An array of 8-bit integers to convert + * @returns MPI-formatted Uint8Array + */ + function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; + + /** + * Convert a Base-64 encoded string an array of 8-bit integer + * Note: accepts both Radix-64 and URL-safe strings + * @param base64 Base-64 encoded string to convert + * @returns An array of 8-bit integers + */ + function b64_to_Uint8Array(base64: string): Uint8Array; + + /** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param bytes An array of 8-bit integers to convert + * @param url If true, output is URL-safe + * @returns Base-64 encoded string + */ + function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; + + /** + * Convert a hex string to an array of 8-bit integers + * @param hex A hex string to convert + * @returns An array of 8-bit integers + */ + function hex_to_Uint8Array(hex: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a hex string + * @param bytes Array of 8-bit integers to convert + * @returns Hexadecimal representation of the array + */ + function Uint8Array_to_hex(bytes: Uint8Array): string; + + /** + * Convert a string to an array of 8-bit integers + * @param str String to convert + * @returns An array of 8-bit integers + */ + function str_to_Uint8Array(str: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a string + * @param bytes An array of 8-bit integers to convert + * @returns String representation of the array + */ + function Uint8Array_to_str(bytes: Uint8Array): string; + + /** + * Convert a native javascript string to a Uint8Array of utf8 bytes + * @param str The string to convert + * @returns A valid squence of utf8 bytes + */ + function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Convert a Uint8Array of utf8 bytes to a native javascript string + * @param utf8 A valid squence of utf8 bytes + * @returns A native javascript string + */ + function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; + + /** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param Array of Uint8Arrays/Strings/Streams to concatenate + * @returns Concatenated array + */ + var concat: any; + + /** + * Concat Uint8Arrays + * @param Array of Uint8Arrays to concatenate + * @returns Concatenated array + */ + var concatUint8Array: any; + + /** + * Check Uint8Array equality + * @param first array + * @param second array + * @returns equality + */ + function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; + + /** + * Calculates a 16bit sum of a Uint8Array by adding each character + * codes modulus 65535 + * @param Uint8Array to create a sum of + * @returns 2 bytes containing the sum of all charcodes % 65535 + */ + function write_checksum(Uint8Array: Uint8Array): Uint8Array; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexarray_dump(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexstr_dump(str: string): void; + + /** + * Helper function to print a debug error. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_error(str: string): void; + + /** + * Read a stream to the end and print it to the console when it's closed. + * @param str String of the debug message + * @param input Stream to print + * @param concat Function to concatenate chunks of the stream (defaults to util.concat). + */ + function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; + + /** + * If S[1] == 0, then double(S) == (S[2..128] || 0); + * otherwise, double(S) == (S[2..128] || 0) xor + * (zeros(120) || 10000111). + * Both OCB and EAX (through CMAC) require this function to be constant-time. + * @param data + */ + /* Illegal function name 'double' can't be used here + function double(data: Uint8Array): void; */ - function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: Array, publickey_MPIs: Array, data: string): boolean; - } -} -export namespace enums { - enum armor { - multipart_section, - multipart_last, - signed, - message, - public_key, - private_key + /** + * Shift a Uint8Array to the right by n bits + * @param array The array to shift + * @param bits Amount of bits to shift (MUST be smaller + * than 8) + * @returns Resulting array. + */ + function shiftRight(array: Uint8Array, bits: Integer): string; + + /** + * Get native Web Cryptography api, only the current version of the spec. + * The default configuration is to use the api when available. But it can + * be deactivated with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCrypto(): object; + + /** + * Get native Web Cryptography api for all browsers, including legacy + * implementations of the spec e.g IE11 and Safari 8/9. The default + * configuration is to use the api when available. But it can be deactivated + * with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCryptoAll(): object; + + /** + * Detect Node.js runtime. + */ + function detectNode(): void; + + /** + * Get native Node.js module + * @param The module to require + * @returns The required module or 'undefined' + */ + function nodeRequire(The: string): object; + + /** + * Get native Node.js crypto api. The default configuration is to use + * the api when available. But it can also be deactivated with config.use_native + * @returns The crypto module or 'undefined' + */ + function getNodeCrypto(): object; + + /** + * Get native Node.js Buffer constructor. This should be used since + * Buffer is not available under browserify. + * @returns The Buffer constructor or 'undefined' + */ + function getNodeBuffer(): Function; + + /** + * Format user id for internal use. + */ + function formatUserId(): void; + + /** + * Parse user id. + */ + function parseUserId(): void; + + /** + * Normalize line endings to \r\n + */ + function canonicalizeEOL(): void; + + /** + * Convert line endings from canonicalized \r\n to native \n + */ + function nativeEOL(): void; + + /** + * Remove trailing spaces and tabs from each line + */ + function removeTrailingSpaces(): void; + + /** + * Encode input buffer using Z-Base32 encoding. + * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 + * @param data The binary data to encode + * @returns Binary data encoded using Z-Base32 + */ + function encodeZBase32(data: Uint8Array): string; } - enum compression { - uncompressed, - zip, - zlib, - bzip2 + namespace wkd { + class WKD { + /** + * Initialize the WKD client + */ + constructor(); + + /** + * Search for a public key using Web Key Directory protocol. + * @param options.email User's email. + * @param options.rawBytes Returns Uint8Array instead of parsed key. + * @returns The public key. + */ + lookup(): Promise, err: Array | null }>; + } } - enum hash { - md5, - sha1, - ripemd, - sha256, - sha384, - sha512, - sha224 - } - - enum packet { - publicKeyEncryptedSessionKey, - signature, - symEncryptedSessionKey, - onePassSignature, - secretKey, - publicKey, - secretSubkey, - compressed, - symmetricallyEncrypted, - marker, - literal, - trust, - userid, - publicSubkey, - userAttribute, - symEncryptedIntegrityProtected, - modificationDetectionCode, - } - - enum publicKey { - rsa_encrypt_sign, - rsa_encrypt, - rsa_sign, - elgamal, - dsa - } - - enum symmetric { - plaintext, - idea, - tripledes, - cast5, - blowfish, - aes128, - aes192, - aes256, - twofish - } - - enum keyStatus { - invalid, - expired, - revoked, - valid, - no_self_cert - } - - enum reasonForRevocation { - no_reason, - key_superseded, - key_compromised, - key_retired, - userid_invalid - } -} - -export namespace key { - interface KeyResult { - keys: Array, - err: Array - } - - /** Class that represents an OpenPGP key. Must contain a primary key. Can contain additional subkeys, signatures, user ids, user attributes. + namespace worker { + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/worker */ - interface Key { - armor(): string, - decrypt(passphrase: string): boolean; - getExpirationTime(): Date; - getKeyIds(): Array; - getPreferredHashAlgorithm(): string; - getPrimaryUser(): any; - getUserIds(): Array; - isPrivate(): boolean; - isPublic(): boolean; - primaryKey: packet.PublicKey; - toPublic(): Key; - update(key: Key): void; - verifyPrimaryKey(): enums.keyStatus; + namespace async_proxy { + class AsyncProxy { + /** + * Initializes a new proxy and loads the web worker + * @param path The path to the worker or 'openpgp.worker.js' by default + * @param n number of workers to initialize if path given + * @param config config The worker configuration + * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' + */ + constructor(path: string, n: number, config: object, worker: any[]); + + /** + * Message handling + */ + handleMessage(): void; + + /** + * Get new request ID + * @returns New unique request ID + */ + getID(): Integer; + + /** + * Send message to worker with random data + * @param size Number of bytes to send + */ + seedRandom(size: Integer): void; + + /** + * Terminates the workers + */ + terminate(): void; + + /** + * Generic proxy function that handles all commands from the public api. + * @param method the public api function to be delegated to the worker thread + * @param options the api function's options + * @returns see the corresponding public api functions for their return types + */ + delegate(method: string, options: object): Promise; + } + } + + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/async_proxy + */ + namespace worker { + /** + * Handle random buffer exhaustion by requesting more random bytes from the main window + * @returns Empty Promise whose resolution indicates that the buffer has been refilled + */ + function randomCallback(): Promise; + + /** + * Set config from main context to worker context. + * @param config The openpgp configuration + */ + function configure(config: object): void; + + /** + * Seed the library with entropy gathered window.crypto.getRandomValues + * as this api is only avalible in the main window. + * @param buffer Some random bytes + */ + function seedRandom(buffer: any[]): void; + + /** + * Generic proxy function that handles all commands from the public api. + * @param method The public api function to be delegated to the worker thread + * @param options The api function's options + */ + function delegate(method: string, options: object): void; + + /** + * Respond to the main window. + * @param event Contains event type and data + */ + function response(event: object): void; + } } - /** Generates a new OpenPGP key. Currently only supports RSA keys. Primary and subkey will be of same type. - - @param options - */ - function generate(options: KeyOptions): Key; - - /** Reads an OpenPGP armored text and returns one or multiple key objects - - @param armoredText text to be parsed - */ - function readArmored(armoredText: string): Promise; -} - -export namespace message { - /** Class that represents an OpenPGP message. Can be an encrypted message, signed message, compressed message or literal message - */ - interface Message { - /** Returns ASCII armored text of message - */ - armor(): string, - - /** Decrypt the message - @param privateKey private key with decrypted secret data - */ - decrypt(privateKey: key.Key): Array, - - /** Encrypt the message - @param keys array of keys, used to encrypt the message - */ - encrypt(keys: Array): Array, - - /** Returns the key IDs of the keys to which the session key is encrypted - */ - getEncryptionKeyIds(): Array, - - /** Get literal data that is the body of the message - */ - getLiteralData(): string, - - /** Returns the key IDs of the keys that signed the message - */ - getSigningKeyIds(): Array, - - /** Get literal data as text - */ - getText(): string, - - /** Sign the message (the literal data packet of the message) - @param privateKey private keys with decrypted secret key data for signing - */ - sign(privateKey: Array): Message, - - /** Unwrap compressed message - */ - unwrapCompressed(): Message, - - /** Verify message signatures - @param keys array of keys to verify signatures - */ - verify(keys: Array): Array, - - packets: { - write(): Uint8Array, - }, - } - - /** creates new message object from binary data - @param bytes - */ - function fromBinary(bytes: Uint8Array | ReadableStream): Message; - - /** creates new message object from text - @param text - */ - function fromText(text: string): Message; - - /** reads an OpenPGP armored message and returns a message object - - @param armoredText text to be parsed - */ - function readArmored(armoredText: string): Promise; /** - * reads an OpenPGP message as byte array and returns a message object - * @param {Uint8Array} input binary message - * @returns {Message} new message object - * @static + * Set the path for the web worker script and create an instance of the async proxy + * @param path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param n number of workers to initialize + * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' */ - function read(data: Uint8Array): Promise; -} - -export namespace packet { - interface PublicKey { - algorithm: enums.publicKey; - created: Date; - fingerprint: string; - - getBitSize(): number; - getFingerprint(): string; - getKeyId(): Keyid; - read(input: string): any; - write(): any; - } - - interface SecretKey extends PublicKey { - read(bytes: string): void; - write(): string; - clearPrivateMPIs(str_passphrase: string): boolean; - encrypt(passphrase: string): void; - } - - /** Allocate a new packet from structured packet clone - @param packetClone packet clone - */ - function fromStructuredClone(packetClone: Object): Object - - /** Allocate a new packet - @param property name from enums.packet - */ - function newPacketFromTag(tag: string): Object; -} - -export namespace util { - /** - * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) - * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage - * Also, convert ReadableStreams to MessagePorts - * @param obj the options object to be passed to the web worker - * @returns an array of binary data to be passed - */ - function getTransferables(obj: Object): ArrayBuffer[]; + function initWorker(path: string, n?: number, workers?: any[]): void; /** - * Convert MessagePorts back to ReadableStreams - * @param obj + * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() + * @returns the async proxy or null if not initialized + */ + function getWorker(): worker.async_proxy.AsyncProxy | null; + + /** + * Cleanup the current instance of the web worker. + */ + function destroyWorker(): void; + + interface UserID { + name: string; + email: string; + } + + interface KeyOptions { + /** + * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + */ + userIds: UserID[]; + /** + * (optional) The passphrase used to encrypt the resulting private key + */ + passphrase?: string; + /** + * (optional) number of bits for RSA keys: 2048 or 4096. + */ + numBits?: number; + /** + * (optional) The number of seconds after the key creation time that the key expires + */ + keyExpirationTime?: number; + /** + * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: + * curve25519, p256, p384, p521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. + */ + curve?: string; + /** + * (optional) override the creation date of the key and the key signatures + */ + date?: Date; + /** + * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + */ + subkeys?: { sign: true, passphrase: "string" }[]; + } + + /** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. + * @param options + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ + function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; + + /** + * Reformats signature packets for a key and rewraps key object. + * @param privateKey private key to reformat + * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param passphrase (optional) The passphrase used to encrypt the resulting private key + * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ + function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; + + /** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. + * @param key (optional) public or private key to revoke + * @param revocationCertificate (optional) revocation certificate to revoke the key with + * @param reasonForRevocation (optional) object indicating the reason for revocation + * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation + * @param reasonForRevocation.string (optional) string explaining the reason for revocation + * @returns The revoked key object in the form: + * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } + * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) + */ + function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ + privateKey: key.Key, + privateKeyArmored: string, + publicKey: key.Key, + publicKeyArmored: string + } | { + publicKey: key.Key, + publicKeyArmored: string + }>; + + /** + * Unlock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the unlocked key object in the form: { key:Key } + */ + function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + + /** + * Lock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the locked key object in the form: { key:Key } + */ + function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + + interface EncryptOptions { + /** + * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary + */ + message: message.Message; + /** + * (optional) array of keys or single key, used to encrypt the message + */ + publicKeys?: key.Key | any[]; + /** + * (optional) private keys for signing. If omitted message will not be signed + */ + privateKeys?: key.Key | any[]; + /** + * (optional) array of passwords or a single password to encrypt the message + */ + passwords?: string | any[]; + /** + * (optional) session key in the form: { data:Uint8Array, algorithm:String } + */ + sessionKey?: { data: Uint8Array, algorithm: string }; + /** + * (optional) which compression algorithm to compress the message with, defaults to what is specified in config + */ + compression?: enums.compression; + /** + * (optional) if the return values should be ascii armored or the message/signature objects + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the signature should be detached (if true, signature will be added to returned object) + */ + detached?: boolean; + /** + * (optional) a detached signature to add to the encrypted message + */ + signature?: signature.Signature; + /** + * (optional) if the unencrypted session key should be added to returned object + */ + returnSessionKey?: boolean; + /** + * (optional) use a key ID of 0 instead of the public key IDs + */ + wildcard?: boolean; + /** + * (optional) override the creation date of the message signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[]; + /** + * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + */ + toUserIds?: UserID[] + } + + interface EncryptResult { + data: string | ReadableStream; + message: message.Message; + signature: string | ReadableStream | signature.Signature; + sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; + } + + /** + * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords + * must be specified. If private keys are specified, those will be used to sign the message. + * @param options + * @returns Object containing encrypted (and optionally signed) message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message, (if `armor` was false) + * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) + * signature: Signature (if `detached` was true and `armor` was false) + * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) + * } + */ + function encrypt(options: EncryptOptions): Promise; + + interface DecryptOptions { + /** + * the message object with the encrypted data + */ + message: message.Message; + /** + * (optional) private keys with decrypted secret key data or session key + */ + privateKeys?: key.Key | key.Key[]; + /** + * (optional) passwords to decrypt the message + */ + passwords?: string | string[]; + /** + * (optional) session keys in the form: { data:Uint8Array, algorithm:String } + */ + sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; + /** + * (optional) array of public keys or single key, to verify signatures + */ + publicKeys?: key.Key | key.Key[]; + /** + * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + */ + format?: 'utf8' | 'binary'; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date + } + + interface DecryptResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, + filename: string, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] + } + + /** + * Decrypts a message with the user's private key, a session key or a password. Either a private key, + * a session key or a password must be specified. + * @param options + * @returns Object containing decrypted and verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) + * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') + * filename: string, + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if streaming was false) + * }, ... + * ] + * } + */ + function decrypt(options: DecryptOptions): Promise; + + interface SignOptions { + /** + * (cleartext) message to be signed + */ + message: cleartext.CleartextMessage | message.Message; + /** + * array of keys or single key with decrypted secret key data to sign cleartext + */ + privateKeys: key.Key | any[]; + /** + * (optional) if the return value should be ascii armored or the message object + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the return value should contain a detached signature + */ + detached?: boolean; + /** + * (optional) override the creation date of the signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[] + } + + interface SignResult { + data: string | ReadableStream | NodeStream, + message: message.Message, + signature: string | ReadableStream | NodeStream | signature.Signature + } + + /** + * Signs a cleartext message. + * @param options + * @returns Object containing signed message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message (if `armor` was false) + * } + * Or, if `detached` was true: + * { + * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * signature: Signature (if `armor` was false) + * } + */ + function sign(options: SignOptions): Promise; + + interface VerifyOptions { + /** + * array of publicKeys or single key, to verify signatures + */ + publicKeys: key.Key | any[]; + /** + * (cleartext) message object with signatures + */ + message: cleartext.CleartextMessage | message.Message; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date + } + + interface VerifyResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] + } + + /** + * Verifies signatures of cleartext signed message + * @param options + * @returns Object containing verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) + * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if `streaming` was false) + * }, ... + * ] + * } + */ + function verify(options: VerifyOptions): Promise; + + /** + * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys + * or passwords must be specified. + * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) + * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) array of public keys or single key, used to encrypt the key + * @param passwords (optional) passwords for the message + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @returns the encrypted session key packets contained in a message object + */ + function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; + + /** + * Decrypt symmetric session keys with a private key or password. Either a private key or + * a password must be specified. + * @param message a message object containing the encrypted session key packets + * @param privateKeys (optional) private keys with decrypted secret key data + * @param passwords (optional) passwords to decrypt the session key + * @returns Array of decrypted session key, algorithm pairs in form: + * { data:Uint8Array, algorithm:String } + * or 'undefined' if no key packets found + */ + function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; + + /** + * Input validation + */ + function checkString(): void; + + /** + * Normalize parameter to an array if it is not undefined. + * @param param the parameter to be normalized + * @returns the resulting array or undefined + */ + function toArray(param: object): any[] | undefined; + + /** + * Convert data to or from Stream + * @param data the data to convert + * @param streaming (optional) whether to return a ReadableStream + * @returns the data in the respective format + */ + function convertStream(data: object, streaming?: 'web' | 'node' | false): object; + + /** + * Convert object properties from Stream + * @param obj the data to convert + * @param streaming (optional) whether to return ReadableStreams + * @param keys (optional) which keys to return as streams, if possible + * @returns the data in the respective format + */ + function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; + + /** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param result the data to convert + * @param message message object + * @param erroringStream (optional) stream which either errors or gets closed without data * @returns */ - function restoreStreams(obj: Object): Object; + function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; /** - * Create hex string from a binary - * @param str String to convert - * @returns String containing the hexadecimal values + * Wait until signature objects have been verified + * @param signatures list of signatures */ - function str_to_hex(str: String): String; + function prepareSignatures(signatures: object): void; /** - * Create binary string from a hex encoded string - * @param str Hex string to convert - * @returns + * Global error handler that logs the stack trace and rethrows a high lvl error message. + * @param message A human readable high level error Message + * @param error The internal error that caused the failure */ - function hex_to_str(str: String): String; + function onError(message: string, error: Error): void; /** - * Convert a Uint8Array to an MPI-formatted Uint8Array. - * Note: the output is **not** an MPI object. - * @see - * @see - * @param bin An array of 8-bit integers to convert - * @returns MPI-formatted Uint8Array + * Check for native AEAD support and configuration by the user. Only + * browsers that implement the current WebCrypto specification support + * native GCM. Native EAX is built on CTR and CBC, which current + * browsers support. OCB and CFB are not natively supported. + * @returns If authenticated encryption should be used */ - function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; - - /** - * Convert a Base-64 encoded string an array of 8-bit integer - * Note: accepts both Radix-64 and URL-safe strings - * @param base64 Base-64 encoded string to convert - * @returns An array of 8-bit integers - */ - function b64_to_Uint8Array(base64: String): Uint8Array; - - /** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param bytes An array of 8-bit integers to convert - * @param url If true, output is URL-safe - * @returns Base-64 encoded string - */ - function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): String; - - /** - * Convert a hex string to an array of 8-bit integers - * @param hex A hex string to convert - * @returns An array of 8-bit integers - */ - function hex_to_Uint8Array(hex: String): Uint8Array; - - /** - * Convert an array of 8-bit integers to a hex string - * @param bytes Array of 8-bit integers to convert - * @returns Hexadecimal representation of the array - */ - function Uint8Array_to_hex(bytes: Uint8Array): String; - - /** - * Convert a string to an array of 8-bit integers - * @param str String to convert - * @returns An array of 8-bit integers - */ - function str_to_Uint8Array(str: String): Uint8Array; - - /** - * Convert an array of 8-bit integers to a string - * @param bytes An array of 8-bit integers to convert - * @returns String representation of the array - */ - function Uint8Array_to_str(bytes: Uint8Array): String; - - /** - * Convert a native javascript string to a Uint8Array of utf8 bytes - * @param str The string to convert - * @returns A valid squence of utf8 bytes - */ - function encode_utf8(str: String | ReadableStream): Uint8Array | ReadableStream; - - /** - * Convert a Uint8Array of utf8 bytes to a native javascript string - * @param utf8 A valid squence of utf8 bytes - * @returns A native javascript string - */ - function decode_utf8(utf8: Uint8Array | ReadableStream): String | ReadableStream; - - /** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param Array of Uint8Arrays/Strings/Streams to concatenate - * @returns Concatenated array - */ - var concat: any; - - /** - * Concat Uint8Arrays - * @param Array of Uint8Arrays to concatenate - * @returns Concatenated array - */ - var concatUint8Array: any; - - /** - * Check Uint8Array equality - * @param first array - * @param second array - * @returns equality - */ - function equalsUint8Array(first: Uint8Array, second: Uint8Array): Boolean; - - /** - * Calculates a 16bit sum of a Uint8Array by adding each character - * codes modulus 65535 - * @param Uint8Array to create a sum of - * @returns 2 bytes containing the sum of all charcodes % 65535 - */ - function write_checksum(Uint8Array: Uint8Array): Uint8Array; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug(str: String): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexarray_dump(str: String): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexstr_dump(str: String): void; - - /** - * Helper function to print a debug error. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_error(str: String): void; - - /** - * Read a stream to the end and print it to the console when it's closed. - * @param str String of the debug message - * @param input Stream to print - * @param concat Function to concatenate chunks of the stream (defaults to util.concat). - */ - function print_entire_stream(str: String, input: ReadableStream | Uint8Array | String, concat: Function): void; - - /** - * If S[1] == 0, then double(S) == (S[2..128] || 0); - * otherwise, double(S) == (S[2..128] || 0) xor - * (zeros(120) || 10000111). - * Both OCB and EAX (through CMAC) require this function to be constant-time. - * @param data - */ - /* Illegal function name 'double' can't be used here - export function double(data: Uint8Array): void; - */ - - /** - * Shift a Uint8Array to the right by n bits - * @param array The array to shift - * @param bits Amount of bits to shift (MUST be smaller - * than 8) - * @returns Resulting array. - */ - function shiftRight(array: Uint8Array, bits: number): String; - - /** - * Get native Web Cryptography api, only the current version of the spec. - * The default configuration is to use the api when available. But it can - * be deactivated with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCrypto(): Object; - - /** - * Get native Web Cryptography api for all browsers, including legacy - * implementations of the spec e.g IE11 and Safari 8/9. The default - * configuration is to use the api when available. But it can be deactivated - * with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCryptoAll(): Object; - - /** - * Detect Node.js runtime. - */ - function detectNode(): void; - - /** - * Get native Node.js module - * @param The module to require - * @returns The required module or 'undefined' - */ - function nodeRequire(The: String): Object; - - /** - * Get native Node.js crypto api. The default configuration is to use - * the api when available. But it can also be deactivated with config.use_native - * @returns The crypto module or 'undefined' - */ - function getNodeCrypto(): Object; - - /** - * Get native Node.js Buffer constructor. This should be used since - * Buffer is not available under browserify. - * @returns The Buffer constructor or 'undefined' - */ - function getNodeBuffer(): Function; - - /** - * Format user id for internal use. - */ - function formatUserId(): void; - - /** - * Parse user id. - */ - function parseUserId(): void; - - /** - * Normalize line endings to \r\n - */ - function canonicalizeEOL(): void; - - /** - * Convert line endings from canonicalized \r\n to native \n - */ - function nativeEOL(): void; - - /** - * Remove trailing spaces and tabs from each line - */ - function removeTrailingSpaces(): void; - - /** - * Encode input buffer using Z-Base32 encoding. - * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 - * @param data The binary data to encode - * @returns Binary data encoded using Z-Base32 - */ - function encodeZBase32(data: Uint8Array): String; + function nativeAEAD(): boolean; } diff --git a/types/openpgp/openpgp-tests.ts b/types/openpgp/openpgp-tests.ts index b4ff8d9487..3d5a1e3717 100644 --- a/types/openpgp/openpgp-tests.ts +++ b/types/openpgp/openpgp-tests.ts @@ -1,6 +1,8 @@ +import { openpgp } from "openpgp" + // Open PGP Sample codes -var options: openpgp.KeyOptions = { +const options: openpgp.KeyOptions = { numBits: 2048, userIds: [{ name: 'Jon Smith', @@ -8,53 +10,51 @@ var options: openpgp.KeyOptions = { }], passphrase: 'super long and hard to guess secret' }; - -openpgp.generateKey(options).then(function (keypair) { +openpgp.generateKey(options).then((keypair) => { // success - var privkey = keypair.privateKeyArmored; - var pubkey = keypair.publicKeyArmored; -}).catch(function (error) { + const privkey = keypair.privateKeyArmored; + const pubkey = keypair.publicKeyArmored; +}).catch((error) => { // failure }); - -var spubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----'; +const spubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----'; openpgp.key.readArmored(spubkey) - .then(function (publicKey) { + .then((publicKey) => { return { message: openpgp.message.fromText('Hello, World!'), publicKeys: publicKey.keys }; }) .then(openpgp.encrypt) - .then(function (pgpMessage) { + .then((pgpMessage) => { // success }) - .catch(function (error) { + .catch((error) => { // failure }); -var sprivkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----'; -var pgpMessageStr = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'; +const sprivkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----'; +const pgpMessageStr = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'; -openpgp.message.readArmored(pgpMessageStr).then(function(pgpMessage) { +openpgp.message.readArmored(pgpMessageStr).then((pgpMessage) => { const options = { message: pgpMessage }; return openpgp.decrypt(options); -}).then(function (plaintext) { +}).then((plaintext) => { // success -}).catch(function (error) { +}).catch((error) => { // failure }); -const promises: [Promise, Promise] = [ +const promises: [Promise<{ keys: openpgp.key.Key[], err: Error[] | null }>, Promise] = [ openpgp.key.readArmored(sprivkey), openpgp.message.readArmored(pgpMessageStr) ]; -Promise.all(promises).then(function (values) { +Promise.all(promises).then((values) => { const keyObject: openpgp.key.KeyResult = values[0]; const pgpMessage: openpgp.message.Message = values[1]; const privateKey = keyObject.keys[0]; @@ -64,13 +64,13 @@ Promise.all(promises).then(function (values) { message: pgpMessage }; return openpgp.decrypt(options); -}).then(function (plaintext) { +}).then((plaintext) => { // success -}).catch(function (error) { +}).catch((error) => { // failure }); -openpgp.initWorker({ path:'openpgp.worker.js' }); +openpgp.initWorker('openpgp.worker.js'); (async () => { let msgOptions: openpgp.EncryptOptions; @@ -81,10 +81,10 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); armor: false, }; - let cipher = await openpgp.encrypt(msgOptions); - let encrypted = cipher.message.packets.write(); // get raw encrypted packets as Uint8Array + const cipher = await openpgp.encrypt(msgOptions); + const encrypted = cipher.message.packets.write(); // get raw encrypted packets as Uint8Array - let plain = await openpgp.decrypt({ + const plain = await openpgp.decrypt({ message: await openpgp.message.read(encrypted), passwords: ['secret stuff'], format: 'binary' @@ -94,14 +94,14 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); })(); (async () => { - let cipher = await openpgp.encrypt({ + const cipher = await openpgp.encrypt({ message: openpgp.message.fromText('hello world'), passwords: 'super secure', armor: true, }); - let encrypted = cipher.data; + const encrypted = cipher.data; - let plain = await openpgp.decrypt({ + const plain = await openpgp.decrypt({ message: await openpgp.message.readArmored(encrypted), passwords: 'super secure', }); @@ -109,10 +109,9 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); return plain.data; })(); - (async () => { - const publicKey = (await openpgp.key.readArmored(spubkey)) - const privateKey = (await openpgp.key.readArmored(sprivkey)) + const publicKey = (await openpgp.key.readArmored(spubkey)); + const privateKey = (await openpgp.key.readArmored(sprivkey)); const signOptions: openpgp.SignOptions = { message: openpgp.message.fromText('hello world'), privateKeys: privateKey.keys, @@ -121,7 +120,7 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); const signed = await openpgp.sign(signOptions); - const signature = signed.signature as openpgp.Signature; + const signature = signed.signature as openpgp.signature.Signature; const message = signed.message; const verifyOptions: openpgp.VerifyOptions = { @@ -130,60 +129,46 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); publicKeys: publicKey.keys }; - let verified = await openpgp.verify(verifyOptions); + const verified = await openpgp.verify(verifyOptions); return verified.signatures[0].valid; })(); -async () => { - let hkp = new openpgp.HKP(); - - const hkpOptions = { - query: 'alice@example.com' - }; - - const armoredPubkey = await hkp.lookup(hkpOptions); - await openpgp.key.readArmored(armoredPubkey); - - hkp = new openpgp.HKP('https://pgp.mit.edu'); - - const pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----'; - - await hkp.upload(pubkey); -} - // Open PGP Tests +const keyoptions: openpgp.KeyOptions = null; +const mpi: openpgp.type.mpi.MPI = null; +const mpis: openpgp.type.mpi.MPI[] = []; -var keyoptions: openpgp.KeyOptions; -var mpi: openpgp.crypto.Mpi; -var mpis: Array; - -openpgp.armor.armor(openpgp.enums.armor.message, {}, 0, 1); -openpgp.armor.dearmor(""); +openpgp.encoding.armor.armor(openpgp.enums.armor.message, {}, 0, 1); +openpgp.encoding.armor.dearmor(""); openpgp.cleartext.readArmored(""); -openpgp.crypto.generateSessionKey(openpgp.enums.symmetric.aes128); -openpgp.crypto.getPrefixRandom(openpgp.enums.symmetric.aes128); -openpgp.crypto.getPrivateMpiCount(openpgp.enums.symmetric.aes128); -openpgp.crypto.publicKeyDecrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, mpi); -openpgp.crypto.publicKeyEncrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpi); +openpgp.crypto.crypto.generateSessionKey(openpgp.enums.symmetric.aes128); +openpgp.crypto.crypto.getPrefixRandom(openpgp.enums.symmetric.aes128); +// openpgp.crypto.crypto.getPrivateMpiCount(openpgp.enums.symmetric.aes128); +openpgp.crypto.crypto.publicKeyDecrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, ""); +openpgp.crypto.crypto.publicKeyEncrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpi, ""); +openpgp.crypto; +// API update with no documentation openpgp.crypto.cfb.decrypt("", "", "", true); -openpgp.crypto.cfb.encrypt("", "", "", "", true); -openpgp.crypto.cfb.mdc({}, "", ""); +openpgp.crypto.cfb.encrypt("", "", "", true); +// Function removed from openpgp.crypto.cfb +// openpgp.crypto.cfb.mdc({}, "", ""); -openpgp.crypto.hash.digest(openpgp.enums.hash.md5, ""); +openpgp.crypto.hash.digest(openpgp.enums.hash.md5, new Uint8Array([0, 1])); openpgp.crypto.hash.getHashByteLength(openpgp.enums.hash.md5); -openpgp.crypto.random.getRandomBigInteger(0); +openpgp.crypto.random.getRandomBN(mpi, mpi); openpgp.crypto.random.getRandomBytes(0); -openpgp.crypto.random.getRandomValues(openpgp.util.str_to_Uint8Array("")); -openpgp.crypto.random.getSecureRandom(0, 1); +// function removed from openpgp.crypto.random +// openpgp.crypto.random.getRandomValues(openpgp.util.str_to_Uint8Array("")); +// openpgp.crypto.random.getSecureRandom(0, 1); -openpgp.crypto.signature.sign(openpgp.enums.hash.md5, openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, ""); -openpgp.crypto.signature.verify(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, mpis, ""); +openpgp.crypto.signature.sign(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, new Uint8Array([0, 1]), new Uint8Array([0, 1])); +openpgp.crypto.signature.verify(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, mpis, new Uint8Array([0, 1]), new Uint8Array([0, 1])); openpgp.key.generate(keyoptions); openpgp.key.readArmored(""); diff --git a/types/openpgp/package.json b/types/openpgp/package.json index d27d838dc6..cda6cc6dc8 100644 --- a/types/openpgp/package.json +++ b/types/openpgp/package.json @@ -2,6 +2,10 @@ "private": true, "types": "index", "typesVersions": { - ">=3.2.0-0": { "*": ["ts3.2/*"] } + ">=3.2.0-0": { + "*": [ + "ts3.2/*" + ] + } } } diff --git a/types/openpgp/ts3.2/index.d.ts b/types/openpgp/ts3.2/index.d.ts index 13b2d1646d..62bccca432 100644 --- a/types/openpgp/ts3.2/index.d.ts +++ b/types/openpgp/ts3.2/index.d.ts @@ -1,5 +1,5 @@ -// Type definitions for openpgp 4.4.8 -// Project: http://openpgpjs.org/ +// Type definitions for openpgp v4.4.10 +// Project: https://openpgpjs.org // Definitions by: Guillaume Lacasa // Errietta Kostala // Daniel Montesinos @@ -8,1041 +8,5227 @@ // SardineFIsh // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -export as namespace openpgp; +import BN = require("bn.js") +import stream = require("stream") -export * from '../common'; +export {} +type NodeStream = stream; +type Integer = number; +type Infinity = any; -export interface UserId { - name?: string, - email?: string, -} -export interface SessionKey { - data: Uint8Array, - algorithm: string -} - -export interface EncryptOptions { - message: message.Message - publicKeys?: key.Key | key.Key[], - privateKeys?: key.Key | key.Key[], - passwords?: string | string[], - sessionKey?: SessionKey, - compression?: enums.compression, - armor?: boolean, - streaming?: 'web' | 'node' | false - detached?: boolean, - signature?: Signature, - returnSessionKey?: boolean, - wildcard?: boolean, - date?: Date, - fromUserId?: UserId, - toUserId?: UserId, -} - -export interface EncryptedMessage { - data?: string, - message?: message.Message, - signature?: string | ReadableStream | Signature // TODO add NodeStream - sessionKey?: SessionKey -} - -export interface DecryptOptions { - message: message.Message, - privateKeys?: key.Key | key.Key[], - passwords?: string | string[], - sessionKeys?: SessionKey | SessionKey[], - publicKeys?: key.Key | key.Key[], - format?: string, - streaming?: 'web' | 'node' | false, - signature?: Signature, - date?: Date, -} - -export interface SignOptions { - message: message.Message, - privateKeys?: key.Key | key.Key[], - armor?: boolean, - streaming?: 'web' | 'node' | false, - detached?: boolean - date?: Date, - fromUserIds?: UserId[] -} - -export interface SignedMessage { - signature?: string | ReadableStream | Signature, // TODO add NodeStream - data?: string | ReadableStream, // TODO add NodeStream - message?: message.Message -} - -export interface KeyContainer { - key: key.Key, -} - -export interface KeyPair extends KeyContainer { - privateKeyArmored: string, - publicKeyArmored: string, - revocationCertificate: string -} - -export interface KeyOptions { - userIds?: UserId[], - passphrase?: string, - numBits?: number, - keyExpirationTime?: number, - curve?: string, - date?: Date, - subkeys?: KeyOptions[] -} - -export interface Keyid { - bytes: string, -} - -export interface Signature { - keyid: Keyid, - valid: boolean, - verified?: boolean -} - -export interface VerifyOptions { - message: message.Message, - publicKeys: key.Key | key.Key[], - streaming?: 'web' | 'node' | false, - signature?: Signature, - date?: Date -} - -export interface VerifiedMessage { - data: Uint8Array | string | ReadableStream | ReadableStream, // TODO add NodeStream - signatures: Array, -} - -export interface DecryptedMessage { - data: Uint8Array | string | ReadableStream | ReadableStream, // TODO add NodeStream - signatures: Array, - filename: string -} - -export interface OpenPGPWorker { - randomCallback(): void; - configure(config: any): void; - seedRandom(buffer: ArrayBuffer): void; - delegate(id: number, method: string, options: any): void; - response(event: any): void; -} - -export interface WorkerOptions { - path?: string, - n?: number, - workers?: OpenPGPWorker[], - config?: any -} - -export class AsyncProxy { - constructor(options: WorkerOptions); - getId(): number; - seedRandom(workerId: number, size: number): Promise; - terminate(): void; - delegate(method: string, options: any): void; - - workers: OpenPGPWorker[]; -} - -/** - * Set the path for the web worker script and create an instance of the async proxy - * @param {String} path relative path to the worker scripts, default: 'openpgp.worker.js' - * @param {Number} n number of workers to initialize - * @param {Array} workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' - */ -export function initWorker(options: WorkerOptions): boolean; - -/** - * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() - * @returns {module:worker/async_proxy.AsyncProxy|null} the async proxy or null if not initialized - */ -export function getWorker(): AsyncProxy; - -/** - * Cleanup the current instance of the web worker. - */ -export function destroyWorker(): void; - -/** - * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords - * must be specified. If private keys are specified, those will be used to sign the message. - * @param {Message} message message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary - * @param {Key|Array} publicKeys (optional) array of keys or single key, used to encrypt the message - * @param {Key|Array} privateKeys (optional) private keys for signing. If omitted message will not be signed - * @param {String|Array} passwords (optional) array of passwords or a single password to encrypt the message - * @param {Object} sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String } - * @param {module:enums.compression} compression (optional) which compression algorithm to compress the message with, defaults to what is specified in config - * @param {Boolean} armor (optional) if the return values should be ascii armored or the message/signature objects - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Boolean} detached (optional) if the signature should be detached (if true, signature will be added to returned object) - * @param {Signature} signature (optional) a detached signature to add to the encrypted message - * @param {Boolean} returnSessionKey (optional) if the unencrypted session key should be added to returned object - * @param {Boolean} wildcard (optional) use a key ID of 0 instead of the public key IDs - * @param {Date} date (optional) override the creation date of the message signature - * @param {Object} fromUserId (optional) user ID to sign with, e.g. { name:'Steve Sender', email:'steve@openpgp.org' } - * @param {Object} toUserId (optional) user ID to encrypt for, e.g. { name:'Robert Receiver', email:'robert@openpgp.org' } - * @returns {Promise} Object containing encrypted (and optionally signed) message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message, (if `armor` was false) - * signature: String|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) - * signature: Signature (if `detached` was true and `armor` was false) - * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) - * } - * @async - * @static - */ -export function encrypt(options: EncryptOptions): Promise; - -/** - * Decrypts a message with the user's private key, a session key or a password. Either a private key, - * a session key or a password must be specified. - * @param {Message} message the message object with the encrypted data - * @param {Key|Array} privateKeys (optional) private keys with decrypted secret key data or session key - * @param {String|Array} passwords (optional) passwords to decrypt the message - * @param {Object|Array} sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String } - * @param {Key|Array} publicKeys (optional) array of public keys or single key, to verify signatures - * @param {String} format (optional) return data format either as 'utf8' or 'binary' - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Signature} signature (optional) detached signature for verification - * @param {Date} date (optional) use the given date for verification instead of the current time - * @returns {Promise} Object containing decrypted and verified message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if format was 'utf8', the default) - * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') - * filename: String, - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: Boolean (if streaming was false) - * }, ... - * ] - * } - * @async - * @static - */ -export function decrypt(options: DecryptOptions): Promise; - -/** - * Signs a cleartext message. - * @param {CleartextMessage|Message} message (cleartext) message to be signed - * @param {Key|Array} privateKeys array of keys or single key with decrypted secret key data to sign cleartext - * @param {Boolean} armor (optional) if the return value should be ascii armored or the message object - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Boolean} detached (optional) if the return value should contain a detached signature - * @param {Date} date (optional) override the creation date of the signature - * @param {Array} fromUserIds (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [{ name:'Steve Sender', email:'steve@openpgp.org' }] - * @returns {Promise} Object containing signed message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * message: Message (if `armor` was false) - * } - * - * Or, if `detached` was true: - * - * { - * signature: String|ReadableStream|NodeStream, (if `armor` was true, the default) - * signature: Signature (if `armor` was false) - * } - * @async - * @static - */ -export function sign(options: SignOptions): Promise; - -/** - * Verifies signatures of cleartext signed message - * @param {Key|Array} publicKeys array of publicKeys or single key, to verify signatures - * @param {CleartextMessage|Message} message (cleartext) message object with signatures - * @param {'web'|'node'|false} streaming (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. - * @param {Signature} signature (optional) detached signature for verification - * @param {Date} date (optional) use the given date for verification instead of the current time - * @returns {Promise} Object containing verified message in the form: - * - * { - * data: String|ReadableStream|NodeStream, (if `message` was a CleartextMessage) - * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) - * signatures: [ - * { - * keyid: module:type/keyid, - * verified: Promise, - * valid: Boolean (if `streaming` was false) - * }, ... - * ] - * } - * @async - * @static - */ -export function verify(options: VerifyOptions): Promise; - -/** - * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. - * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key - * @param {Number} numBits (optional) number of bits for RSA keys: 2048 or 4096. - * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param {String} curve (optional) elliptic curve for ECC keys: - * curve25519, p256, p384, p521, secp256k1, - * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. - * @param {Date} date (optional) override the creation date of the key and the key signatures - * @param {Array} subkeys (optional) options for each subkey, default to main key options. e.g. [{sign: true, passphrase: '123'}] - * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt - * @returns {Promise} The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - * @async - * @static - */ -export function generateKey(options: KeyOptions): Promise; - -/** - * Reformats signature packets for a key and rewraps key object. - * @param {Key} privateKey private key to reformat - * @param {Array} userIds array of user IDs e.g. [{ name:'Phil Zimmermann', email:'phil@openpgp.org' }] - * @param {String} passphrase (optional) The passphrase used to encrypt the resulting private key - * @param {Number} keyExpirationTime (optional) The number of seconds after the key creation time that the key expires - * @param {Boolean} revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key - * @returns {Promise} The generated key object in the form: - * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } - * @async - * @static - */ -export function reformatKey(options: { - privateKey: key.Key, - userIds?: UserId[], - passphrase?: string, - keyExpirationTime?: number, - revocationCertificate?: boolean -}): Promise; - -/** - * Revokes a key. Requires either a private key or a revocation certificate. - * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. - * @param {Key} key (optional) public or private key to revoke - * @param {String} revocationCertificate (optional) revocation certificate to revoke the key with - * @param {Object} reasonForRevocation (optional) object indicating the reason for revocation - * @param {module:enums.reasonForRevocation} reasonForRevocation.flag (optional) flag indicating the reason for revocation - * @param {String} reasonForRevocation.string (optional) string explaining the reason for revocation - * @returns {Promise} The revoked key object in the form: - * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } - * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) - * @static - */ -export function revokeKey(options: { - key?: key.Key, - revocationCertificate?: string - reasonForRevocation?: { - flag: enums.reasonForRevocation, - 'string': string - }, -}): Promise; - -/** - * Unlock a private key with your passphrase. - * @param {Key} privateKey the private key that is to be decrypted - * @param {String|Array} passphrase the user's passphrase(s) chosen during key generation - * @returns {Promise} the unlocked key object in the form: { key:Key } - * @async - */ -export function decryptKey(options: { - privateKey: key.Key, - passphrase?: string | string[], -}): Promise; - -/** - * Lock a private key with your passphrase. - * @param {Key} privateKey the private key that is to be decrypted - * @param {String|Array} passphrase the user's passphrase(s) chosen during key generation - * @returns {Promise} the locked key object in the form: { key:Key } - * @async - */ -export function encryptKey(options: { - privateKey: key.Key, - passphrase?: string | string[], -}): Promise; - -// TODO add typings for encryptSessionKey and decryptSessionKeys - -export namespace armor { - /** Armor an OpenPGP binary packet block - - @param messagetype type of the message - @param body - @param partindex - @param parttotal - */ - function armor(messagetype: enums.armor, body: Object, partindex: number, parttotal: number): string; - - /** DeArmor an OpenPGP armored message; verify the checksum and return the encoded bytes - - @param text OpenPGP armored message - */ - function dearmor(text: string): Object; -} - -export namespace cleartext { - /** Class that represents an OpenPGP cleartext signed message. - */ - interface CleartextMessage { - /** Returns ASCII armored text of cleartext signed message +export namespace openpgp { + namespace cleartext { + /** + * Class that represents an OpenPGP cleartext signed message. + * See {@link https://tools.ietf.org/html/rfc4880#section-7} */ - armor(): string; + class CleartextMessage { + /** + * @param text The cleartext of the signed message + * @param signature The detached signature or an empty signature for unsigned messages + */ + constructor(text: string, signature: signature.Signature); - /** Returns the key IDs of the keys that signed the cleartext message - */ - getSigningKeyIds(): Array; + /** + * Returns the key IDs of the keys that signed the cleartext message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; - /** Get cleartext - */ - getText(): string; + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new cleartext message with signed content + */ + sign(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - /** Sign the cleartext message - @param privateKeys private keys with decrypted secret key data for signing - */ - sign(privateKeys: Array): void; + /** + * Sign the cleartext message + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) The creation time of the signature that should be created + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; - /** Verify signatures of cleartext signed message - @param keys array of keys to verify signatures + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date: Date): Promise>; + + /** + * Verify signatures of cleartext signed message + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], date: Date): Promise>; + + /** + * Get cleartext + * @returns cleartext of message + */ + getText(): string; + + /** + * Returns ASCII armored text of cleartext signed message + * @returns ASCII armor + */ + armor(): string | ReadableStream; + } + + /** + * reads an OpenPGP cleartext signed message and returns a CleartextMessage object + * @param armoredText text to be parsed + * @returns new cleartext message object */ - verify(keys: Array): Array; + function readArmored(armoredText: string | ReadableStream): CleartextMessage; + + /** + * Creates a new CleartextMessage object from text + * @param text + */ + function fromText(text: string): void; } - /** creates new message object from text - @param text + /** + * @see module:config/config */ - function fromText(text: string): CleartextMessage; + namespace config { + var prefer_hash_algorithm: any; - function readArmored(armoredText: string): Promise; -} + var encryption_cipher: any; -export namespace config { - var prefer_hash_algorithm: enums.hash; - var encryption_cipher: enums.symmetric; - var compression: enums.compression; - var show_version: boolean; - var show_comment: boolean; - var integrity_protect: boolean; - var keyserver: string; - var debug: boolean; -} + var compression: any; -export namespace crypto { - interface Mpi { - data: number, - read(input: string): number, - write(): string, + var deflate_level: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * **NOT INTEROPERABLE WITH OTHER OPENPGP IMPLEMENTATIONS** + * **FUTURE OPENPGP.JS VERSIONS MAY BREAK COMPATIBILITY WHEN USING THIS OPTION** + */ + var aead_protect: any; + + /** + * Use Authenticated Encryption with Additional Data (AEAD) protection for symmetric encryption. + * 0 means we implement a variant of {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00|this IETF draft}. + * 4 means we implement {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04|RFC4880bis-04}. + * Note that this determines how AEAD packets are parsed even when aead_protect is set to false + */ + var aead_protect_version: any; + + /** + * Default Authenticated Encryption with Additional Data (AEAD) encryption mode + * Only has an effect when aead_protect is set to true. + */ + var aead_mode: any; + + /** + * Chunk Size Byte for Authenticated Encryption with Additional Data (AEAD) mode + * Only has an effect when aead_protect is set to true. + * Must be an integer value from 0 to 56. + */ + var aead_chunk_size_byte: any; + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-3.7.1.3|RFC4880 3.7.1.3}: + * Iteration Count Byte for S2K (String to Key) + */ + var s2k_iteration_count_byte: any; + + /** + * Use integrity protection for symmetric encryption + */ + var integrity_protect: any; + + var ignore_mdc_error: any; + + var allow_unauthenticated_stream: any; + + var checksum_required: any; + + var rsa_blinding: any; + + /** + * Work-around for rare GPG decryption bug when encrypting with multiple passwords. + * **Slower and slightly less secure** + */ + var password_collision_check: any; + + var revocations_expire: any; + + var use_native: any; + + var min_bytes_for_web_crypto: any; + + var zero_copy: any; + + var debug: any; + + var tolerant: any; + + var show_version: any; + + var show_comment: any; + + var versionstring: any; + + var commentstring: any; + + var keyserver: any; + + var node_store: any; + + /** + * Max userid string length (used for parsing) + */ + var max_userid_length: any; + + namespace localStorage { + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); + + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; + + /** + * Writes the config to HTML5 local storage + */ + write(): void; + } + } } - /** Generating a session key for the specified symmetric algorithm - @param algo Algorithm to use - */ - function generateSessionKey(algo: enums.symmetric): string; + class LocalStorage { + /** + * This object is used for storing and retrieving configuration from HTML5 local storage. + */ + constructor(); - /** generate random byte prefix as string for the specified algorithm - @param algo Algorithm to use - */ - function getPrefixRandom(algo: enums.symmetric): string; + /** + * Reads the config out of the HTML5 local storage + * and initializes the object config. + * if config is null the default config will be used + */ + read(): void; - /** Returns the number of integers comprising the private key of an algorithm - @param algo The public key algorithm - */ - function getPrivateMpiCount(algo: enums.symmetric): number; - - /** Decrypts data using the specified public key multiprecision integers of the private key, the specified secretMPIs of the private key and the specified algorithm. - @param algo Algorithm to be used - @param publicMPIs Algorithm dependent multiprecision integers of the public key part of the private key - @param secretMPIs Algorithm dependent multiprecision integers of the private key used - @param data Data to be encrypted as MPI - */ - function publicKeyDecrypt(algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: Mpi): Mpi; - - /** Encrypts data using the specified public key multiprecision integers and the specified algorithm. - @param algo Algorithm to be used - @param publicMPIs Algorithm dependent multiprecision integers - @param data Data to be encrypted as MPI - */ - function publicKeyEncrypt(algo: enums.publicKey, publicMPIs: Array, data: Mpi): Array; - - - namespace cfb { - /** This function decrypts a given plaintext using the specified blockcipher to decrypt a message - @param cipherfn the algorithm cipher class to decrypt data in one block_size encryption - @param key binary string representation of key to be used to decrypt the ciphertext. This will be passed to the cipherfn - @param ciphertext to be decrypted provided as a string - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Decryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function decrypt(cipherfn: string, key: string, ciphertext: string, resync: boolean): string; - - /** This function encrypts a given with the specified prefixrandom using the specified blockcipher to encrypt a message - @param prefixrandom random bytes of block_size length provided as a string to be used in prefixing the data - @param cipherfn the algorithm cipher class to encrypt data in one block_size encryption - @param plaintext data to be encrypted provided as a string - @param key binary string representation of key to be used to encrypt the plaintext. This will be passed to the cipherfn - @param resync a boolean value specifying if a resync of the IV should be used or not. The encrypteddatapacket uses the "old" style with a resync. Encryption within an encryptedintegrityprotecteddata packet is not resyncing the IV. - */ - function encrypt(prefixrandom: string, cipherfn: string, plaintext: string, key: string, resync: boolean): string; - - /** Decrypts the prefixed data for the Modification Detection Code (MDC) computation - @param cipherfn cipherfn.encrypt Cipher function to use - @param key binary string representation of key to be used to check the mdc This will be passed to the cipherfn - @param ciphertext The encrypted data - */ - function mdc(cipherfn: Object, key: string, ciphertext: string): string; + /** + * Writes the config to HTML5 local storage + */ + write(): void; } - namespace hash { - /** Create a hash on the specified data using the specified algorithm - @param algo Hash algorithm type - @param data Data to be hashed - */ - function digest(algo: enums.hash, data: string): string; - /** Returns the hash size in bytes of the specified hash algorithm type - @param algo Hash algorithm type + + /** + * @see module:crypto/crypto + * @see module:crypto/signature + * @see module:crypto/public_key + * @see module:crypto/cipher + * @see module:crypto/random + * @see module:crypto/hash + */ + namespace crypto { + /** + * @see module:crypto/public_key/elliptic/ecdh + */ + namespace aes_kw { + /** + * AES key wrap + * @param key + * @param data + * @returns + */ + function wrap(key: string, data: string): Uint8Array; + + /** + * AES key unwrap + * @param key + * @param data + * @returns + * @throws + */ + function unwrap(key: string, data: string): Uint8Array; + } + + namespace cfb { + function encrypt(algo: any, key: any, plaintext: any, iv: any): any + function decrypt(algo: any, key: any, ciphertext: any, iv: any): Promise + } + + namespace cipher { + /** + * AES-128 encryption and decryption (ID 7) + * @param key 128-bit key + * @see + * @see + * @returns + */ + function aes128(key: string): object; + + /** + * AES-128 Block Cipher (ID 8) + * @param key 192-bit key + * @see + * @see + * @returns + */ + function aes192(key: string): object; + + /** + * AES-128 Block Cipher (ID 9) + * @param key 256-bit key + * @see + * @see + * @returns + */ + function aes256(key: string): object; + + /** + * Triple DES Block Cipher (ID 2) + * @param key 192-bit key + * @see + * @returns + */ + function tripledes(key: string): object; + + /** + * CAST-128 Block Cipher (ID 3) + * @param key 128-bit key + * @see + * @returns + */ + function cast5(key: string): object; + + /** + * Twofish Block Cipher (ID 10) + * @param key 256-bit key + * @see + * @returns + */ + function twofish(key: string): object; + + /** + * Blowfish Block Cipher (ID 4) + * @param key 128-bit key + * @see + * @returns + */ + function blowfish(key: string): object; + + /** + * Not implemented + * @throws + */ + function idea(): void; + } + + namespace cmac { + /** + * This implementation of CMAC is based on the description of OMAC in + * http://web.cs.ucdavis.edu/~rogaway/papers/eax.pdf. As per that + * document: + * We have made a small modification to the OMAC algorithm as it was + * originally presented, changing one of its two constants. + * Specifically, the constant 4 at line 85 was the constant 1/2 (the + * multiplicative inverse of 2) in the original definition of OMAC [14]. + * The OMAC authors indicate that they will promulgate this modification + * [15], which slightly simplifies implementations. + */ + const blockLength: any; + + /** + * xor `padding` into the end of `data`. This function implements "the + * operation xor→ [which] xors the shorter string into the end of longer + * one". Since data is always as least as long as padding, we can + * simplify the implementation. + * @param data + * @param padding + */ + function rightXorMut(data: Uint8Array, padding: Uint8Array): void; + } + + namespace crypto { + /** + * Encrypts data using specified algorithm and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param pub_params Algorithm-specific public key parameters + * @param data Data to be encrypted as MPI + * @param fingerprint Recipient fingerprint + * @returns encrypted session key parameters + */ + function publicKeyEncrypt(algo: enums.publicKey, pub_params: Array, data: type.mpi.MPI, fingerprint: string): any[]; + + /** + * Decrypts data using specified algorithm and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} for public key algorithms. + * @param algo Public key algorithm + * @param key_params Algorithm-specific public, private key parameters + * @param data_params encrypted session key parameters + * @param fingerprint Recipient fingerprint + * @returns An MPI containing the decrypted data + */ + function publicKeyDecrypt(algo: enums.publicKey, key_params: Array, data_params: Array, fingerprint: string): type.mpi.MPI; + + /** + * Returns the types comprising the private key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPrivKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the public key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getPubKeyParamTypes(algo: string): any[]; + + /** + * Returns the types comprising the encrypted session key of an algorithm + * @param algo The public key algorithm + * @returns The array of types + */ + function getEncSessionKeyParamTypes(algo: string): any[]; + + /** + * Generate algorithm-specific key parameters + * @param algo The public key algorithm + * @param bits Bit length for RSA keys + * @param oid Object identifier for ECC keys + * @returns The array of parameters + */ + function generateParams(algo: string, bits: Integer, oid: type.oid.OID): any[]; + + /** + * Generates a random byte prefix for the specified algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes with length equal to the block size of the cipher, plus the last two bytes repeated. + */ + function getPrefixRandom(algo: enums.symmetric): Uint8Array; + + /** + * Generating a session key for the specified symmetric algorithm + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param algo Symmetric encryption algorithm + * @returns Random bytes as a string to be used as a key + */ + function generateSessionKey(algo: enums.symmetric): Uint8Array; + } + + namespace eax { + /** + * Class to en/decrypt using EAX mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function EAX(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (16 bytes) + * @param adata Associated data to verify + * @returns The plaintext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + namespace gcm { + /** + * Class to en/decrypt using GCM mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function GCM(cipher: string, key: Uint8Array): void; + } + + /** + * @see + * @see + */ + namespace hash { + /** + * @see module:md5 + */ + var md5: any; + + /** + * @see asmCrypto + */ + var sha1: any; + + /** + * @see hash.js + */ + var sha224: any; + + /** + * @see asmCrypto + */ + var sha256: any; + + /** + * @see hash.js + */ + var sha384: any; + + /** + * @see asmCrypto + */ + var sha512: any; + + /** + * @see hash.js + */ + var ripemd: any; + + /** + * Create a hash on the specified data using the specified algorithm + * @param algo Hash algorithm type (see {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @param data Data to be hashed + * @returns hash value + */ + function digest(algo: enums.hash, data: Uint8Array): Promise; + + /** + * Returns the hash size in bytes of the specified hash algorithm type + * @param algo Hash algorithm type (See {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4}) + * @returns Size in bytes of the resulting hash + */ + function getHashByteLength(algo: enums.hash): Integer; + } + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + namespace pkcs5 { + /** + * Add pkcs5 padding to a text. + * @param msg Text to add padding + * @returns Text with padding added + */ + function encode(msg: string): string; + + /** + * Remove pkcs5 padding from a string. + * @param msg Text to remove padding from + * @returns Text with padding removed + */ + function decode(msg: string): string; + } + + namespace ocb { + /** + * Class to en/decrypt using OCB mode. + * @param cipher The symmetric cipher algorithm to use e.g. 'aes128' + * @param key The encryption key + */ + function OCB(cipher: string, key: Uint8Array): void; + + /** + * Encrypt plaintext input. + * @param plaintext The cleartext input to be encrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function encrypt(plaintext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + + /** + * Decrypt ciphertext input. + * @param ciphertext The ciphertext input to be decrypted + * @param nonce The nonce (15 bytes) + * @param adata Associated data to sign + * @returns The ciphertext output + */ + function decrypt(ciphertext: Uint8Array, nonce: Uint8Array, adata: Uint8Array): Promise; + } + + /** + * @see module:crypto/public_key/rsa + * @see module:crypto/public_key/elliptic/ecdh + * @see module:packet.PublicKeyEncryptedSessionKey */ - function getHashByteLength(algo: enums.hash): number; + namespace pkcs1 { + namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; + + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; + } + + namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; + } + + /** + * ASN1 object identifiers for hashes + * @see + */ + const hash_headers: any; + } + + namespace public_key { + namespace dsa { + /** + * DSA Sign function + * @param hash_algo + * @param hashed + * @param g + * @param p + * @param q + * @param x + * @returns + */ + function sign(hash_algo: Integer, hashed: Uint8Array, g: BN, p: BN, q: BN, x: BN): object; + + /** + * DSA Verify function + * @param hash_algo + * @param r + * @param s + * @param hashed + * @param g + * @param p + * @param q + * @param y + * @returns BN + */ + function verify(hash_algo: Integer, r: BN, s: BN, hashed: Uint8Array, g: BN, p: BN, q: BN, y: BN): any; + } + + namespace elgamal { + /** + * ElGamal Encryption function + * @param m + * @param p + * @param g + * @param y + * @returns + */ + function encrypt(m: BN, p: BN, g: BN, y: BN): object; + + /** + * ElGamal Encryption function + * @param c1 + * @param c2 + * @param p + * @param x + * @returns BN + */ + function decrypt(c1: BN, c2: BN, p: BN, x: BN): any; + } + + /** + * @see module:crypto/public_key/elliptic/curve + * @see module:crypto/public_key/elliptic/ecdh + * @see module:crypto/public_key/elliptic/ecdsa + * @see module:crypto/public_key/elliptic/eddsa + */ + namespace elliptic { + namespace curve { + class Curve { + } + } + + namespace ecdh { + /** + * Generate ECDHE ephemeral key and secret from public key + * @param curve Elliptic curve object + * @param Q Recipient public key + * @returns Returns public part of ephemeral key and generated ephemeral secret + */ + function genPublicEphemeralKey(curve: curve.Curve, Q: Uint8Array): Promise<{ V: Uint8Array, S: BN }>; + + /** + * Encrypt and wrap a session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param m Value derived from session key (RFC 6637) + * @param Q Recipient public key + * @param fingerprint Recipient fingerprint + * @returns Returns public part of ephemeral key and encoded session key + */ + function encrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, m: type.mpi.MPI, Q: Uint8Array, fingerprint: string): Promise<{ V: BN, C: BN }>; + + /** + * Generate ECDHE secret from private key and public part of ephemeral key + * @param curve Elliptic curve object + * @param V Public part of ephemeral key + * @param d Recipient private key + * @returns Generated ephemeral secret + */ + function genPrivateEphemeralKey(curve: curve.Curve, V: Uint8Array, d: Uint8Array): Promise; + + /** + * Decrypt and unwrap the value derived from session key + * @param oid Elliptic curve object identifier + * @param cipher_algo Symmetric cipher to use + * @param hash_algo Hash algorithm to use + * @param V Public part of ephemeral key + * @param C Encrypted and wrapped value derived from session key + * @param d Recipient private key + * @param fingerprint Recipient fingerprint + * @returns Value derived from session + */ + function decrypt(oid: type.oid.OID, cipher_algo: enums.symmetric, hash_algo: enums.hash, V: Uint8Array, C: Uint8Array, d: Uint8Array, fingerprint: string): Promise; + } + + namespace ecdsa { + /** + * Sign a message using the provided key + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign the message + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; + + /** + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns + */ + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace eddsa { + /** + * Sign a message using the provided keygit + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used to sign + * @param m Message to sign + * @param d Private key used to sign + * @param hashed The hashed message + * @returns Signature of the message + */ + function sign(oid: type.oid.OID, hash_algo: enums.hash, m: Uint8Array, d: Uint8Array, hashed: Uint8Array): object; + + /** + * Verifies if a signature is valid for a message + * @param oid Elliptic curve object identifier + * @param hash_algo Hash algorithm used in the signature + * @param signature Signature to verify the message + * @param m Message to verify + * @param Q Public key used to verify the message + * @param hashed The hashed message + * @returns + */ + function verify(oid: type.oid.OID, hash_algo: enums.hash, signature: object, m: Uint8Array, Q: Uint8Array, hashed: Uint8Array): boolean; + } + + namespace key { + class KeyPair { + } + } + } + + namespace prime { + /** + * Probabilistic random number generator + * @param bits Bit length of the prime + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns BN + */ + function randomProbablePrime(bits: Integer, e: BN, k: Integer): any; + + /** + * Probabilistic primality testing + * @param n Number to test + * @param e Optional RSA exponent to check against the prime + * @param k Optional number of iterations of Miller-Rabin test + * @returns + */ + function isProbablePrime(n: BN, e: BN, k: Integer): boolean; + + /** + * Tests whether n is probably prime or not using Fermat's test with b = 2. + * Fails if b^(n-1) mod n === 1. + * @param n Number to test + * @param b Optional Fermat test base + * @returns + */ + function fermat(n: BN, b: Integer): boolean; + + /** + * Tests whether n is probably prime or not using the Miller-Rabin test. + * See HAC Remark 4.28. + * @param n Number to test + * @param k Optional number of iterations of Miller-Rabin test + * @param rand Optional function to generate potential witnesses + * @returns + */ + function millerRabin(n: BN, k: Integer, rand: Function): boolean; + } + + namespace rsa { + /** + * Create signature + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @returns RSA Signature + */ + function sign(m: BN, n: BN, e: BN, d: BN): BN; + + /** + * Verify signature + * @param s signature + * @param n RSA public modulus + * @param e RSA public exponent + * @returns + */ + function verify(s: BN, n: BN, e: BN): BN; + + /** + * Encrypt message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @returns RSA Ciphertext + */ + function encrypt(m: BN, n: BN, e: BN): BN; + + /** + * Decrypt RSA message + * @param m message + * @param n RSA public modulus + * @param e RSA public exponent + * @param d RSA private exponent + * @param p RSA private prime p + * @param q RSA private prime q + * @param u RSA private inverse of prime q + * @returns RSA Plaintext + */ + function decrypt(m: BN, n: BN, e: BN, d: BN, p: BN, q: BN, u: BN): BN; + + /** + * Generate a new random private key B bits long with public exponent E. + * When possible, webCrypto is used. Otherwise, primes are generated using + * 40 rounds of the Miller-Rabin probabilistic random prime generation algorithm. + * @see module:crypto/public_key/prime + * @param B RSA bit length + * @param E RSA public exponent in hex string + * @returns RSA public modulus, RSA public exponent, RSA private exponent, + * RSA private prime p, RSA private prime q, u = q ** -1 mod p + */ + function generate(B: Integer, E: string): object; + } + } + + namespace random { + /** + * Retrieve secure random byte array of the specified length + * @param length Length in bytes to generate + * @returns Random byte array + */ + function getRandomBytes(length: Integer): Uint8Array; + + /** + * Create a secure random MPI that is greater than or equal to min and less than max. + * @param min Lower bound, included + * @param max Upper bound, excluded + * @returns Random MPI + */ + function getRandomBN(min: type.mpi.MPI, max: type.mpi.MPI): BN; + + /** + * Buffer for secure random numbers + */ + function RandomBuffer(): void; + } + + namespace signature { + /** + * Verifies the signature provided for data using specified algorithms and public key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param msg_MPIs Algorithm-specific signature parameters + * @param pub_MPIs Algorithm-specific public key parameters + * @param data Data for which the signature was created + * @param hashed The hashed data + * @returns True if signature is valid + */ + function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: type.mpi.MPI[], pub_MPIs: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): boolean; + + /** + * Creates a signature on data using specified algorithms and private key parameters. + * See {@link https://tools.ietf.org/html/rfc4880#section-9.1|RFC 4880 9.1} + * and {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC 4880 9.4} + * for public key and hash algorithms. + * @param algo Public key algorithm + * @param hash_algo Hash algorithm + * @param key_params Algorithm-specific public and private key parameters + * @param data Data to be signed + * @param hashed The hashed data + * @returns Signature + */ + function sign(algo: enums.publicKey, hash_algo: enums.hash, key_params: type.mpi.MPI[], data: Uint8Array, hashed: Uint8Array): Uint8Array; + } } - namespace random { - /** Create a secure random big integer of bits length - @param bits Bit length of the MPI to create - */ - function getRandomBigInteger(bits: number): number; + namespace eme { + /** + * Create a EME-PKCS1-v1_5 padded message + * @see + * @param M message to be encoded + * @param k the length in octets of the key modulus + * @returns EME-PKCS1 padded message + */ + function encode(M: string, k: Integer): Promise; - /** Retrieve secure random byte string of the specified length - @param length Length in bytes to generate - */ - function getRandomBytes(length: number): string; + /** + * Decode a EME-PKCS1-v1_5 padded message + * @see + * @param EM encoded message, an octet string + * @returns message, an octet string + */ + function decode(EM: string): string; + } - /** Helper routine which calls platform specific crypto random generator - @param buf - */ - function getRandomValues(buf: Uint8Array): void; + namespace emsa { + /** + * Create a EMSA-PKCS1-v1_5 padded message + * @see + * @param algo Hash algorithm type used + * @param hashed message to be encoded + * @param emLen intended length in octets of the encoded message + * @returns encoded message + */ + function encode(algo: Integer, hashed: Uint8Array, emLen: Integer): string; + } - /** Return a secure random number in the specified range - @param from Min of the random number - @param to Max of the random number (max 32bit) - */ - function getSecureRandom(from: number, to: number): number; + namespace encoding { + namespace armor { + /** + * Add additional information to the armor version of an OpenPGP binary + * packet block. + * @author Alex + * @version 2011-12-16 + * @param customComment (optional) additional comment to add to the armored string + * @returns The header information + */ + function addheader(customComment: string): string; + + /** + * Calculates a checksum over the given data and returns it base64 encoded + * @param data Data to create a CRC-24 checksum for + * @returns Base64 encoded checksum + */ + function getCheckSum(data: string | ReadableStream): string | ReadableStream; + + /** + * Internal function to calculate a CRC-24 checksum over a given string (data) + * @param data Data to create a CRC-24 checksum for + * @returns The CRC-24 checksum + */ + function createcrc24(data: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Splits a message into two parts, the body and the checksum. This is an internal function + * @param text OpenPGP armored message part + * @returns An object with attribute "body" containing the body + * and an attribute "checksum" containing the checksum. + */ + function splitChecksum(text: string): object; + + /** + * DeArmor an OpenPGP armored message; verify the checksum and return + * the encoded bytes + * @param text OpenPGP armored message + * @returns An object with attribute "text" containing the message text, + * an attribute "data" containing a stream of bytes and "type" for the ASCII armor type + */ + function dearmor(text: string): Promise; + + /** + * Armor an OpenPGP binary packet block + * @param messagetype type of the message + * @param body + * @param partindex + * @param parttotal + * @param customComment (optional) additional comment to add to the armored string + * @returns Armored text + */ + function armor(messagetype: Integer, body: any, partindex: Integer, parttotal: Integer, customComment?: string): string | ReadableStream; + } + + namespace base64 { + /** + * Convert binary array to radix-64 + * @param t Uint8Array to convert + * @param u if true, output is URL-safe + * @returns radix-64 version of input string + */ + function s2r(t: Uint8Array | ReadableStream, u?: boolean): string | ReadableStream; + + /** + * Convert radix-64 to binary array + * @param t radix-64 string to convert + * @param u if true, input is interpreted as URL-safe + * @returns binary array version of input string + */ + function r2s(t: string | ReadableStream, u: boolean): Uint8Array | ReadableStream; + } + } + + namespace enums { + /** + * Maps curve names under various standards to one + * @see + */ + enum curve { + /** + * NIST P-256 Curve + */ + p256 = "p256", + "P-256" = "p256", + secp256r1 = "p256", + prime256v1 = "p256", + "1.2.840.10045.3.1.7" = "p256", + "2a8648ce3d030107" = "p256", + "2A8648CE3D030107" = "p256", + /** + * NIST P-384 Curve + */ + p384 = "p384", + "P-384" = "p384", + secp384r1 = "p384", + "1.3.132.0.34" = "p384", + "2b81040022" = "p384", + "2B81040022" = "p384", + /** + * NIST P-521 Curve + */ + p521 = "p521", + "P-521" = "p521", + secp521r1 = "p521", + "1.3.132.0.35" = "p521", + "2b81040023" = "p521", + "2B81040023" = "p521", + /** + * SECG SECP256k1 Curve + */ + secp256k1 = "secp256k1", + "1.3.132.0.10" = "secp256k1", + "2b8104000a" = "secp256k1", + "2B8104000A" = "secp256k1", + /** + * Ed25519 + */ + ED25519 = "ed25519", + ed25519 = "ed25519", + Ed25519 = "ed25519", + "1.3.6.1.4.1.11591.15.1" = "ed25519", + "2b06010401da470f01" = "ed25519", + "2B06010401DA470F01" = "ed25519", + /** + * Curve25519 + */ + X25519 = "curve25519", + cv25519 = "curve25519", + curve25519 = "curve25519", + Curve25519 = "curve25519", + "1.3.6.1.4.1.3029.1.5.1" = "curve25519", + "2b060104019755010501" = "curve25519", + "2B060104019755010501" = "curve25519", + /** + * BrainpoolP256r1 Curve + */ + brainpoolP256r1 = "brainpoolP256r1", + "1.3.36.3.3.2.8.1.1.7" = "brainpoolP256r1", + "2b2403030208010107" = "brainpoolP256r1", + "2B2403030208010107" = "brainpoolP256r1", + /** + * BrainpoolP384r1 Curve + */ + brainpoolP384r1 = "brainpoolP384r1", + "1.3.36.3.3.2.8.1.1.11" = "brainpoolP384r1", + "2b240303020801010b" = "brainpoolP384r1", + "2B240303020801010B" = "brainpoolP384r1", + /** + * BrainpoolP512r1 Curve + */ + brainpoolP512r1 = "brainpoolP512r1", + "1.3.36.3.3.2.8.1.1.13" = "brainpoolP512r1", + "2b240303020801010d" = "brainpoolP512r1", + "2B240303020801010D" = "brainpoolP512r1", + } + + /** + * A string to key specifier type + */ + enum s2k { + simple = 0, + salted = 1, + iterated = 3, + gnu = 101, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.1|RFC4880bis-04, section 9.1} + */ + enum publicKey { + /** + * RSA (Encrypt or Sign) [HAC] + */ + rsa_encrypt_sign = 1, + /** + * RSA (Encrypt only) [HAC] + */ + rsa_encrypt = 2, + /** + * RSA (Sign only) [HAC] + */ + rsa_sign = 3, + /** + * Elgamal (Encrypt only) [ELGAMAL] [HAC] + */ + elgamal = 16, + /** + * DSA (Sign only) [FIPS186] [HAC] + */ + dsa = 17, + /** + * ECDH (Encrypt only) [RFC6637] + */ + ecdh = 18, + /** + * ECDSA (Sign only) [RFC6637] + */ + ecdsa = 19, + /** + * EdDSA (Sign only) + * [ {@link https://tools.ietf.org/html/draft-koch-eddsa-for-openpgp-04|Draft RFC}] + */ + eddsa = 22, + /** + * Reserved for AEDH + */ + aedh = 23, + /** + * Reserved for AEDSA + */ + aedsa = 24, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC4880, section 9.2} + */ + enum symmetric { + plaintext = 0, + /** + * Not implemented! + */ + idea = 1, + "3des" = 2, + tripledes = 2, + cast5 = 3, + blowfish = 4, + aes128 = 7, + aes192 = 8, + aes256 = 9, + twofish = 10, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.3|RFC4880, section 9.3} + */ + enum compression { + uncompressed = 0, + /** + * RFC1951 + */ + zip = 1, + /** + * RFC1950 + */ + zlib = 2, + bzip2 = 3, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-9.4|RFC4880, section 9.4} + */ + enum hash { + md5 = 1, + sha1 = 2, + ripemd = 3, + sha256 = 8, + sha384 = 9, + sha512 = 10, + sha224 = 11, + } + + /** + * A list of hash names as accepted by webCrypto functions. + * {@link https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/digest|Parameters, algo} + */ + enum webHash { + "SHA-1" = 2, + "SHA-256" = 8, + "SHA-384" = 9, + "SHA-512" = 10, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-9.6|RFC4880bis-04, section 9.6} + */ + enum aead { + eax = 1, + ocb = 2, + experimental_gcm = 100, + } + + /** + * A list of packet types and numeric tags associated with them. + */ + enum packet { + publicKeyEncryptedSessionKey = 1, + signature = 2, + symEncryptedSessionKey = 3, + onePassSignature = 4, + secretKey = 5, + publicKey = 6, + secretSubkey = 7, + compressed = 8, + symmetricallyEncrypted = 9, + marker = 10, + literal = 11, + trust = 12, + userid = 13, + publicSubkey = 14, + userAttribute = 17, + symEncryptedIntegrityProtected = 18, + modificationDetectionCode = 19, + symEncryptedAEADProtected = 20, + } + + /** + * Data types in the literal packet + */ + enum literal { + /** + * Binary data 'b' + */ + binary = "", + /** + * Text data 't' + */ + text = "", + /** + * Utf8 data 'u' + */ + utf8 = "", + /** + * MIME message body part 'm' + */ + mime = "", + } + + /** + * One pass signature packet type + */ + enum signature { + /** + * 0x00: Signature of a binary document. + */ + binary = 0, + /** + * 0x01: Signature of a canonical text document. + * Canonicalyzing the document by converting line endings. + */ + text = 1, + /** + * 0x02: Standalone signature. + * This signature is a signature of only its own subpacket contents. + * It is calculated identically to a signature over a zero-lengh + * binary document. Note that it doesn't make sense to have a V3 + * standalone signature. + */ + standalone = 2, + /** + * 0x10: Generic certification of a User ID and Public-Key packet. + * The issuer of this certification does not make any particular + * assertion as to how well the certifier has checked that the owner + * of the key is in fact the person described by the User ID. + */ + cert_generic = 16, + /** + * 0x11: Persona certification of a User ID and Public-Key packet. + * The issuer of this certification has not done any verification of + * the claim that the owner of this key is the User ID specified. + */ + cert_persona = 17, + /** + * 0x12: Casual certification of a User ID and Public-Key packet. + * The issuer of this certification has done some casual + * verification of the claim of identity. + */ + cert_casual = 18, + /** + * 0x13: Positive certification of a User ID and Public-Key packet. + * The issuer of this certification has done substantial + * verification of the claim of identity. + * Most OpenPGP implementations make their "key signatures" as 0x10 + * certifications. Some implementations can issue 0x11-0x13 + * certifications, but few differentiate between the types. + */ + cert_positive = 19, + /** + * 0x30: Certification revocation signature + * This signature revokes an earlier User ID certification signature + * (signature class 0x10 through 0x13) or direct-key signature + * (0x1F). It should be issued by the same key that issued the + * revoked signature or an authorized revocation key. The signature + * is computed over the same data as the certificate that it + * revokes, and should have a later creation date than that + * certificate. + */ + cert_revocation = 48, + /** + * 0x18: Subkey Binding Signature + * This signature is a statement by the top-level signing key that + * indicates that it owns the subkey. This signature is calculated + * directly on the primary key and subkey, and not on any User ID or + * other packets. A signature that binds a signing subkey MUST have + * an Embedded Signature subpacket in this binding signature that + * contains a 0x19 signature made by the signing subkey on the + * primary key and subkey. + */ + subkey_binding = 24, + /** + * 0x19: Primary Key Binding Signature + * This signature is a statement by a signing subkey, indicating + * that it is owned by the primary key and subkey. This signature + * is calculated the same way as a 0x18 signature: directly on the + * primary key and subkey, and not on any User ID or other packets. + * When a signature is made over a key, the hash data starts with the + * octet 0x99, followed by a two-octet length of the key, and then body + * of the key packet. (Note that this is an old-style packet header for + * a key packet with two-octet length.) A subkey binding signature + * (type 0x18) or primary key binding signature (type 0x19) then hashes + * the subkey using the same format as the main key (also using 0x99 as + * the first octet). + */ + key_binding = 25, + /** + * 0x1F: Signature directly on a key + * This signature is calculated directly on a key. It binds the + * information in the Signature subpackets to the key, and is + * appropriate to be used for subpackets that provide information + * about the key, such as the Revocation Key subpacket. It is also + * appropriate for statements that non-self certifiers want to make + * about the key itself, rather than the binding between a key and a + * name. + */ + key = 31, + /** + * 0x20: Key revocation signature + * The signature is calculated directly on the key being revoked. A + * revoked key is not to be used. Only revocation signatures by the + * key being revoked, or by an authorized revocation key, should be + * considered valid revocation signatures.a + */ + key_revocation = 32, + /** + * 0x28: Subkey revocation signature + * The signature is calculated directly on the subkey being revoked. + * A revoked subkey is not to be used. Only revocation signatures + * by the top-level signature key that is bound to this subkey, or + * by an authorized revocation key, should be considered valid + * revocation signatures. + * Key revocation signatures (types 0x20 and 0x28) + * hash only the key being revoked. + */ + subkey_revocation = 40, + /** + * 0x40: Timestamp signature. + * This signature is only meaningful for the timestamp contained in + * it. + */ + timestamp = 64, + /** + * 0x50: Third-Party Confirmation signature. + * This signature is a signature over some other OpenPGP Signature + * packet(s). It is analogous to a notary seal on the signed data. + * A third-party signature SHOULD include Signature Target + * subpacket(s) to give easy identification. Note that we really do + * mean SHOULD. There are plausible uses for this (such as a blind + * party that only sees the signature, not the key or source + * document) that cannot include a target subpacket. + */ + third_party = 80, + } + + /** + * Signature subpacket type + */ + enum signatureSubpacket { + signature_creation_time = 2, + signature_expiration_time = 3, + exportable_certification = 4, + trust_signature = 5, + regular_expression = 6, + revocable = 7, + key_expiration_time = 9, + placeholder_backwards_compatibility = 10, + preferred_symmetric_algorithms = 11, + revocation_key = 12, + issuer = 16, + notation_data = 20, + preferred_hash_algorithms = 21, + preferred_compression_algorithms = 22, + key_server_preferences = 23, + preferred_key_server = 24, + primary_user_id = 25, + policy_uri = 26, + key_flags = 27, + signers_user_id = 28, + reason_for_revocation = 29, + features = 30, + signature_target = 31, + embedded_signature = 32, + issuer_fingerprint = 33, + preferred_aead_algorithms = 34, + } + + /** + * Key flags + */ + enum keyFlags { + /** + * 0x01 - This key may be used to certify other keys. + */ + certify_keys = 1, + /** + * 0x02 - This key may be used to sign data. + */ + sign_data = 2, + /** + * 0x04 - This key may be used to encrypt communications. + */ + encrypt_communication = 4, + /** + * 0x08 - This key may be used to encrypt storage. + */ + encrypt_storage = 8, + /** + * 0x10 - The private component of this key may have been split + * by a secret-sharing mechanism. + */ + split_private_key = 16, + /** + * 0x20 - This key may be used for authentication. + */ + authentication = 32, + /** + * 0x80 - The private component of this key may be in the + * possession of more than one person. + */ + shared_private_key = 128, + } + + /** + * Key status + */ + enum keyStatus { + invalid = 0, + expired = 1, + revoked = 2, + valid = 3, + no_self_cert = 4, + } + + /** + * Armor type + */ + enum armor { + multipart_section = 0, + multipart_last = 1, + signed = 2, + message = 3, + public_key = 4, + private_key = 5, + signature = 6, + } + + /** + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.3.23|RFC4880, section 5.2.3.23} + */ + enum reasonForRevocation { + /** + * No reason specified (key revocations or cert revocations) + */ + no_reason = 0, + /** + * Key is superseded (key revocations) + */ + key_superseded = 1, + /** + * Key material has been comPromised (key revocations) + */ + key_comPromised = 2, + /** + * Key is retired and no longer used (key revocations) + */ + key_retired = 3, + /** + * User ID information is no longer valid (cert revocations) + */ + userid_invalid = 32, + } + + /** + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.2.3.25|RFC4880bis-04, section 5.2.3.25} + */ + enum features { + /** + * 0x01 - Modification Detection (packets 18 and 19) + */ + modification_detection = 1, + /** + * 0x02 - AEAD Encrypted Data Packet (packet 20) and version 5 + * Symmetric-Key Encrypted Session Key Packets (packet 3) + */ + aead = 2, + /** + * 0x04 - Version 5 Public-Key Packet format and corresponding new + * fingerprint format + */ + v5_keys = 4, + } + + /** + * Asserts validity and converts from string/integer to integer. + */ + function write(): void; + + /** + * Converts from an integer to string. + */ + function read(): void; + } + + namespace hkp { + class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; + } + } + + class HKP { + /** + * Initialize the HKP client and configure it with the key server url and fetch function. + * @param keyServerBaseUrl (optional) The HKP key server base url including + * the protocol to use, e.g. 'https://pgp.mit.edu'; defaults to + * openpgp.config.keyserver (https://keyserver.ubuntu.com) + */ + constructor(keyServerBaseUrl: string); + + /** + * Search for a public key on the key server either by key ID or part of the user ID. + * @param options.keyID The long public key ID. + * @param options.query This can be any part of the key user ID such as name + * or email address. + * @returns The ascii armored public key. + */ + lookup(): Promise; + + /** + * Upload a public key to the server. + * @param publicKeyArmored An ascii armored public key to be uploaded. + * @returns + */ + upload(publicKeyArmored: string): Promise; + } + + namespace key { + /** + * Class that represents an OpenPGP key. Must contain a primary key. + * Can contain additional subkeys, signatures, user ids, user attributes. + */ + class Key { + /** + * @param packetlist The packets that form this key + */ + constructor(packetlist: packet.List); + + /** + * Transforms packetlist to structured key data + * @param packetlist The packets that form a key + */ + packetlist2structure(packetlist: packet.List): void; + + /** + * Transforms structured key data to packetlist + * @returns The packets that form a key + */ + toPacketlist(): packet.List; + + /** + * Returns an array containing all public or private subkeys matching keyId; + * If keyId is not present, returns all subkeys. + * @param keyId + * @returns + */ + getSubkeys(keyId: type.keyid.Keyid): any[]; + + /** + * Returns an array containing all public or private keys matching keyId. + * If keyId is not present, returns all keys starting with the primary key. + * @param keyId + * @returns + */ + getKeys(keyId: type.keyid.Keyid): any[]; + + /** + * Returns key IDs of all keys + * @returns + */ + getKeyIds(): any[]; + + /** + * Returns userids + * @returns array of userids + */ + getUserIds(): any[]; + + /** + * Returns true if this is a public key + * @returns + */ + isPublic(): boolean; + + /** + * Returns true if this is a private key + * @returns + */ + isPrivate(): boolean; + + /** + * Returns key as public key (shallow copy) + * @returns new public Key + */ + toPublic(): Key; + + /** + * Returns ASCII armored text of key + * @returns ASCII armor + */ + armor(): ReadableStream; + + /** + * Returns last created key or key by given keyId that is available for signing and verification + * @param keyId, optional + * @param date (optional) use the given date for verification instead of the current time + * @param userId, optional user ID + * @returns key or null if no signing key has been found + */ + getSigningKey(keyId: type.keyid.Keyid, date?: Date, userId?: object): Promise; + + /** + * Returns last created key or key by given keyId that is available for encryption or decryption + * @param keyId, optional + * @param date, optional + * @param userId, optional + * @returns key or null if no encryption key has been found + */ + getEncryptionKey(keyId?: type.keyid.Keyid, date?: Date, userId?: string): Promise; + + /** + * Encrypts all secret key and subkey packets matching keyId + * @param passphrases - if multiple passphrases, then should be in same order as packets each should encrypt + * @param keyId + * @returns + */ + encrypt(passphrases: string | any[], keyId?: type.keyid.Keyid): Promise>; + + /** + * Decrypts all secret key and subkey packets matching keyId + * @param passphrases + * @param keyId + * @returns true if all matching key and subkey packets decrypted successfully + */ + decrypt(passphrases: string | string[], keyId?: type.keyid.Keyid): Promise; + + /** + * Checks if a signature on a key is revoked + * @param + * @param signature The signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(signature: packet.Signature, key?: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date?: Date): Promise; + + /** + * Verify primary key. Checks for revocation signatures, expiration time + * and valid self signature + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns The status of the primary key + */ + verifyPrimaryKey(date?: Date, userId?: object): Promise; + + /** + * Returns the latest date when the key can be used for encrypting, signing, or both, depending on the `capabilities` paramater. + * When `capabilities` is null, defaults to returning the expiry date of the primary key. + * Returns null if `capabilities` is passed and the key does not have the specified capabilities or is revoked or invalid. + * Returns Infinity if the key doesn't expire. + * @param {encrypt | sign | encrypt_sign} capabilities, optional + * @param keyId, optional + * @param userId, optional user ID + * @returns + */ + getExpirationTime(capabilities: any, keyId: type.keyid.Keyid, userId: object): Promise; + + /** + * Returns primary user and most significant (latest valid) self signature + * - if multiple primary users exist, returns the one with the latest self signature + * - otherwise, returns the user with the latest self signature + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns The primary user and the self signature + */ + getPrimaryUser(date: Date, userId: object): Promise<{ user: User, selfCertification: packet.Signature }>; + + /** + * Update key with new components from specified key with same key ID: + * users, subkeys, certificates are merged into the destination key, + * duplicates and expired signatures are ignored. + * If the specified key is a private key and the destination key is public, + * the destination key is transformed to a private key. + * @param key Source key to merge + * @returns + */ + update(key: Key): Promise; + + /** + * Revokes the key + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new key with revocation signature + */ + revoke(reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Get revocation certificate from a revoked key. + * (To get a revocation certificate for an unrevoked key, call revoke() first.) + * @returns armored revocation certificate + */ + getRevocationCertificate(): Promise; + + /** + * Applies a revocation certificate to a key + * This adds the first signature packet in the armored text to the key, + * if it is a valid revocation signature. + * @param revocationCertificate armored revocation certificate + * @returns new revoked key + */ + applyRevocationCertificate(revocationCertificate: string): Promise; + + /** + * Signs primary user of key + * @param privateKey decrypted private keys for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns new public key with new certificate signature + */ + signPrimaryUser(privateKey: any[], date: Date, userId: object): Promise; + + /** + * Signs all users of key + * @param privateKeys decrypted private keys for signing + * @returns new public key with new certificate signature + */ + signAllUsers(privateKeys: any[]): Promise; + + /** + * Verifies primary user of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID to get instead of the primary user, if it exists + * @returns List of signer's keyid and validity of signature + */ + verifyPrimaryUser(keys: any[], date: Date, userId: object): Promise>; + + /** + * Verifies all users of key + * - if no arguments are given, verifies the self certificates; + * - otherwise, verifies all certificates signed with given keys. + * @param keys array of keys to verify certificate signatures + * @returns list of userid, signer's keyid and validity of signature + */ + verifyAllUsers(keys: any[]): Promise>; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * Returns the valid and non-expired signature that has the latest creation date, while ignoring signatures created in the future. + * @param signatures List of signatures + * @param date Use the given date instead of the current time + * @returns The latest valid signature + */ + function getLatestValidSignature(signatures: any[], date: Date): Promise; + + /** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ + class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + } + + /** + * Create signature packet + * @param dataToSign Contains packets to be signed + * @param signingKeyPacket secret key packet for signing + * @param signatureProperties (optional) properties to write on the signature packet before signing + * @param date (optional) override the creationtime of the signature + * @param userId (optional) user ID + * @returns signature packet + */ + function createSignaturePacket(dataToSign: object, signingKeyPacket: packet.SecretKey | packet.SecretSubkey, signatureProperties: object, date: Date, userId: object): packet.Signature; + + /** + * Class that represents a subkey packet and the relevant signatures. + */ + class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * Reads an unarmored OpenPGP key list and returns one or multiple key objects + * @param data to be parsed + * @returns result object with key and error arrays + */ + function read(data: Uint8Array): Promise<{ keys: Array, err: Array | null }>; + + interface KeyResult { keys: Array, err: Array | null } + + /** + * Reads an OpenPGP armored text and returns one or multiple key objects + * @param armoredText text to be parsed + * @returns result object with key and error arrays + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * Generates a new OpenPGP key. Supports RSA and ECC keys. + * Primary and subkey will be of same type. + * @param options.keyType To indicate what type of key to make. + * RSA is 1. See {@link https://tools.ietf.org/html/rfc4880#section-9.1} + * @param options.numBits number of bits for the key creation. + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param curve (optional) elliptic curve for ECC keys + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + * @returns + */ + function generate(options: KeyOptions): Promise; + + /** + * Reformats and signs an OpenPGP key with a given User ID. Currently only supports RSA keys. + * @param options.privateKey The private key to reformat + * @param options.keyType + * @param options.userIds Assumes already in form of "User Name " + * If array is used, the first userId is set as primary user Id + * @param options.passphrase The passphrase used to encrypt the resulting private key + * @param options.keyExpirationTime The number of seconds after the key creation time that the key expires + * @param date Override the creation date of the key and the key signatures + * @param subkeys (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * @returns + */ + function reformat(date: Date, subkeys: any[]): Promise; + + /** + * Checks if a given certificate or binding signature is revoked + * @param primaryKey The primary key packet + * @param dataToVerify The data to check + * @param revocations The revocation signatures to check + * @param signature The certificate or signature to check + * @param key, optional The key packet to check the signature + * @param date Use the given date instead of the current time + * @returns True if the signature revokes the data + */ + function isDataRevoked(primaryKey: packet.SecretKey | packet.PublicKey, dataToVerify: object, revocations: any[], signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Check if signature has revocation key sub packet (not supported by OpenPGP.js) + * and throw error if found + * @param signature The certificate or signature to check + * @param keyId Check only certificates or signatures from a certain issuer key ID + */ + function checkRevocationKey(signature: packet.Signature, keyId: type.keyid.Keyid): void; + + /** + * Returns the preferred signature hash algorithm of a key + * @param key (optional) the key to get preferences from + * @param keyPacket key packet used for signing + * @param date (optional) use the given date for verification instead of the current time + * @param userId (optional) user ID + * @returns + */ + function getPreferredHashAlgo(key: Key, keyPacket: packet.SecretKey | packet.SecretSubkey, date: Date, userId: object): Promise; + + /** + * Returns the preferred symmetric/aead algorithm for a set of keys + * @param {symmetric | aead} type Type of preference to return + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns Preferred symmetric algorithm + */ + function getPreferredAlgo(type: any, keys: any[], date: Date, userIds: any[]): Promise; + + /** + * Returns whether aead is supported by all keys in the set + * @param keys Set of keys + * @param date (optional) use the given date for verification instead of the current time + * @param userIds (optional) user IDs + * @returns + */ + function isAeadSupported(keys: any[], date: Date, userIds: any[]): Promise; + } + + interface revoke_reasonForRevocation { + /** + * optional, flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * optional, string explaining the reason for revocation + */ + string: string; + } + + /** + * Class that represents an user ID or attribute packet and the relevant signatures. + */ + class User { + constructor(); + + /** + * Transforms structured user data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Signs user + * @param primaryKey The primary key packet + * @param privateKeys Decrypted private keys for signing + * @returns New user with new certificate signatures + */ + sign(primaryKey: packet.SecretKey | packet.PublicKey, privateKeys: any[]): Promise; + + /** + * Checks if a given certificate of the user is revoked + * @param primaryKey The primary key packet + * @param certificate The certificate to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the certificate is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verifies the user certificate + * @param primaryKey The primary key packet + * @param certificate A certificate of this user + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns status of the certificate + */ + verifyCertificate(primaryKey: packet.SecretKey | packet.PublicKey, certificate: packet.Signature, keys: any[], date: Date): Promise; + + /** + * Verifies all user certificates + * @param primaryKey The primary key packet + * @param keys Array of keys to verify certificate signatures + * @param date Use the given date instead of the current time + * @returns List of signer's keyid and validity of signature + */ + verifyAllCertifications(primaryKey: packet.SecretKey | packet.PublicKey, keys: any[], date: Date): Promise>; + + /** + * Verify User. Checks for existence of self signatures, revocation signatures + * and validity of self signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns Status of user + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update user with new components from specified user + * @param user Source user to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(user: key.User, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + } + + /** + * Class that represents a subkey packet and the relevant signatures. + */ + class SubKey { + constructor(); + + /** + * Transforms structured subkey data to packetlist + * @returns + */ + toPacketlist(): packet.List; + + /** + * Checks if a binding signature of a subkey is revoked + * @param primaryKey The primary key packet + * @param signature The binding signature to verify + * @param key, optional The key to verify the signature + * @param date Use the given date instead of the current time + * @returns True if the binding signature is revoked + */ + isRevoked(primaryKey: packet.SecretKey | packet.PublicKey, signature: packet.Signature, key: packet.PublicSubkey | packet.SecretSubkey | packet.PublicKey | packet.SecretKey, date: Date): Promise; + + /** + * Verify subkey. Checks for revocation signatures, expiration time + * and valid binding signature + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns The status of the subkey + */ + verify(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Returns the expiration time of the subkey or Infinity if key does not expire + * Returns null if the subkey is invalid. + * @param primaryKey The primary key packet + * @param date Use the given date instead of the current time + * @returns + */ + getExpirationTime(primaryKey: packet.SecretKey | packet.PublicKey, date: Date): Promise; + + /** + * Update subkey with new components from specified subkey + * @param subKey Source subkey to merge + * @param primaryKey primary key used for validation + * @returns + */ + update(subKey: key.SubKey, primaryKey: packet.SecretKey | packet.SecretSubkey): Promise; + + /** + * Revokes the subkey + * @param primaryKey decrypted private primary key for revocation + * @param reasonForRevocation optional, object indicating the reason for revocation + * @param reasonForRevocation.flag optional, flag indicating the reason for revocation + * @param reasonForRevocation.string optional, string explaining the reason for revocation + * @param date optional, override the creationtime of the revocation signature + * @returns new subkey with revocation signature + */ + revoke(primaryKey: packet.SecretKey, reasonForRevocation: revoke_reasonForRevocation, date: Date): Promise; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + } + + /** + * @see module:keyring/keyring + * @see module:keyring/localstore + */ + namespace keyring { + namespace keyring { + class Keyring { + /** + * Initialization routine for the keyring. + * @param storeHandler class implementing loadPublic(), loadPrivate(), storePublic(), and storePrivate() methods + */ + constructor(storeHandler?: localstore.LocalStore); + + /** + * Calls the storeHandler to load the keys + */ + load(): void; + + /** + * Calls the storeHandler to save the keys + */ + store(): void; + + /** + * Clear the keyring - erase all the keys + */ + clear(): void; + + /** + * Searches the keyring for keys having the specified key id + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @param deep if true search also in subkeys + * @returns keys found or null + */ + getKeysForId(keyId: string, deep: boolean): any[] | null; + + /** + * Removes keys having the specified key id from the keyring + * @param keyId provided as string of lowercase hex number + * withouth 0x prefix (can be 16-character key ID or fingerprint) + * @returns keys found or null + */ + removeKeysForId(keyId: string): any[] | null; + + /** + * Get all public and private keys + * @returns all keys + */ + getAllKeys(): any[]; + } + + /** + * Array of keys + * @param keys The keys to store in this array + */ + function KeyArray(keys: any[]): void; + } + + namespace localstore { + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; + } + } + } + + class LocalStore { + /** + * The class that deals with storage of the keyring. + * Currently the only option is to use HTML5 local storage. + * @param prefix prefix for itemnames in localstore + */ + constructor(prefix: string); + + /** + * Load the public keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPublic(): any[]; + + /** + * Load the private keys from HTML5 local storage. + * @returns array of keys retrieved from localstore + */ + loadPrivate(): any[]; + + /** + * Saves the current state of the public keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePublic(keys: any[]): void; + + /** + * Saves the current state of the private keys to HTML5 local storage. + * The key array gets stringified using JSON + * @param keys array of keys to save in localstore + */ + storePrivate(keys: any[]): void; + } + + namespace message { + /** + * Class that represents an OpenPGP message. + * Can be an encrypted message, signed message, compressed message or literal message + */ + class Message { + packets: packet.List; + + /** + * @param packetlist The packets that form this message + * See {@link https://tools.ietf.org/html/rfc4880#section-11.3} + */ + constructor(packetlist: packet.List); + + /** + * Returns the key IDs of the keys to which the session key is encrypted + * @returns array of keyid objects + */ + getEncryptionKeyIds(): any[]; + + /** + * Returns the key IDs of the keys that signed the message + * @returns array of keyid objects + */ + getSigningKeyIds(): any[]; + + /** + * Decrypt the message. Either a private key, a session key, or a password must be specified. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @param sessionKeys (optional) session keys in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param streaming (optional) whether to process data as a stream + * @returns new message with decrypted content + */ + decrypt(privateKeys?: any[], passwords?: any[], sessionKeys?: any[], streaming?: boolean): Promise; + + /** + * Decrypt encrypted session keys either with private keys or passwords. + * @param privateKeys (optional) private keys with decrypted secret data + * @param passwords (optional) passwords used to decrypt + * @returns array of object with potential sessionKey, algorithm pairs + */ + decryptSessionKeys(privateKeys?: any[], passwords?: any[]): Promise>; + + /** + * Get literal data that is the body of the message + * @returns literal body of the message as Uint8Array + */ + getLiteralData(): Uint8Array | null; + + /** + * Get filename from literal data packet + * @returns filename of literal data packet as string + */ + getFilename(): string | null; + + /** + * Get literal data as text + * @returns literal body of the message interpreted as text + */ + getText(): string | null; + + /** + * Encrypt the message either with public keys, passwords, or both at once. + * @param keys (optional) public key(s) for message encryption + * @param passwords (optional) password(s) for message encryption + * @param sessionKey (optional) session key in the form: { data:Uint8Array, algorithm:String, [aeadAlgorithm:String] } + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the creation date of the literal package + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @param streaming (optional) whether to process data as a stream + * @returns new message with encrypted content + */ + encrypt(keys?: any[], passwords?: any[], sessionKey?: object, wildcard?: boolean, date?: Date, userIds?: any[], streaming?: boolean): Promise; + + /** + * Sign the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to add to the message + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new message with signed content + */ + sign(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Compresses the message (the literal and -if signed- signature data packets of the message) + * @param compression compression algorithm to be used + * @returns new message with compressed content + */ + compress(compression: enums.compression): Message; + + /** + * Create a detached signature for the message (the literal data packet of the message) + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature + * @param date (optional) override the creation time of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns new detached signature of message content + */ + signDetached(privateKeys: any[], signature?: signature.Signature, date?: Date, userIds?: any[]): Promise; + + /** + * Verify message signatures + * @param keys array of keys to verify signatures + * @param date (optional) Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @param streaming (optional) whether to process data as a stream + * @returns list of signer's keyid and validity of signature + */ + verify(keys: any[], date?: Date, streaming?: boolean): Promise>; + + /** + * Verify detached message signature + * @param keys array of keys to verify signatures + * @param signature + * @param date Verify the signature against the given date, i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + verifyDetached(keys: any[], signature: signature.Signature, date?: Date): Promise>; + + /** + * Unwrap compressed message + * @returns message Content of compressed message + */ + unwrapCompressed(): Message; + + /** + * Append signature to unencrypted message object + * @param detachedSignature The detached ASCII-armored or Uint8Array PGP signature + */ + appendSignature(detachedSignature: string | Uint8Array): void; + + /** + * Returns ASCII armored text of message + * @returns ASCII armor + */ + armor(): ReadableStream; + } + + /** + * Encrypt a session key either with public keys, passwords, or both at once. + * @param sessionKey session key for encryption + * @param symAlgo session key algorithm + * @param aeadAlgo (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) public key(s) for message encryption + * @param passwords (optional) for message encryption + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param userIds (optional) user IDs to encrypt for, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + * @returns new message with encrypted content + */ + function encryptSessionKey(sessionKey: Uint8Array, symAlgo: string, aeadAlgo: string, publicKeys: any[], passwords: any[], wildcard: boolean, date: Date, userIds: any[]): Promise; + + /** + * Create signature packets for the message + * @param literalDataPacket the literal data packet to sign + * @param privateKeys private keys with decrypted secret key data for signing + * @param signature (optional) any existing detached signature to append + * @param date (optional) override the creationtime of the signature + * @param userIds (optional) user IDs to sign with, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + * @returns list of signature packets + */ + function createSignaturePackets(literalDataPacket: packet.Literal, privateKeys: any[], signature: signature.Signature, date: Date, userIds: any[]): Promise; + + /** + * Create object containing signer's keyid and validity of signature + * @param signature signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObject(signature: packet.Signature, literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * Create list of objects containing signer's keyid and validity of signature + * @param signatureList array of signature packets + * @param literalDataList array of literal data packets + * @param keys array of keys to verify signatures + * @param date Verify the signature against the given date, + * i.e. check signature creation time < date < expiration time + * @returns list of signer's keyid and validity of signature + */ + function createVerificationObjects(signatureList: any[], literalDataList: any[], keys: any[], date: Date): Promise>; + + /** + * reads an OpenPGP armored message and returns a message object + * @param armoredText text to be parsed + * @returns new message object + */ + function readArmored(armoredText: string | ReadableStream): Promise; + + /** + * reads an OpenPGP message as byte array and returns a message object + * @param input binary message + * @param fromStream whether the message was created from a Stream + * @returns new message object + */ + function read(input: Uint8Array | ReadableStream, fromStream?: boolean): Promise; + + /** + * creates new message object from text + * @param text + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromText(text: string | ReadableStream, filename?: string, date?: Date, type?: any): Message; + + /** + * creates new message object from binary data + * @param bytes + * @param filename (optional) + * @param date (optional) + * @param {utf8 | binary | text | mime} type (optional) data packet type + * @returns new message object + */ + function fromBinary(bytes: Uint8Array | ReadableStream, filename?: string, date?: Date, type?: any): Message; + } + + interface revokeKey_reasonForRevocation { + /** + * (optional) flag indicating the reason for revocation + */ + flag: enums.reasonForRevocation; + /** + * (optional) string explaining the reason for revocation + */ + string: string; + } + + /** + * @see module:packet/all_packets + * @see module:packet/clone + * @see module:packet.List + */ + namespace packet { + /** + * Allocate a new packet + * @param tag property name from {@link module:enums.packet} + * @returns new packet object with type based on tag + */ + function newPacketFromTag(tag: string): object; + + /** + * Allocate a new packet from structured packet clone + * @see + * @param packetClone packet clone + * @returns new packet object with data from packet clone + */ + function fromStructuredClone(packetClone: object): object; + + class Compressed { + /** + * Implementation of the Compressed Data Packet (Tag 8) + * {@link https://tools.ietf.org/html/rfc4880#section-5.6|RFC4880 5.6}: + * The Compressed Data packet contains compressed data. Typically, + * this packet is found as the contents of an encrypted packet, or following + * a Signature or One-Pass Signature packet, and contains a literal data packet. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * List of packets + */ + packets: List; + + /** + * Compression algorithm + * @type {compression} + */ + algorithm: any; + + /** + * Compressed packet data + */ + compressed: Uint8Array | ReadableStream; + + /** + * Parsing function for the packet. + * @param bytes Payload of a tag 8 packet + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Return the compressed packet. + * @returns binary compressed packet + */ + write(): Uint8Array | ReadableStream; + + /** + * Decompression method for decompressing the compressed data + * read by read_packet + */ + decompress(): void; + + /** + * Compress the packet data (member decompressedData) + */ + compress(): void; + } + + class Literal { + /** + * Implementation of the Literal Data Packet (Tag 11) + * {@link https://tools.ietf.org/html/rfc4880#section-5.9|RFC4880 5.9}: + * A Literal Data packet contains the body of a message; data that is not to be + * further interpreted. + * @param date the creation date of the literal package + */ + constructor(date: Date); + + /** + * Set the packet data to a javascript native string, end of line + * will be normalized to \r\n and by default text is converted to UTF8 + * @param text Any native javascript string + * @param {utf8 | binary | text | mime} format (optional) The format of the string of bytes + */ + setText(text: string | ReadableStream, format: any): void; + + /** + * Returns literal data packets as native JavaScript string + * with normalized end of line to \n + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns literal data as text + */ + getText(clone: boolean): string | ReadableStream; + + /** + * Set the packet data to value represented by the provided string of bytes. + * @param bytes The string of bytes + * @param {utf8 | binary | text | mime} format The format of the string of bytes + */ + setBytes(bytes: Uint8Array | ReadableStream, format: any): void; + + /** + * Get the byte sequence representing the literal packet data + * @param clone (optional) Whether to return a clone so that getBytes/getText can be called again + * @returns A sequence of bytes + */ + getBytes(clone: boolean): Uint8Array | ReadableStream; + + /** + * Sets the filename of the literal packet data + * @param filename Any native javascript string + */ + setFilename(filename: string): void; + + /** + * Get the filename of the literal packet data + * @returns filename + */ + getFilename(): string; + + /** + * Parsing function for a literal data packet (tag 11). + * @param input Payload of a tag 11 packet + * @returns object representation + */ + read(input: Uint8Array | ReadableStream): Literal; + + /** + * Creates a string representation of the packet + * @returns Uint8Array representation of the packet + */ + write(): Uint8Array | ReadableStream; + } + + class Marker { + /** + * Implementation of the strange "Marker packet" (Tag 10) + * {@link https://tools.ietf.org/html/rfc4880#section-5.8|RFC4880 5.8}: + * An experimental version of PGP used this packet as the Literal + * packet, but no released version of PGP generated Literal packets with this + * tag. With PGP 5.x, this packet has been reassigned and is reserved for use as + * the Marker packet. + * Such a packet MUST be ignored when received. + */ + constructor(); + + /** + * Parsing function for a literal data packet (tag 10). + * @param input Payload of a tag 10 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: string, position: Integer, len: Integer): Marker; + } + + class OnePassSignature { + /** + * Implementation of the One-Pass Signature Packets (Tag 4) + * {@link https://tools.ietf.org/html/rfc4880#section-5.4|RFC4880 5.4}: + * The One-Pass Signature packet precedes the signed data and contains + * enough information to allow the receiver to begin calculating any + * hashes needed to verify the signature. It allows the Signature + * packet to be placed at the end of the message, so that the signer + * can compute the entire signed message in one pass. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * A one-octet version number. The current version is 3. + */ + version: any; + + /** + * A one-octet signature type. + * Signature types are described in + * {@link https://tools.ietf.org/html/rfc4880#section-5.2.1|RFC4880 Section 5.2.1}. + */ + signatureType: any; + + /** + * A one-octet number describing the hash algorithm used. + * @see + */ + hashAlgorithm: any; + + /** + * A one-octet number describing the public-key algorithm used. + * @see + */ + publicKeyAlgorithm: any; + + /** + * An eight-octet number holding the Key ID of the signing key. + */ + issuerKeyId: any; + + /** + * A one-octet number holding a flag showing whether the signature is nested. + * A zero value indicates that the next packet is another One-Pass Signature packet + * that describes another signature to be applied to the same message data. + */ + flags: any; + + /** + * parsing function for a one-pass signature packet (tag 4). + * @param bytes payload of a tag 4 packet + * @returns object representation + */ + read(bytes: Uint8Array): OnePassSignature; + + /** + * creates a string representation of a one-pass signature packet + * @returns a Uint8Array representation of a one-pass signature packet + */ + write(): Uint8Array; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class List { + /** + * This class represents a list of openpgp packets. + * Take care when iterating over it - the packets themselves + * are stored as numerical indices. + */ + constructor(); + + /** + * The number of packets contained within the list. + */ + readonly length: Integer; + + /** + * Reads a stream of binary data and interprents it as a list of packets. + * @param A Uint8Array of bytes. + */ + read(A: Uint8Array | ReadableStream): void; + + /** + * Creates a binary representation of openpgp objects contained within the + * class instance. + * @returns A Uint8Array containing valid openpgp packets. + */ + write(): Uint8Array; + + /** + * Adds a packet to the list. This is the only supported method of doing so; + * writing to packetlist[i] directly will result in an error. + * @param packet Packet to push + */ + push(packet: object): void; + + /** + * Creates a new PacketList with all packets from the given types + */ + filterByTag(): void; + + /** + * Traverses packet tree and returns first matching packet + * @param type The packet type + * @returns + */ + findPacket(type: enums.packet): List | undefined; + + /** + * Returns array of found indices by tag + */ + indexOfTag(): void; + + /** + * Concatenates packetlist or array of packets + */ + concat(): void; + + /** + * Allocate a new packetlist from structured packetlist clone + * See {@link https://w3c.github.io/html/infrastructure.html#safe-passing-of-structured-data} + * @param packetClone packetlist clone + * @returns new packetlist object with data from packetlist clone + */ + static fromStructuredClone(packetClone: object): object; + } + + class PublicKey { + /** + * Implementation of the Key Material Packet (Tag 5,6,7,14) + * {@link https://tools.ietf.org/html/rfc4880#section-5.5|RFC4480 5.5}: + * A key material packet contains all the information about a public or + * private key. There are four variants of this packet type, and two + * major versions. + * A Public-Key packet starts a series of packets that forms an OpenPGP + * key (sometimes called an OpenPGP certificate). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicKeyEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + encrypted: any[]; + + /** + * Parsing function for a publickey encrypted session key packet (tag 1). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): PublicKeyEncryptedSessionKey + + /** + * Create a string representation of a tag 1 packet + * @returns The Uint8Array representation + */ + write(): Uint8Array; + + /** + * Encrypt session key packet + * @param key Public key + * @returns + */ + encrypt(key: PublicKey): Promise; + + /** + * Decrypts the session key (only for public key encrypted session key + * packets (tag 1) + * @param key Private key with secret params unlocked + * @returns + */ + decrypt(key: SecretKey): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class PublicSubkey { + /** + * A Public-Subkey packet (tag 14) has exactly the same format as a + * Public-Key packet, but denotes a subkey. One or more subkeys may be + * associated with a top-level key. By convention, the top-level key + * provides signature services, and the subkeys provide encryption + * services. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Internal Parser for public keys as specified in {@link https://tools.ietf.org/html/rfc4880#section-5.5.2|RFC 4880 section 5.5.2 Public-Key Packet Formats} + * called by read_tag<num> + * @param bytes Input array to read the packet from + * @returns This object with attributes set by the parser + */ + read(bytes: Uint8Array): object; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Same as write_private_key, but has less information because of + * public key. + * @returns OpenPGP packet body contents, + */ + write(): Uint8Array; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SecretKey { + /** + * A Secret-Key packet contains all the information that is found in a + * Public-Key packet, including the public-key material, but also + * includes the secret-key material after all the public-key fields. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class SecretSubkey { + /** + * A Secret-Subkey packet (tag 7) is the subkey analog of the Secret + * Key packet and has exactly the same format. + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Indicator if secret-key data is encrypted. `this.isEncrypted === false` means data is available in decrypted form. + */ + isEncrypted: any; + + /** + * Internal parser for private keys as specified in + * {@link https://tools.ietf.org/html/draft-ietf-openpgp-rfc4880bis-04#section-5.5.3|RFC4880bis-04 section 5.5.3} + * @param bytes Input string to read the packet from + */ + read(bytes: string): void; + + /** + * Creates an OpenPGP key packet for the given key. + * @returns A string of bytes containing the secret key OpenPGP packet + */ + write(): string; + + /** + * Check whether secret-key data is available in decrypted form. Returns null for public keys. + * @returns + */ + isDecrypted(): boolean | null; + + /** + * Encrypt the payload. By default, we use aes256 and iterated, salted string + * to key specifier. If the key is in a decrypted state (isEncrypted === false) + * and the passphrase is empty or undefined, the key will be set as not encrypted. + * This can be used to remove passphrase protection after calling decrypt(). + * @param passphrase + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Decrypts the private key params which are needed to use the key. + * {@link module:packet.SecretKey.isDecrypted} should be false, as + * otherwise calls to this function will throw an error. + * @param passphrase The passphrase for this private key as string + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Clear private params, return to initial state + */ + clearPrivateParams(): void; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + + /** + * Packet version + */ + version: Integer; + + /** + * Key creation date. + */ + created: Date; + + /** + * Public key algorithm. + */ + algorithm: string; + + /** + * Algorithm specific params + */ + params: object[]; + + /** + * Time until expiration in days (V3 only) + */ + expirationTimeV3: Integer; + + /** + * Fingerprint in lowercase hex + */ + fingerprint: string; + + /** + * Keyid + */ + keyid: type.keyid.Keyid; + + /** + * Alias of read() + * @see module:packet.PublicKey#read + */ + readPublicKey: any; + + /** + * Alias of write() + * @see module:packet.PublicKey#write + */ + writePublicKey: any; + + /** + * Write an old version packet - it's used by some of the internal routines. + */ + writeOld(): void; + + /** + * Returns the creation time of the key + * @returns + */ + getCreationTime(): Date; + + /** + * Calculates the key id of the key + * @returns A 8 byte key id + */ + getKeyId(): string; + + /** + * Calculates the fingerprint of the key + * @returns A Uint8Array containing the fingerprint + */ + getFingerprintBytes(): Uint8Array; + + /** + * Calculates the fingerprint of the key + * @returns A string containing the fingerprint in lowercase hex + */ + getFingerprint(): string; + + /** + * Calculates whether two keys have the same fingerprint without actually calculating the fingerprint + * @returns Whether the two keys have the same version and public key data + */ + hasSameFingerprintAs(): boolean; + + /** + * Returns algorithm information + * @returns An object of the form {algorithm: string, bits:int, curve:String} + */ + getAlgorithmInfo(): object; + } + + class Signature { + /** + * Implementation of the Signature Packet (Tag 2) + * {@link https://tools.ietf.org/html/rfc4880#section-5.2|RFC4480 5.2}: + * A Signature packet describes a binding between some public key and + * some data. The most common signatures are a signature of a file or a + * block of text, and a signature that is a certification of a User ID. + * @param date the creation date of the signature + */ + constructor(date: Date); + + /** + * parsing function for a signature packet (tag 2). + * @param bytes payload of a tag 2 packet + * @param position position to start reading from the bytes string + * @param len length of the packet or the remaining length of bytes at position + * @returns object representation + */ + read(bytes: string, position: Integer, len: Integer): Signature; + + /** + * Signs provided data. This needs to be done prior to serialization. + * @param key private key used to sign the message. + * @param data Contains packets to be signed. + * @returns + */ + sign(key: SecretKey, data: object): Promise; + + /** + * Creates Uint8Array of bytes of all subpacket data except Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_hashed_sub_packets(): Uint8Array; + + /** + * Creates Uint8Array of bytes of Issuer and Embedded Signature subpackets + * @returns subpacket data + */ + write_unhashed_sub_packets(): Uint8Array; + + /** + * verifys the signature packet. Note: not signature types are implemented + * @param key the public key to verify the signature + * @param signatureType expected signature type + * @param data data which on the signature applies + * @returns True if message is verified, else false. + */ + verify(key: PublicSubkey | PublicKey | SecretSubkey | SecretKey, signatureType: enums.signature, data: string | object): Promise; + + /** + * Verifies signature expiration date + * @param date (optional) use the given date for verification instead of the current time + * @returns true if expired + */ + isExpired(date: Date): boolean; + + /** + * Returns the expiration time of the signature or Infinity if signature does not expire + * @returns expiration time + */ + getExpirationTime(): Date; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymEncryptedAEADProtected { + /** + * Implementation of the Symmetrically Encrypted Authenticated Encryption with + * Additional Data (AEAD) Protected Data Packet + * {@link https://tools.ietf.org/html/draft-ford-openpgp-format-00#section-2.1}: + * AEAD Protected Data Packet + */ + constructor(); + + /** + * Parse an encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @param bytes + */ + read(bytes: Uint8Array | ReadableStream): void; + + /** + * Write the encrypted payload of bytes in the order: version, IV, ciphertext (see specification) + * @returns The encrypted payload + */ + write(): Uint8Array | ReadableStream; + + /** + * Decrypt the encrypted payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): boolean; + + /** + * Encrypt the packet list payload. + * @param sessionKeyAlgorithm The session key's cipher algorithm e.g. 'aes128' + * @param key The session key used to encrypt the payload + * @param streaming Whether the top-level function will return a stream + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): void; + + /** + * En/decrypt the payload. + * @param {encrypt | decrypt} fn Whether to encrypt or decrypt + * @param key The session key used to en/decrypt the payload + * @param data The data to en/decrypt + * @param streaming Whether the top-level function will return a stream + * @returns + */ + crypt(fn: any, key: Uint8Array, data: Uint8Array | ReadableStream, streaming: boolean): Uint8Array | ReadableStream; + } + + class SymEncryptedIntegrityProtected { + /** + * Implementation of the Sym. Encrypted Integrity Protected Data Packet (Tag 18) + * {@link https://tools.ietf.org/html/rfc4880#section-5.13|RFC4880 5.13}: + * The Symmetrically Encrypted Integrity Protected Data packet is + * a variant of the Symmetrically Encrypted Data packet. It is a new feature + * created for OpenPGP that addresses the problem of detecting a modification to + * encrypted data. It is used in combination with a Modification Detection Code + * packet. + */ + constructor(); + + /** + * The encrypted payload. + */ + encrypted: any; + + /** + * If after decrypting the packet this is set to true, + * a modification has been detected and thus the contents + * should be discarded. + */ + modification: boolean; + + /** + * Encrypt the payload in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to set this.encrypted to a stream + * @returns + */ + encrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + + /** + * Decrypts the encrypted data contained in the packet. + * @param sessionKeyAlgorithm The selected symmetric encryption algorithm to be used e.g. 'aes128' + * @param key The key of cipher blocksize length to be used + * @param streaming Whether to read this.encrypted as a stream + * @returns + */ + decrypt(sessionKeyAlgorithm: string, key: Uint8Array, streaming: boolean): Promise; + } + + class SymEncryptedSessionKey { + /** + * Public-Key Encrypted Session Key Packets (Tag 1) + * {@link https://tools.ietf.org/html/rfc4880#section-5.1|RFC4880 5.1}: + * A Public-Key Encrypted Session Key packet holds the session key + * used to encrypt a message. Zero or more Public-Key Encrypted Session Key + * packets and/or Symmetric-Key Encrypted Session Key packets may precede a + * Symmetrically Encrypted Data Packet, which holds an encrypted message. The + * message is encrypted with the session key, and the session key is itself + * encrypted and stored in the Encrypted Session Key packet(s). The + * Symmetrically Encrypted Data Packet is preceded by one Public-Key Encrypted + * Session Key packet for each OpenPGP key to which the message is encrypted. + * The recipient of the message finds a session key that is encrypted to their + * public key, decrypts the session key, and then uses the session key to + * decrypt the message. + */ + constructor(); + + /** + * Parsing function for a symmetric encrypted session key packet (tag 3). + * @param input Payload of a tag 1 packet + * @param position Position to start reading from the input string + * @param len Length of the packet or the remaining length of + * input at position + * @returns Object representation + */ + read(input: Uint8Array, position: Integer, len: Integer): SymEncryptedSessionKey; + + /** + * Decrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + decrypt(passphrase: string): Promise; + + /** + * Encrypts the session key + * @param passphrase The passphrase in string form + * @returns + */ + encrypt(passphrase: string): Promise; + + /** + * Fix custom types after cloning + */ + postCloneTypeFix(): void; + } + + class SymmetricallyEncrypted { + /** + * Implementation of the Symmetrically Encrypted Data Packet (Tag 9) + * {@link https://tools.ietf.org/html/rfc4880#section-5.7|RFC4880 5.7}: + * The Symmetrically Encrypted Data packet contains data encrypted with a + * symmetric-key algorithm. When it has been decrypted, it contains other + * packets (usually a literal data packet or compressed data packet, but in + * theory other Symmetrically Encrypted Data packets or sequences of packets + * that form whole OpenPGP messages). + */ + constructor(); + + /** + * Packet type + */ + tag: enums.packet; + + /** + * Encrypted secret-key data + */ + encrypted: any; + + /** + * Decrypted packets contained within. + */ + packets: List; + + /** + * When true, decrypt fails if message is not integrity protected + * @see module:config.ignore_mdc_error + */ + ignore_mdc_error: any; + + /** + * Decrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + decrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + + /** + * Encrypt the symmetrically-encrypted packet data + * See {@link https://tools.ietf.org/html/rfc4880#section-9.2|RFC 4880 9.2} for algorithms. + * @param sessionKeyAlgorithm Symmetric key algorithm to use + * @param key The key of cipher blocksize length to be used + * @returns + */ + encrypt(sessionKeyAlgorithm: enums.symmetric, key: Uint8Array): Promise; + } + + class Trust { + /** + * Implementation of the Trust Packet (Tag 12) + * {@link https://tools.ietf.org/html/rfc4880#section-5.10|RFC4880 5.10}: + * The Trust packet is used only within keyrings and is not normally + * exported. Trust packets contain data that record the user's + * specifications of which key holders are trustworthy introducers, + * along with other information that implementing software uses for + * trust information. The format of Trust packets is defined by a given + * implementation. + * Trust packets SHOULD NOT be emitted to output streams that are + * transferred to other users, and they SHOULD be ignored on any input + * other than local keyring files. + */ + constructor(); + + /** + * Parsing function for a trust packet (tag 12). + * Currently not implemented as we ignore trust packets + * @param byptes payload of a tag 12 packet + */ + read(byptes: string): void; + } + + class UserAttribute { + /** + * Implementation of the User Attribute Packet (Tag 17) + * The User Attribute packet is a variation of the User ID packet. It + * is capable of storing more types of data than the User ID packet, + * which is limited to text. Like the User ID packet, a User Attribute + * packet may be certified by the key owner ("self-signed") or any other + * key owner who cares to certify it. Except as noted, a User Attribute + * packet may be used anywhere that a User ID packet may be used. + * While User Attribute packets are not a required part of the OpenPGP + * standard, implementations SHOULD provide at least enough + * compatibility to properly handle a certification signature on the + * User Attribute packet. A simple way to do this is by treating the + * User Attribute packet as a User ID packet with opaque contents, but + * an implementation may use any method desired. + */ + constructor(); + + /** + * parsing function for a user attribute packet (tag 17). + * @param input payload of a tag 17 packet + */ + read(input: Uint8Array): void; + + /** + * Creates a binary representation of the user attribute packet + * @returns string representation + */ + write(): Uint8Array; + + /** + * Compare for equality + * @param usrAttr + * @returns true if equal + */ + equals(usrAttr: UserAttribute): boolean; + } + + class Userid { + /** + * Implementation of the User ID Packet (Tag 13) + * A User ID packet consists of UTF-8 text that is intended to represent + * the name and email address of the key holder. By convention, it + * includes an RFC 2822 [RFC2822] mail name-addr, but there are no + * restrictions on its content. The packet length in the header + * specifies the length of the User ID. + */ + constructor(); + + /** + * A string containing the user id. Usually in the form + * John Doe + */ + userid: string; + + /** + * Parsing function for a user id packet (tag 13). + * @param input payload of a tag 13 packet + */ + read(input: Uint8Array): void; + + /** + * Parse userid string, e.g. 'John Doe ' + */ + parse(): void; + + /** + * Creates a binary representation of the user id packet + * @returns binary representation + */ + write(): Uint8Array; + + /** + * Set userid string from object, e.g. { name:'Phil Zimmermann', email:'phil@openpgp.org' } + */ + format(): void; + } + + namespace all_packets { + /** + * @see module:packet.Compressed + */ + var Compressed: any; + + /** + * @see module:packet.SymEncryptedIntegrityProtected + */ + var SymEncryptedIntegrityProtected: any; + + /** + * @see module:packet.SymEncryptedAEADProtected + */ + var SymEncryptedAEADProtected: any; + + /** + * @see module:packet.PublicKeyEncryptedSessionKey + */ + var PublicKeyEncryptedSessionKey: any; + + /** + * @see module:packet.SymEncryptedSessionKey + */ + var SymEncryptedSessionKey: any; + + /** + * @see module:packet.Literal + */ + var Literal: any; + + /** + * @see module:packet.PublicKey + */ + var PublicKey: any; + + /** + * @see module:packet.SymmetricallyEncrypted + */ + var SymmetricallyEncrypted: any; + + /** + * @see module:packet.Marker + */ + var Marker: any; + + /** + * @see module:packet.PublicSubkey + */ + var PublicSubkey: any; + + /** + * @see module:packet.UserAttribute + */ + var UserAttribute: any; + + /** + * @see module:packet.OnePassSignature + */ + var OnePassSignature: any; + + /** + * @see module:packet.SecretKey + */ + var SecretKey: any; + + /** + * @see module:packet.Userid + */ + var Userid: any; + + /** + * @see module:packet.SecretSubkey + */ + var SecretSubkey: any; + + /** + * @see module:packet.Signature + */ + var Signature: any; + + /** + * @see module:packet.Trust + */ + var Trust: any; + } + + namespace clone { + /** + * Create a packetlist from the correspoding object types. + * @param options the object passed to and from the web worker + * @returns a mutated version of the options optject + */ + function clonePackets(options: object): object; + + /** + * Creates an object with the correct prototype from a corresponding packetlist. + * @param options the object passed to and from the web worker + * @param method the public api function name to be delegated to the worker + * @returns a mutated version of the options optject + */ + function parseClonedPackets(options: object, method: string): object; + } + + namespace packet { + /** + * Encodes a given integer of length to the openpgp length specifier to a + * string + * @param length The length to encode + * @returns String with openpgp length representation + */ + function writeSimpleLength(length: Integer): Uint8Array; + + /** + * Writes a packet header version 4 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeHeader(tag_type: Integer, length: Integer): string; + + /** + * Writes a packet header Version 3 with the given tag_type and length to a + * string + * @param tag_type Tag type + * @param length Length of the payload + * @returns String of the header + */ + function writeOldHeader(tag_type: Integer, length: Integer): string; + + /** + * Whether the packet type supports partial lengths per RFC4880 + * @param tag_type Tag type + * @returns String of the header + */ + function supportsStreaming(tag_type: Integer): boolean; + + /** + * Generic static Packet Parser function + * @param input Input stream as string + * @param callback Function to call with the parsed packet + * @returns Returns false if the stream was empty and parsing is done, and true otherwise. + */ + function read(input: Uint8Array | ReadableStream, callback: Function): boolean; + } + } + + + namespace polyfills { } namespace signature { - /** Create a signature on data using the specified algorithm - @param hash_algo hash Algorithm to use - @param algo Asymmetric cipher algorithm to use - @param publicMPIs Public key multiprecision integers of the private key - @param secretMPIs Private key multiprecision integers which is used to sign the data - @param data Data to be signed - */ - function sign(hash_algo: enums.hash, algo: enums.publicKey, publicMPIs: Array, secretMPIs: Array, data: string): Mpi; + /** + * Class that represents an OpenPGP signature. + */ + class Signature { + /** + * @param packetlist The signature packets + */ + constructor(packetlist: packet.List); + + /** + * Returns ASCII armored text of signature + * @returns ASCII armor + */ + armor(): ReadableStream; + } /** - @param algo public Key algorithm - @param hash_algo Hash algorithm - @param msg_MPIs Signature multiprecision integers - @param publickey_MPIs Public key multiprecision integers - @param data Data on where the signature was computed on + * reads an OpenPGP armored signature and returns a signature object + * @param armoredText text to be parsed + * @returns new signature object + */ + function readArmored(armoredText: string | ReadableStream): Signature; + + /** + * reads an OpenPGP signature as byte array and returns a signature object + * @param input binary signature + * @returns new signature object + */ + function read(input: Uint8Array | ReadableStream): Signature; + } + + namespace type { + /** + * Encoded symmetric key for ECDH + */ + namespace ecdh_symkey { + class ECDHSymmetricKey { + constructor(); + + /** + * Read an ECDHSymmetricKey from an Uint8Array + * @param input Where to read the encoded symmetric key from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Write an ECDHSymmetricKey as an Uint8Array + * @returns An array containing the value + */ + write(): Uint8Array; + } + } + + /** + * Implementation of type KDF parameters + * {@link https://tools.ietf.org/html/rfc6637#section-7|RFC 6637 7}: + * A key derivation function (KDF) is necessary to implement the EC + * encryption. The Concatenation Key Derivation Function (Approved + * Alternative 1) [NIST-SP800-56A] with the KDF hash function that is + * SHA2-256 [FIPS-180-3] or stronger is REQUIRED. + */ + namespace kdf_params { + class KDFParams { + /** + * @param hash Hash algorithm + * @param cipher Symmetric algorithm + */ + constructor(hash: enums.hash, cipher: enums.symmetric); + + /** + * Read KDFParams from an Uint8Array + * @param input Where to read the KDFParams from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Write KDFParams to an Uint8Array + * @returns Array with the KDFParams value + */ + write(): Uint8Array; + } + } + + /** + * Implementation of type key id + * {@link https://tools.ietf.org/html/rfc4880#section-3.3|RFC4880 3.3}: + * A Key ID is an eight-octet scalar that identifies a key. + * Implementations SHOULD NOT assume that Key IDs are unique. The + * section "Enhanced Key Formats" below describes how Key IDs are + * formed. + */ + namespace keyid { + class Keyid { + constructor(); + + /** + * Parsing method for a key id + * @param input Input to read the key id from + */ + read(input: Uint8Array): void; + + /** + * Checks equality of Key ID's + * @param keyid + * @param matchWildcard Indicates whether to check if either keyid is a wildcard + */ + equals(keyid: Keyid, matchWildcard: boolean): void; + } + } + + /** + * Implementation of type MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2}) + * Multiprecision integers (also called MPIs) are unsigned integers used + * to hold large integers such as the ones used in cryptographic + * calculations. + * An MPI consists of two pieces: a two-octet scalar that is the length + * of the MPI in bits followed by a string of octets that contain the + * actual integer. + */ + namespace mpi { + class MPI { + constructor(); + + /** + * Parsing function for a MPI ( {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC 4880 3.2}). + * @param input Payload of MPI data + * @param endian Endianness of the data; 'be' for big-endian or 'le' for little-endian + * @returns Length of data read + */ + read(input: Uint8Array, endian: string): Integer; + + /** + * Converts the mpi object to a bytes as specified in + * {@link https://tools.ietf.org/html/rfc4880#section-3.2|RFC4880 3.2} + * @param endian Endianness of the payload; 'be' for big-endian or 'le' for little-endian + * @param length Length of the data part of the MPI + * @returns mpi Byte representation + */ + write(endian: string, length: Integer): Uint8Array; + } + } + + /** + * Wrapper to an OID value + * {@link https://tools.ietf.org/html/rfc6637#section-11|RFC6637, section 11}: + * The sequence of octets in the third column is the result of applying + * the Distinguished Encoding Rules (DER) to the ASN.1 Object Identifier + * with subsequent truncation. The truncation removes the two fields of + * encoded Object Identifier. The first omitted field is one octet + * representing the Object Identifier tag, and the second omitted field + * is the length of the Object Identifier body. For example, the + * complete ASN.1 DER encoding for the NIST P-256 curve OID is "06 08 2A + * 86 48 CE 3D 03 01 07", from which the first entry in the table above + * is constructed by omitting the first two octets. Only the truncated + * sequence of octets is the valid representation of a curve OID. + */ + namespace oid { + class OID { + constructor(); + + /** + * Method to read an OID object + * @param input Where to read the OID from + * @returns Number of read bytes + */ + read(input: Uint8Array): number; + + /** + * Serialize an OID object + * @returns Array with the serialized value the OID + */ + write(): Uint8Array; + + /** + * Serialize an OID object as a hex string + * @returns String with the hex value of the OID + */ + toHex(): string; + + /** + * If a known curve object identifier, return the canonical name of the curve + * @returns String with the canonical name of the curve + */ + getName(): string; + } + } + + /** + * Implementation of the String-to-key specifier + * {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC4880 3.7}: + * String-to-key (S2K) specifiers are used to convert passphrase strings + * into symmetric-key encryption/decryption keys. They are used in two + * places, currently: to encrypt the secret part of private keys in the + * private keyring, and to convert passphrases to encryption keys for + * symmetrically encrypted messages. + */ + namespace s2k { + class S2K { + constructor(); + + algorithm: enums.hash; + + type: enums.s2k; + + c: Integer; + + /** + * Eight bytes of salt in a binary string. + */ + salt: string; + + /** + * Parsing function for a string-to-key specifier ( {@link https://tools.ietf.org/html/rfc4880#section-3.7|RFC 4880 3.7}). + * @param input Payload of string-to-key specifier + * @returns Actual length of the object + */ + read(input: string): Integer; + + /** + * Serializes s2k information + * @returns binary representation of s2k + */ + write(): Uint8Array; + + /** + * Produces a key using the specified passphrase and the defined + * hashAlgorithm + * @param passphrase Passphrase containing user input + * @returns Produced key with a length corresponding to + * hashAlgorithm hash length + */ + produce_key(passphrase: string): Uint8Array; + } + } + } + + /** + * This object contains utility functions + */ + namespace util { + /** + * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) + * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage + * Also, convert ReadableStreams to MessagePorts + * @param obj the options object to be passed to the web worker + * @returns an array of binary data to be passed + */ + function getTransferables(obj: object): any[]; + + /** + * Convert MessagePorts back to ReadableStreams + * @param obj + * @returns + */ + function restoreStreams(obj: object): object; + + /** + * Create hex string from a binary + * @param str String to convert + * @returns String containing the hexadecimal values + */ + function str_to_hex(str: string): string; + + /** + * Create binary string from a hex encoded string + * @param str Hex string to convert + * @returns + */ + function hex_to_str(str: string): string; + + /** + * Convert a Uint8Array to an MPI-formatted Uint8Array. + * Note: the output is **not** an MPI object. + * @see + * @see + * @param bin An array of 8-bit integers to convert + * @returns MPI-formatted Uint8Array + */ + function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; + + /** + * Convert a Base-64 encoded string an array of 8-bit integer + * Note: accepts both Radix-64 and URL-safe strings + * @param base64 Base-64 encoded string to convert + * @returns An array of 8-bit integers + */ + function b64_to_Uint8Array(base64: string): Uint8Array; + + /** + * Convert an array of 8-bit integer to a Base-64 encoded string + * @param bytes An array of 8-bit integers to convert + * @param url If true, output is URL-safe + * @returns Base-64 encoded string + */ + function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): string; + + /** + * Convert a hex string to an array of 8-bit integers + * @param hex A hex string to convert + * @returns An array of 8-bit integers + */ + function hex_to_Uint8Array(hex: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a hex string + * @param bytes Array of 8-bit integers to convert + * @returns Hexadecimal representation of the array + */ + function Uint8Array_to_hex(bytes: Uint8Array): string; + + /** + * Convert a string to an array of 8-bit integers + * @param str String to convert + * @returns An array of 8-bit integers + */ + function str_to_Uint8Array(str: string): Uint8Array; + + /** + * Convert an array of 8-bit integers to a string + * @param bytes An array of 8-bit integers to convert + * @returns String representation of the array + */ + function Uint8Array_to_str(bytes: Uint8Array): string; + + /** + * Convert a native javascript string to a Uint8Array of utf8 bytes + * @param str The string to convert + * @returns A valid squence of utf8 bytes + */ + function encode_utf8(str: string | ReadableStream): Uint8Array | ReadableStream; + + /** + * Convert a Uint8Array of utf8 bytes to a native javascript string + * @param utf8 A valid squence of utf8 bytes + * @returns A native javascript string + */ + function decode_utf8(utf8: Uint8Array | ReadableStream): string | ReadableStream; + + /** + * Concat a list of Uint8Arrays, Strings or Streams + * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. + * @param Array of Uint8Arrays/Strings/Streams to concatenate + * @returns Concatenated array + */ + var concat: any; + + /** + * Concat Uint8Arrays + * @param Array of Uint8Arrays to concatenate + * @returns Concatenated array + */ + var concatUint8Array: any; + + /** + * Check Uint8Array equality + * @param first array + * @param second array + * @returns equality + */ + function equalsUint8Array(first: Uint8Array, second: Uint8Array): boolean; + + /** + * Calculates a 16bit sum of a Uint8Array by adding each character + * codes modulus 65535 + * @param Uint8Array to create a sum of + * @returns 2 bytes containing the sum of all charcodes % 65535 + */ + function write_checksum(Uint8Array: Uint8Array): Uint8Array; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexarray_dump(str: string): void; + + /** + * Helper function to print a debug message. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_hexstr_dump(str: string): void; + + /** + * Helper function to print a debug error. Debug + * messages are only printed if + * @param str String of the debug message + */ + function print_debug_error(str: string): void; + + /** + * Read a stream to the end and print it to the console when it's closed. + * @param str String of the debug message + * @param input Stream to print + * @param concat Function to concatenate chunks of the stream (defaults to util.concat). + */ + function print_entire_stream(str: string, input: ReadableStream | Uint8Array | string, concat: Function): void; + + /** + * If S[1] == 0, then double(S) == (S[2..128] || 0); + * otherwise, double(S) == (S[2..128] || 0) xor + * (zeros(120) || 10000111). + * Both OCB and EAX (through CMAC) require this function to be constant-time. + * @param data + */ + /* Illegal function name 'double' can't be used here + function double(data: Uint8Array): void; */ - function verify(algo: enums.publicKey, hash_algo: enums.hash, msg_MPIs: Array, publickey_MPIs: Array, data: string): boolean; - } -} -export namespace enums { - enum armor { - multipart_section, - multipart_last, - signed, - message, - public_key, - private_key + /** + * Shift a Uint8Array to the right by n bits + * @param array The array to shift + * @param bits Amount of bits to shift (MUST be smaller + * than 8) + * @returns Resulting array. + */ + function shiftRight(array: Uint8Array, bits: Integer): string; + + /** + * Get native Web Cryptography api, only the current version of the spec. + * The default configuration is to use the api when available. But it can + * be deactivated with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCrypto(): object; + + /** + * Get native Web Cryptography api for all browsers, including legacy + * implementations of the spec e.g IE11 and Safari 8/9. The default + * configuration is to use the api when available. But it can be deactivated + * with config.use_native + * @returns The SubtleCrypto api or 'undefined' + */ + function getWebCryptoAll(): object; + + /** + * Detect Node.js runtime. + */ + function detectNode(): void; + + /** + * Get native Node.js module + * @param The module to require + * @returns The required module or 'undefined' + */ + function nodeRequire(The: string): object; + + /** + * Get native Node.js crypto api. The default configuration is to use + * the api when available. But it can also be deactivated with config.use_native + * @returns The crypto module or 'undefined' + */ + function getNodeCrypto(): object; + + /** + * Get native Node.js Buffer constructor. This should be used since + * Buffer is not available under browserify. + * @returns The Buffer constructor or 'undefined' + */ + function getNodeBuffer(): Function; + + /** + * Format user id for internal use. + */ + function formatUserId(): void; + + /** + * Parse user id. + */ + function parseUserId(): void; + + /** + * Normalize line endings to \r\n + */ + function canonicalizeEOL(): void; + + /** + * Convert line endings from canonicalized \r\n to native \n + */ + function nativeEOL(): void; + + /** + * Remove trailing spaces and tabs from each line + */ + function removeTrailingSpaces(): void; + + /** + * Encode input buffer using Z-Base32 encoding. + * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 + * @param data The binary data to encode + * @returns Binary data encoded using Z-Base32 + */ + function encodeZBase32(data: Uint8Array): string; } - enum compression { - uncompressed, - zip, - zlib, - bzip2 + namespace wkd { + class WKD { + /** + * Initialize the WKD client + */ + constructor(); + + /** + * Search for a public key using Web Key Directory protocol. + * @param options.email User's email. + * @param options.rawBytes Returns Uint8Array instead of parsed key. + * @returns The public key. + */ + lookup(): Promise, err: Array | null }>; + } } - enum hash { - md5, - sha1, - ripemd, - sha256, - sha384, - sha512, - sha224 - } - - enum packet { - publicKeyEncryptedSessionKey, - signature, - symEncryptedSessionKey, - onePassSignature, - secretKey, - publicKey, - secretSubkey, - compressed, - symmetricallyEncrypted, - marker, - literal, - trust, - userid, - publicSubkey, - userAttribute, - symEncryptedIntegrityProtected, - modificationDetectionCode, - } - - enum publicKey { - rsa_encrypt_sign, - rsa_encrypt, - rsa_sign, - elgamal, - dsa - } - - enum symmetric { - plaintext, - idea, - tripledes, - cast5, - blowfish, - aes128, - aes192, - aes256, - twofish - } - - enum keyStatus { - invalid, - expired, - revoked, - valid, - no_self_cert - } - - enum reasonForRevocation { - no_reason, - key_superseded, - key_compromised, - key_retired, - userid_invalid - } -} - -export namespace key { - interface KeyResult { - keys: Array, - err: Array - } - - /** Class that represents an OpenPGP key. Must contain a primary key. Can contain additional subkeys, signatures, user ids, user attributes. + namespace worker { + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/worker */ - interface Key { - armor(): string, - decrypt(passphrase: string): boolean; - getExpirationTime(): Date; - getKeyIds(): Array; - getPreferredHashAlgorithm(): string; - getPrimaryUser(): any; - getUserIds(): Array; - isPrivate(): boolean; - isPublic(): boolean; - primaryKey: packet.PublicKey; - toPublic(): Key; - update(key: Key): void; - verifyPrimaryKey(): enums.keyStatus; + namespace async_proxy { + class AsyncProxy { + /** + * Initializes a new proxy and loads the web worker + * @param path The path to the worker or 'openpgp.worker.js' by default + * @param n number of workers to initialize if path given + * @param config config The worker configuration + * @param worker alternative to path parameter: web worker initialized with 'openpgp.worker.js' + */ + constructor(path: string, n: number, config: object, worker: any[]); + + /** + * Message handling + */ + handleMessage(): void; + + /** + * Get new request ID + * @returns New unique request ID + */ + getID(): Integer; + + /** + * Send message to worker with random data + * @param size Number of bytes to send + */ + seedRandom(size: Integer): void; + + /** + * Terminates the workers + */ + terminate(): void; + + /** + * Generic proxy function that handles all commands from the public api. + * @param method the public api function to be delegated to the worker thread + * @param options the api function's options + * @returns see the corresponding public api functions for their return types + */ + delegate(method: string, options: object): Promise; + } + } + + /** + * @see module:openpgp.initWorker + * @see module:openpgp.getWorker + * @see module:openpgp.destroyWorker + * @see module:worker/async_proxy + */ + namespace worker { + /** + * Handle random buffer exhaustion by requesting more random bytes from the main window + * @returns Empty Promise whose resolution indicates that the buffer has been refilled + */ + function randomCallback(): Promise; + + /** + * Set config from main context to worker context. + * @param config The openpgp configuration + */ + function configure(config: object): void; + + /** + * Seed the library with entropy gathered window.crypto.getRandomValues + * as this api is only avalible in the main window. + * @param buffer Some random bytes + */ + function seedRandom(buffer: any[]): void; + + /** + * Generic proxy function that handles all commands from the public api. + * @param method The public api function to be delegated to the worker thread + * @param options The api function's options + */ + function delegate(method: string, options: object): void; + + /** + * Respond to the main window. + * @param event Contains event type and data + */ + function response(event: object): void; + } } - /** Generates a new OpenPGP key. Currently only supports RSA keys. Primary and subkey will be of same type. - - @param options - */ - function generate(options: KeyOptions): Key; - - /** Reads an OpenPGP armored text and returns one or multiple key objects - - @param armoredText text to be parsed - */ - function readArmored(armoredText: string): Promise; -} - -export namespace message { - /** Class that represents an OpenPGP message. Can be an encrypted message, signed message, compressed message or literal message - */ - interface Message { - /** Returns ASCII armored text of message - */ - armor(): string, - - /** Decrypt the message - @param privateKey private key with decrypted secret data - */ - decrypt(privateKey: key.Key): Array, - - /** Encrypt the message - @param keys array of keys, used to encrypt the message - */ - encrypt(keys: Array): Array, - - /** Returns the key IDs of the keys to which the session key is encrypted - */ - getEncryptionKeyIds(): Array, - - /** Get literal data that is the body of the message - */ - getLiteralData(): string, - - /** Returns the key IDs of the keys that signed the message - */ - getSigningKeyIds(): Array, - - /** Get literal data as text - */ - getText(): string, - - /** Sign the message (the literal data packet of the message) - @param privateKey private keys with decrypted secret key data for signing - */ - sign(privateKey: Array): Message, - - /** Unwrap compressed message - */ - unwrapCompressed(): Message, - - /** Verify message signatures - @param keys array of keys to verify signatures - */ - verify(keys: Array): Array, - - packets: { - write(): Uint8Array, - }, - } - - /** creates new message object from binary data - @param bytes - */ - function fromBinary(bytes: Uint8Array | ReadableStream): Message; - - /** creates new message object from text - @param text - */ - function fromText(text: string): Message; - - /** reads an OpenPGP armored message and returns a message object - - @param armoredText text to be parsed - */ - function readArmored(armoredText: string): Promise; /** - * reads an OpenPGP message as byte array and returns a message object - * @param {Uint8Array} input binary message - * @returns {Message} new message object - * @static + * Set the path for the web worker script and create an instance of the async proxy + * @param path relative path to the worker scripts, default: 'openpgp.worker.js' + * @param n number of workers to initialize + * @param workers alternative to path parameter: web workers initialized with 'openpgp.worker.js' */ - function read(data: Uint8Array): Promise; -} - -export namespace packet { - interface PublicKey { - algorithm: enums.publicKey; - created: Date; - fingerprint: string; - - getBitSize(): number; - getFingerprint(): string; - getKeyId(): Keyid; - read(input: string): any; - write(): any; - } - - interface SecretKey extends PublicKey { - read(bytes: string): void; - write(): string; - clearPrivateMPIs(str_passphrase: string): boolean; - encrypt(passphrase: string): void; - } - - /** Allocate a new packet from structured packet clone - @param packetClone packet clone - */ - function fromStructuredClone(packetClone: Object): Object - - /** Allocate a new packet - @param property name from enums.packet - */ - function newPacketFromTag(tag: string): Object; -} - -export namespace util { - /** - * Get transferable objects to pass buffers with zero copy (similar to "pass by reference" in C++) - * See: https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage - * Also, convert ReadableStreams to MessagePorts - * @param obj the options object to be passed to the web worker - * @returns an array of binary data to be passed - */ - function getTransferables(obj: Object): ArrayBuffer[]; + function initWorker(path: string, n?: number, workers?: any[]): void; /** - * Convert MessagePorts back to ReadableStreams - * @param obj + * Returns a reference to the async proxy if the worker was initialized with openpgp.initWorker() + * @returns the async proxy or null if not initialized + */ + function getWorker(): worker.async_proxy.AsyncProxy | null; + + /** + * Cleanup the current instance of the web worker. + */ + function destroyWorker(): void; + + interface UserID { + name: string; + email: string; + } + + interface KeyOptions { + /** + * array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + */ + userIds: UserID[]; + /** + * (optional) The passphrase used to encrypt the resulting private key + */ + passphrase?: string; + /** + * (optional) number of bits for RSA keys: 2048 or 4096. + */ + numBits?: number; + /** + * (optional) The number of seconds after the key creation time that the key expires + */ + keyExpirationTime?: number; + /** + * (optional) elliptic curve for ECC keys: elliptic curve for ECC keys: + * curve25519, p256, p384, p521, secp256k1, + * brainpoolP256r1, brainpoolP384r1, or brainpoolP512r1. + */ + curve?: string; + /** + * (optional) override the creation date of the key and the key signatures + */ + date?: Date; + /** + * (optional) options for each subkey, default to main key options. e.g. [ {sign: true, passphrase: '123'}] + * sign parameter defaults to false, and indicates whether the subkey should sign rather than encrypt + */ + subkeys?: { sign: true, passphrase: "string" }[]; + } + + /** + * Generates a new OpenPGP key pair. Supports RSA and ECC keys. Primary and subkey will be of same type. + * @param options + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ + function generateKey(option: KeyOptions): Promise<{ key: key.Key, privateKeyArmored: string, publicKeyArmored: string, revocationCertificate: string }>; + + /** + * Reformats signature packets for a key and rewraps key object. + * @param privateKey private key to reformat + * @param userIds array of user IDs e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @param passphrase (optional) The passphrase used to encrypt the resulting private key + * @param keyExpirationTime (optional) The number of seconds after the key creation time that the key expires + * @param revocationCertificate (optional) Whether the returned object should include a revocation certificate to revoke the public key + * @returns The generated key object in the form: + * { key:Key, privateKeyArmored:String, publicKeyArmored:String, revocationCertificate:String } + */ + function reformatKey(privateKey: key.Key, userIds: any[], passphrase?: string, keyExpirationTime?: number, revocationCertificate?: boolean): Promise; + + /** + * Revokes a key. Requires either a private key or a revocation certificate. + * If a revocation certificate is passed, the reasonForRevocation parameters will be ignored. + * @param key (optional) public or private key to revoke + * @param revocationCertificate (optional) revocation certificate to revoke the key with + * @param reasonForRevocation (optional) object indicating the reason for revocation + * @param reasonForRevocation.flag (optional) flag indicating the reason for revocation + * @param reasonForRevocation.string (optional) string explaining the reason for revocation + * @returns The revoked key object in the form: + * { privateKey:Key, privateKeyArmored:String, publicKey:Key, publicKeyArmored:String } + * (if private key is passed) or { publicKey:Key, publicKeyArmored:String } (otherwise) + */ + function revokeKey(key?: key.Key, revocationCertificate?: string, reasonForRevocation?: revokeKey_reasonForRevocation): Promise<{ + privateKey: key.Key, + privateKeyArmored: string, + publicKey: key.Key, + publicKeyArmored: string + } | { + publicKey: key.Key, + publicKeyArmored: string + }>; + + /** + * Unlock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the unlocked key object in the form: { key:Key } + */ + function decryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + + /** + * Lock a private key with your passphrase. + * @param privateKey the private key that is to be decrypted + * @param passphrase the user's passphrase(s) chosen during key generation + * @returns the locked key object in the form: { key:Key } + */ + function encryptKey(privateKey: key.Key, passphrase: string | any[]): Promise<{ key: key.Key }>; + + interface EncryptOptions { + /** + * message to be encrypted as created by openpgp.message.fromText or openpgp.message.fromBinary + */ + message: message.Message; + /** + * (optional) array of keys or single key, used to encrypt the message + */ + publicKeys?: key.Key | any[]; + /** + * (optional) private keys for signing. If omitted message will not be signed + */ + privateKeys?: key.Key | any[]; + /** + * (optional) array of passwords or a single password to encrypt the message + */ + passwords?: string | any[]; + /** + * (optional) session key in the form: { data:Uint8Array, algorithm:String } + */ + sessionKey?: { data: Uint8Array, algorithm: string }; + /** + * (optional) which compression algorithm to compress the message with, defaults to what is specified in config + */ + compression?: enums.compression; + /** + * (optional) if the return values should be ascii armored or the message/signature objects + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the signature should be detached (if true, signature will be added to returned object) + */ + detached?: boolean; + /** + * (optional) a detached signature to add to the encrypted message + */ + signature?: signature.Signature; + /** + * (optional) if the unencrypted session key should be added to returned object + */ + returnSessionKey?: boolean; + /** + * (optional) use a key ID of 0 instead of the public key IDs + */ + wildcard?: boolean; + /** + * (optional) override the creation date of the message signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[]; + /** + * (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Robert Receiver', email:'robert@openpgp.org' }] + */ + toUserIds?: UserID[] + } + + interface EncryptResult { + data: string | ReadableStream; + message: message.Message; + signature: string | ReadableStream | signature.Signature; + sessionKey: { data: Uint8Array, algorithm: string, aeadAlgorithm: string }; + } + + /** + * Encrypts message text/data with public keys, passwords or both at once. At least either public keys or passwords + * must be specified. If private keys are specified, those will be used to sign the message. + * @param options + * @returns Object containing encrypted (and optionally signed) message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message, (if `armor` was false) + * signature: string|ReadableStream|NodeStream, (if `detached` was true and `armor` was true) + * signature: Signature (if `detached` was true and `armor` was false) + * sessionKey: { data, algorithm, aeadAlgorithm } (if `returnSessionKey` was true) + * } + */ + function encrypt(options: EncryptOptions): Promise; + + interface DecryptOptions { + /** + * the message object with the encrypted data + */ + message: message.Message; + /** + * (optional) private keys with decrypted secret key data or session key + */ + privateKeys?: key.Key | key.Key[]; + /** + * (optional) passwords to decrypt the message + */ + passwords?: string | string[]; + /** + * (optional) session keys in the form: { data:Uint8Array, algorithm:String } + */ + sessionKeys?: { data: Uint8Array, algorithm: string } | { data: Uint8Array, algorithm: string }[]; + /** + * (optional) array of public keys or single key, to verify signatures + */ + publicKeys?: key.Key | key.Key[]; + /** + * (optional) whether to return data as a string(Stream) or Uint8Array(Stream). If 'utf8' (the default), also normalize newlines. + */ + format?: 'utf8' | 'binary'; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date + } + + interface DecryptResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream, + filename: string, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] + } + + /** + * Decrypts a message with the user's private key, a session key or a password. Either a private key, + * a session key or a password must be specified. + * @param options + * @returns Object containing decrypted and verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if format was 'utf8', the default) + * data: Uint8Array|ReadableStream|NodeStream, (if format was 'binary') + * filename: string, + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if streaming was false) + * }, ... + * ] + * } + */ + function decrypt(options: DecryptOptions): Promise; + + interface SignOptions { + /** + * (cleartext) message to be signed + */ + message: cleartext.CleartextMessage | message.Message; + /** + * array of keys or single key with decrypted secret key data to sign cleartext + */ + privateKeys: key.Key | any[]; + /** + * (optional) if the return value should be ascii armored or the message object + */ + armor?: boolean; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) if the return value should contain a detached signature + */ + detached?: boolean; + /** + * (optional) override the creation date of the signature + */ + date?: Date; + /** + * (optional) array of user IDs to sign with, one per key in `privateKeys`, e.g. [ { name:'Steve Sender', email:'steve@openpgp.org' }] + */ + fromUserIds?: UserID[] + } + + interface SignResult { + data: string | ReadableStream | NodeStream, + message: message.Message, + signature: string | ReadableStream | NodeStream | signature.Signature + } + + /** + * Signs a cleartext message. + * @param options + * @returns Object containing signed message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * message: Message (if `armor` was false) + * } + * Or, if `detached` was true: + * { + * signature: string|ReadableStream|NodeStream, (if `armor` was true, the default) + * signature: Signature (if `armor` was false) + * } + */ + function sign(options: SignOptions): Promise; + + interface VerifyOptions { + /** + * array of publicKeys or single key, to verify signatures + */ + publicKeys: key.Key | any[]; + /** + * (cleartext) message object with signatures + */ + message: cleartext.CleartextMessage | message.Message; + /** + * (optional) whether to return data as a stream. Defaults to the type of stream `message` was created from, if any. + */ + streaming?: 'web' | 'node' | false; + /** + * (optional) detached signature for verification + */ + signature?: signature.Signature; + /** + * (optional) use the given date for verification instead of the current time + */ + date?: Date + } + + interface VerifyResult { + data: string | ReadableStream | NodeStream | Uint8Array | ReadableStream | NodeStream, + signatures: { + keyid: type.keyid.Keyid, + verified: Promise, + valid: boolean + }[] + } + + /** + * Verifies signatures of cleartext signed message + * @param options + * @returns Object containing verified message in the form: + * { + * data: string|ReadableStream|NodeStream, (if `message` was a CleartextMessage) + * data: Uint8Array|ReadableStream|NodeStream, (if `message` was a Message) + * signatures: [ + * { + * keyid: module:type/keyid, + * verified: Promise, + * valid: boolean (if `streaming` was false) + * }, ... + * ] + * } + */ + function verify(options: VerifyOptions): Promise; + + /** + * Encrypt a symmetric session key with public keys, passwords, or both at once. At least either public keys + * or passwords must be specified. + * @param data the session key to be encrypted e.g. 16 random bytes (for aes128) + * @param algorithm algorithm of the symmetric session key e.g. 'aes128' or 'aes256' + * @param aeadAlgorithm (optional) aead algorithm, e.g. 'eax' or 'ocb' + * @param publicKeys (optional) array of public keys or single key, used to encrypt the key + * @param passwords (optional) passwords for the message + * @param wildcard (optional) use a key ID of 0 instead of the public key IDs + * @param date (optional) override the date + * @param toUserIds (optional) array of user IDs to encrypt for, one per key in `publicKeys`, e.g. [ { name:'Phil Zimmermann', email:'phil@openpgp.org' }] + * @returns the encrypted session key packets contained in a message object + */ + function encryptSessionKey(data: Uint8Array, algorithm: string, aeadAlgorithm?: string, publicKeys?: key.Key | key.Key[], passwords?: string | string[], wildcard?: boolean, date?: Date, toUserIds?: any[]): Promise; + + /** + * Decrypt symmetric session keys with a private key or password. Either a private key or + * a password must be specified. + * @param message a message object containing the encrypted session key packets + * @param privateKeys (optional) private keys with decrypted secret key data + * @param passwords (optional) passwords to decrypt the session key + * @returns Array of decrypted session key, algorithm pairs in form: + * { data:Uint8Array, algorithm:String } + * or 'undefined' if no key packets found + */ + function decryptSessionKeys(message: message.Message, privateKeys?: key.Key | key.Key[], passwords?: string | string[]): Promise<{ data: Uint8Array, algorithm: string }[] | undefined>; + + /** + * Input validation + */ + function checkString(): void; + + /** + * Normalize parameter to an array if it is not undefined. + * @param param the parameter to be normalized + * @returns the resulting array or undefined + */ + function toArray(param: object): any[] | undefined; + + /** + * Convert data to or from Stream + * @param data the data to convert + * @param streaming (optional) whether to return a ReadableStream + * @returns the data in the respective format + */ + function convertStream(data: object, streaming?: 'web' | 'node' | false): object; + + /** + * Convert object properties from Stream + * @param obj the data to convert + * @param streaming (optional) whether to return ReadableStreams + * @param keys (optional) which keys to return as streams, if possible + * @returns the data in the respective format + */ + function convertStreams(obj: object, streaming: 'web' | 'node' | false, keys: any[]): object; + + /** + * Link result.data to the message stream for cancellation. + * Also, forward errors in the message to result.data. + * @param result the data to convert + * @param message message object + * @param erroringStream (optional) stream which either errors or gets closed without data * @returns */ - function restoreStreams(obj: Object): Object; + function linkStreams(result: object, message: message.Message, erroringStream: ReadableStream): object; /** - * Create hex string from a binary - * @param str String to convert - * @returns String containing the hexadecimal values + * Wait until signature objects have been verified + * @param signatures list of signatures */ - function str_to_hex(str: String): String; + function prepareSignatures(signatures: object): void; /** - * Create binary string from a hex encoded string - * @param str Hex string to convert - * @returns + * Global error handler that logs the stack trace and rethrows a high lvl error message. + * @param message A human readable high level error Message + * @param error The internal error that caused the failure */ - function hex_to_str(str: String): String; + function onError(message: string, error: Error): void; /** - * Convert a Uint8Array to an MPI-formatted Uint8Array. - * Note: the output is **not** an MPI object. - * @see - * @see - * @param bin An array of 8-bit integers to convert - * @returns MPI-formatted Uint8Array + * Check for native AEAD support and configuration by the user. Only + * browsers that implement the current WebCrypto specification support + * native GCM. Native EAX is built on CTR and CBC, which current + * browsers support. OCB and CFB are not natively supported. + * @returns If authenticated encryption should be used */ - function Uint8Array_to_MPI(bin: Uint8Array): Uint8Array; - - /** - * Convert a Base-64 encoded string an array of 8-bit integer - * Note: accepts both Radix-64 and URL-safe strings - * @param base64 Base-64 encoded string to convert - * @returns An array of 8-bit integers - */ - function b64_to_Uint8Array(base64: String): Uint8Array; - - /** - * Convert an array of 8-bit integer to a Base-64 encoded string - * @param bytes An array of 8-bit integers to convert - * @param url If true, output is URL-safe - * @returns Base-64 encoded string - */ - function Uint8Array_to_b64(bytes: Uint8Array, url: boolean): String; - - /** - * Convert a hex string to an array of 8-bit integers - * @param hex A hex string to convert - * @returns An array of 8-bit integers - */ - function hex_to_Uint8Array(hex: String): Uint8Array; - - /** - * Convert an array of 8-bit integers to a hex string - * @param bytes Array of 8-bit integers to convert - * @returns Hexadecimal representation of the array - */ - function Uint8Array_to_hex(bytes: Uint8Array): String; - - /** - * Convert a string to an array of 8-bit integers - * @param str String to convert - * @returns An array of 8-bit integers - */ - function str_to_Uint8Array(str: String): Uint8Array; - - /** - * Convert an array of 8-bit integers to a string - * @param bytes An array of 8-bit integers to convert - * @returns String representation of the array - */ - function Uint8Array_to_str(bytes: Uint8Array): String; - - /** - * Convert a native javascript string to a Uint8Array of utf8 bytes - * @param str The string to convert - * @returns A valid squence of utf8 bytes - */ - function encode_utf8(str: String | ReadableStream): Uint8Array | ReadableStream; - - /** - * Convert a Uint8Array of utf8 bytes to a native javascript string - * @param utf8 A valid squence of utf8 bytes - * @returns A native javascript string - */ - function decode_utf8(utf8: Uint8Array | ReadableStream): String | ReadableStream; - - /** - * Concat a list of Uint8Arrays, Strings or Streams - * The caller must not mix Uint8Arrays with Strings, but may mix Streams with non-Streams. - * @param Array of Uint8Arrays/Strings/Streams to concatenate - * @returns Concatenated array - */ - var concat: any; - - /** - * Concat Uint8Arrays - * @param Array of Uint8Arrays to concatenate - * @returns Concatenated array - */ - var concatUint8Array: any; - - /** - * Check Uint8Array equality - * @param first array - * @param second array - * @returns equality - */ - function equalsUint8Array(first: Uint8Array, second: Uint8Array): Boolean; - - /** - * Calculates a 16bit sum of a Uint8Array by adding each character - * codes modulus 65535 - * @param Uint8Array to create a sum of - * @returns 2 bytes containing the sum of all charcodes % 65535 - */ - function write_checksum(Uint8Array: Uint8Array): Uint8Array; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug(str: String): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexarray_dump(str: String): void; - - /** - * Helper function to print a debug message. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_hexstr_dump(str: String): void; - - /** - * Helper function to print a debug error. Debug - * messages are only printed if - * @param str String of the debug message - */ - function print_debug_error(str: String): void; - - /** - * Read a stream to the end and print it to the console when it's closed. - * @param str String of the debug message - * @param input Stream to print - * @param concat Function to concatenate chunks of the stream (defaults to util.concat). - */ - function print_entire_stream(str: String, input: ReadableStream | Uint8Array | String, concat: Function): void; - - /** - * If S[1] == 0, then double(S) == (S[2..128] || 0); - * otherwise, double(S) == (S[2..128] || 0) xor - * (zeros(120) || 10000111). - * Both OCB and EAX (through CMAC) require this function to be constant-time. - * @param data - */ - /* Illegal function name 'double' can't be used here - export function double(data: Uint8Array): void; - */ - - /** - * Shift a Uint8Array to the right by n bits - * @param array The array to shift - * @param bits Amount of bits to shift (MUST be smaller - * than 8) - * @returns Resulting array. - */ - function shiftRight(array: Uint8Array, bits: number): String; - - /** - * Get native Web Cryptography api, only the current version of the spec. - * The default configuration is to use the api when available. But it can - * be deactivated with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCrypto(): Object; - - /** - * Get native Web Cryptography api for all browsers, including legacy - * implementations of the spec e.g IE11 and Safari 8/9. The default - * configuration is to use the api when available. But it can be deactivated - * with config.use_native - * @returns The SubtleCrypto api or 'undefined' - */ - function getWebCryptoAll(): Object; - - /** - * Detect Node.js runtime. - */ - function detectNode(): void; - - /** - * Get native Node.js module - * @param The module to require - * @returns The required module or 'undefined' - */ - function nodeRequire(The: String): Object; - - /** - * Get native Node.js crypto api. The default configuration is to use - * the api when available. But it can also be deactivated with config.use_native - * @returns The crypto module or 'undefined' - */ - function getNodeCrypto(): Object; - - /** - * Get native Node.js Buffer constructor. This should be used since - * Buffer is not available under browserify. - * @returns The Buffer constructor or 'undefined' - */ - function getNodeBuffer(): Function; - - /** - * Format user id for internal use. - */ - function formatUserId(): void; - - /** - * Parse user id. - */ - function parseUserId(): void; - - /** - * Normalize line endings to \r\n - */ - function canonicalizeEOL(): void; - - /** - * Convert line endings from canonicalized \r\n to native \n - */ - function nativeEOL(): void; - - /** - * Remove trailing spaces and tabs from each line - */ - function removeTrailingSpaces(): void; - - /** - * Encode input buffer using Z-Base32 encoding. - * See: https://tools.ietf.org/html/rfc6189#section-5.1.6 - * @param data The binary data to encode - * @returns Binary data encoded using Z-Base32 - */ - function encodeZBase32(data: Uint8Array): String; + function nativeAEAD(): boolean; } diff --git a/types/openpgp/ts3.2/openpgp-tests.ts b/types/openpgp/ts3.2/openpgp-tests.ts index 9c19f87339..fc3efeeda0 100644 --- a/types/openpgp/ts3.2/openpgp-tests.ts +++ b/types/openpgp/ts3.2/openpgp-tests.ts @@ -1,3 +1,5 @@ +import { openpgp } from "openpgp"; + // Open PGP Sample codes var options: openpgp.KeyOptions = { @@ -8,7 +10,6 @@ var options: openpgp.KeyOptions = { }], passphrase: 'super long and hard to guess secret' }; - openpgp.generateKey(options).then(function (keypair) { // success var privkey = keypair.privateKeyArmored; @@ -38,7 +39,7 @@ openpgp.key.readArmored(spubkey) 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) { +openpgp.message.readArmored(pgpMessageStr).then(function (pgpMessage) { const options = { message: pgpMessage }; @@ -49,11 +50,12 @@ openpgp.message.readArmored(pgpMessageStr).then(function(pgpMessage) { // failure }); -const promises: [Promise, Promise] = [ +const promises: [Promise<{ keys: Array, err: Array | null }>, Promise] = [ openpgp.key.readArmored(sprivkey), openpgp.message.readArmored(pgpMessageStr) ]; + Promise.all(promises).then(function (values) { const keyObject: openpgp.key.KeyResult = values[0]; const pgpMessage: openpgp.message.Message = values[1]; @@ -70,7 +72,7 @@ Promise.all(promises).then(function (values) { // failure }); -openpgp.initWorker({ path:'openpgp.worker.js' }); +openpgp.initWorker('openpgp.worker.js'); (async () => { let msgOptions: openpgp.EncryptOptions; @@ -120,7 +122,7 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); const signed = await openpgp.sign(signOptions); - const signature = signed.signature as openpgp.Signature; + const signature = signed.signature as openpgp.signature.Signature; const message = signed.message; const verifyOptions: openpgp.VerifyOptions = { @@ -138,34 +140,38 @@ openpgp.initWorker({ path:'openpgp.worker.js' }); var keyoptions: openpgp.KeyOptions; -var mpi: openpgp.crypto.Mpi; -var mpis: Array; +var mpi: openpgp.type.mpi.MPI; +var mpis: Array; -openpgp.armor.armor(openpgp.enums.armor.message, {}, 0, 1); -openpgp.armor.dearmor(""); +openpgp.encoding.armor.armor(openpgp.enums.armor.message, {}, 0, 1); +openpgp.encoding.armor.dearmor(""); openpgp.cleartext.readArmored(""); -openpgp.crypto.generateSessionKey(openpgp.enums.symmetric.aes128); -openpgp.crypto.getPrefixRandom(openpgp.enums.symmetric.aes128); -openpgp.crypto.getPrivateMpiCount(openpgp.enums.symmetric.aes128); -openpgp.crypto.publicKeyDecrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, mpi); -openpgp.crypto.publicKeyEncrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpi); +openpgp.crypto.crypto.generateSessionKey(openpgp.enums.symmetric.aes128); +openpgp.crypto.crypto.getPrefixRandom(openpgp.enums.symmetric.aes128); +// openpgp.crypto.crypto.getPrivateMpiCount(openpgp.enums.symmetric.aes128); +openpgp.crypto.crypto.publicKeyDecrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, ""); +openpgp.crypto.crypto.publicKeyEncrypt(openpgp.enums.publicKey.rsa_encrypt, mpis, mpi, ""); +openpgp.crypto +// API update with no documentation openpgp.crypto.cfb.decrypt("", "", "", true); -openpgp.crypto.cfb.encrypt("", "", "", "", true); -openpgp.crypto.cfb.mdc({}, "", ""); +openpgp.crypto.cfb.encrypt("", "", "", true); +// Function removed from openpgp.crypto.cfb +// openpgp.crypto.cfb.mdc({}, "", ""); -openpgp.crypto.hash.digest(openpgp.enums.hash.md5, ""); +openpgp.crypto.hash.digest(openpgp.enums.hash.md5, new Uint8Array([0, 1])); openpgp.crypto.hash.getHashByteLength(openpgp.enums.hash.md5); -openpgp.crypto.random.getRandomBigInteger(0); +openpgp.crypto.random.getRandomBN(mpi, mpi); openpgp.crypto.random.getRandomBytes(0); -openpgp.crypto.random.getRandomValues(openpgp.util.str_to_Uint8Array("")); -openpgp.crypto.random.getSecureRandom(0, 1); +// function removed from openpgp.crypto.random +// openpgp.crypto.random.getRandomValues(openpgp.util.str_to_Uint8Array("")); +// openpgp.crypto.random.getSecureRandom(0, 1); -openpgp.crypto.signature.sign(openpgp.enums.hash.md5, openpgp.enums.publicKey.rsa_encrypt, mpis, mpis, ""); -openpgp.crypto.signature.verify(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, mpis, ""); +openpgp.crypto.signature.sign(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, new Uint8Array([0, 1]), new Uint8Array([0, 1])); +openpgp.crypto.signature.verify(openpgp.enums.publicKey.rsa_encrypt, openpgp.enums.hash.md5, mpis, mpis, new Uint8Array([0, 1]), new Uint8Array([0, 1])); openpgp.key.generate(keyoptions); openpgp.key.readArmored(""); diff --git a/types/openpgp/ts3.2/tsconfig.json b/types/openpgp/ts3.2/tsconfig.json index 9267c27cd0..5819fdf2ca 100644 --- a/types/openpgp/ts3.2/tsconfig.json +++ b/types/openpgp/ts3.2/tsconfig.json @@ -4,6 +4,7 @@ "lib": [ "es6", "dom" ], + "esModuleInterop": true, "noImplicitAny": true, "noImplicitThis": true, "strictNullChecks": false, diff --git a/types/openpgp/tsconfig.json b/types/openpgp/tsconfig.json index e9ff22b4ce..0f0960782b 100644 --- a/types/openpgp/tsconfig.json +++ b/types/openpgp/tsconfig.json @@ -6,8 +6,9 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": false, "strictFunctionTypes": true, + "strictNullChecks": false, + "allowSyntheticDefaultImports": true, "baseUrl": "../", "typeRoots": [ "../" diff --git a/types/openpgp/tslint.json b/types/openpgp/tslint.json index 3242154128..3db8366030 100644 --- a/types/openpgp/tslint.json +++ b/types/openpgp/tslint.json @@ -17,6 +17,7 @@ "space-before-function-paren": false, "typedef-whitespace": false, "unified-signatures": false, - "whitespace": false + "whitespace": false, + "no-trailing-whitespace": false } } \ No newline at end of file diff --git a/types/p-any/index.d.ts b/types/p-any/index.d.ts deleted file mode 100644 index 8b4df3504c..0000000000 --- a/types/p-any/index.d.ts +++ /dev/null @@ -1,41 +0,0 @@ -// Type definitions for p-any 1.1 -// Project: https://github.com/sindresorhus/p-any#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -import AggregateErrorModule = require('aggregate-error'); - -export = pAny; - -declare function pAny( - values: [Value, Value, Value, Value, Value, Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny( - values: [Value, Value, Value, Value, Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny( - values: [Value, Value, Value, Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny( - values: [Value, Value, Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny(values: [Value, Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny(values: [Value, Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny(values: [Value, Value, Value, Value], - options?: pAny.Options): Promise; -declare function pAny(values: [Value, Value, Value], options?: pAny.Options): Promise; -declare function pAny(values: [Value, Value], options?: pAny.Options): Promise; -declare function pAny(values: Iterable> | Array>, options?: pAny.Options): Promise; - -type Value = T | PromiseLike; - -declare namespace pAny { - interface Options { - filter?(value: T): boolean; - } - - const AggregateError: typeof AggregateErrorModule; -} diff --git a/types/p-any/p-any-tests.ts b/types/p-any/p-any-tests.ts deleted file mode 100644 index 9e5e6520b9..0000000000 --- a/types/p-any/p-any-tests.ts +++ /dev/null @@ -1,24 +0,0 @@ -import got = require('got'); -import pAny = require('p-any'); - -pAny([ - got.head('github.com').then(() => 'github'), - got.head('google.com').then(() => 'google'), - got.head('twitter.com').then(() => 'twitter'), -]).then(first => { - const str: string = first; -}); - -pAny(new Set([ - got.head('github.com').then(() => 'github'), - got.head('google.com').then(() => 'google'), - got.head('twitter.com').then(() => 'twitter'), -]), { - filter(str: string) { - return true; - } -}).then(first => { - const str: string = first; -}); - -throw new pAny.AggregateError([]); diff --git a/types/p-any/tsconfig.json b/types/p-any/tsconfig.json deleted file mode 100644 index 67d983361a..0000000000 --- a/types/p-any/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-any-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-any/tslint.json b/types/p-any/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-any/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-cancelable/index.d.ts b/types/p-cancelable/index.d.ts deleted file mode 100644 index 8375149e32..0000000000 --- a/types/p-cancelable/index.d.ts +++ /dev/null @@ -1,70 +0,0 @@ -// Type definitions for p-cancelable 1.0 -// Project: https://github.com/sindresorhus/p-cancelable#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = PCancelable; - -declare const PCancelable: PCancelableConstructor; - -interface PCancelableConstructor extends PromiseConstructor { - readonly prototype: PCancelable.PCancelable; - readonly CancelError: PCancelable.CancelErrorConstructor; - - new ( - executor: ( - resolve: (value?: T | PromiseLike) => void, - reject: (reason?: any) => void, - onCancel: PCancelable.OnCancelFn - ) => void - ): PCancelable.PCancelable; - - fn( - userFn: (onCancel: PCancelable.OnCancelFn) => PromiseLike - ): () => PCancelable.PCancelable; - fn( - userFn: (param1: T1, onCancel: PCancelable.OnCancelFn) => PromiseLike - ): (param1: T1) => PCancelable.PCancelable; - fn( - userFn: (param1: T1, param2: T2, onCancel: PCancelable.OnCancelFn) => PromiseLike - ): (param1: T1, param2: T2) => PCancelable.PCancelable; - fn( - userFn: ( - param1: T1, - param2: T2, - param3: T3, - onCancel: PCancelable.OnCancelFn - ) => PromiseLike - ): (param1: T1, param2: T2, param3: T3) => PCancelable.PCancelable; - fn( - userFn: ( - param1: T1, - param2: T2, - param3: T3, - param4: T4, - onCancel: PCancelable.OnCancelFn - ) => PromiseLike - ): (param1: T1, param2: T2, param3: T3, param4: T4) => PCancelable.PCancelable; - fn(userFn: (...args: any[]) => PromiseLike): (args: any[]) => PCancelable.PCancelable; -} - -declare namespace PCancelable { - interface PCancelable extends Promise { - readonly isCanceled: boolean; - cancel(reason?: string): void; - } - - interface OnCancelFn { - (cancelHandler: () => void): void; - shouldReject: boolean; - } - - interface CancelErrorConstructor extends ErrorConstructor { - new (reason?: string): CancelError; - } - - interface CancelError extends Error { - readonly name: 'CancelError'; - readonly isCanceled: boolean; - } -} diff --git a/types/p-cancelable/p-cancelable-tests.ts b/types/p-cancelable/p-cancelable-tests.ts deleted file mode 100644 index 3e15c7d1f8..0000000000 --- a/types/p-cancelable/p-cancelable-tests.ts +++ /dev/null @@ -1,88 +0,0 @@ -/// - -import PCancelable = require('p-cancelable'); -import { EventEmitter } from 'events'; - -const cancelablePromise: PCancelable.PCancelable<{}> = new PCancelable( - (resolve, reject, onCancel) => { - class Worker extends EventEmitter { - close() {} - } - - const worker = new Worker(); - - onCancel.shouldReject = false; - onCancel(() => { - worker.close(); - }); - - worker.on('finish', resolve); - worker.on('error', reject); - } -); - -cancelablePromise - .then(value => { - console.log('Operation finished successfully:', value); - }) - .catch(reason => { - if (cancelablePromise.isCanceled) { - // Handle the cancelation here - console.log('Operation was canceled'); - return; - } - - throw reason; - }); - -setTimeout(() => { - cancelablePromise.cancel(); - cancelablePromise.cancel('foo'); -}, 10000); - -const fn0 = PCancelable.fn(onCancel => { - // $ExpectType OnCancelFn - onCancel; - - return Promise.resolve(10); -}); -// $ExpectType () => PCancelable -fn0; - -const fn1 = PCancelable.fn((p1: string, onCancel: PCancelable.OnCancelFn) => { - return Promise.resolve(10); -}); -// $ExpectType (param1: string) => PCancelable -fn1; - -const fn2 = PCancelable.fn((p1: string, p2: boolean, onCancel: PCancelable.OnCancelFn) => { - return Promise.resolve(10); -}); -// $ExpectType (param1: string, param2: boolean) => PCancelable -fn2; - -const fn3 = PCancelable.fn( - (p1: string, p2: boolean, p3: number, onCancel: PCancelable.OnCancelFn) => { - return Promise.resolve(10); - } -); -// $ExpectType (param1: string, param2: boolean, param3: number) => PCancelable -fn3; - -const fn4 = PCancelable.fn( - (p1: string, p2: boolean, p3: number, p4: null, onCancel: PCancelable.OnCancelFn) => { - return Promise.resolve(10); - } -); -// $ExpectType (param1: string, param2: boolean, param3: number, param4: null) => PCancelable -fn4; - -const promise = fn0(); -let num: number; -promise.then(innum => (num = innum)); -if (!promise.isCanceled) { - promise.cancel(); -} - -const err: PCancelable.CancelError = new PCancelable.CancelError(); -throw err; diff --git a/types/p-cancelable/tsconfig.json b/types/p-cancelable/tsconfig.json deleted file mode 100644 index 504511081d..0000000000 --- a/types/p-cancelable/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-cancelable-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-cancelable/tslint.json b/types/p-cancelable/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-cancelable/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-catch-if/index.d.ts b/types/p-catch-if/index.d.ts deleted file mode 100644 index a832b88534..0000000000 --- a/types/p-catch-if/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for p-catch-if 1.0 -// Project: https://github.com/sindresorhus/p-catch-if#readme -// Definitions by: Linus Unnebäck -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -declare namespace pCatchIf { - type Predicate = ErrorConstructor | ReadonlyArray | boolean | ((err: Error) => boolean | PromiseLike); -} - -declare function pCatchIf(predicate: pCatchIf.Predicate, fn: (err: Error) => T): (err: Error) => T; - -export = pCatchIf; diff --git a/types/p-catch-if/p-catch-if-tests.ts b/types/p-catch-if/p-catch-if-tests.ts deleted file mode 100644 index f42679cce6..0000000000 --- a/types/p-catch-if/p-catch-if-tests.ts +++ /dev/null @@ -1,39 +0,0 @@ -import pCatchIf = require('p-catch-if'); - -/**** Setup "fake" environemt ****/ - -declare function getData(): Promise<{}>; -declare function retry(fn: () => T): T; -declare function recordError(err: Error): undefined; -declare function isProduction(): boolean; -declare function sendError(err: Error): Promise; -declare function checkResults(): Promise; - -declare const TimeoutError: ErrorConstructor; -declare const NetworkError: ErrorConstructor; -declare const UnicornError: ErrorConstructor; - -declare const console: { error(): undefined }; - -/**** Use examples from the official library's readme.md ****/ - -// error constructor -getData().catch(pCatchIf(TimeoutError, () => retry(getData))); - -// multiple error constructors -getData().catch(pCatchIf([NetworkError, TimeoutError], () => retry(getData))); - -// boolean -getData().catch(pCatchIf(isProduction, recordError)); - -// function -const hasUnicornMessage = (err: Error) => err.message.includes('unicorn'); -getData().catch(pCatchIf(hasUnicornMessage, console.error)); - -// promise-returning function -const handler = (err: Error) => sendError(err).then(checkResults); -getData().catch(pCatchIf(handler, console.error)); - -// can also be nested -const validateMessage = (err: Error) => err.message === 'Too many rainbows'; -getData().catch(pCatchIf(UnicornError, pCatchIf(validateMessage, console.error))); diff --git a/types/p-catch-if/tsconfig.json b/types/p-catch-if/tsconfig.json deleted file mode 100644 index bdabef2511..0000000000 --- a/types/p-catch-if/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-catch-if-tests.ts" - ] -} diff --git a/types/p-catch-if/tslint.json b/types/p-catch-if/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-catch-if/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-debounce/index.d.ts b/types/p-debounce/index.d.ts deleted file mode 100644 index 4a18903762..0000000000 --- a/types/p-debounce/index.d.ts +++ /dev/null @@ -1,45 +0,0 @@ -// Type definitions for p-debounce 1.0 -// Project: https://github.com/sindresorhus/p-debounce#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pDebounce; - -declare function pDebounce(fn: () => PromiseLike | R, wait: number, options?: pDebounce.Options): (() => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1) => PromiseLike | R, wait: number, options?: pDebounce.Options): ((arg1: T1) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1, arg2: T2) => PromiseLike | R, wait: number, options?: pDebounce.Options): ((arg1: T1, arg2: T2) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1, arg2: T2, arg3: T3) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise) & { abort(): void; }; -declare function pDebounce( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7) => Promise) & { abort(): void; }; -declare function pDebounce( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8) => Promise) & { abort(): void; }; -declare function pDebounce( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9) => Promise) & { abort(): void; }; -declare function pDebounce( - fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10) => PromiseLike | R, - wait: number, - options?: pDebounce.Options): ((arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6, arg7: T7, arg8: T8, arg9: T9, arg10: T10) => Promise) & { abort(): void; }; -declare function pDebounce(fn: (...args: any[]) => PromiseLike | R, wait: number, options?: pDebounce.Options): ((...args: any[]) => Promise) & { abort(): void; }; - -declare namespace pDebounce { - interface Options { - leading?: boolean; - } -} diff --git a/types/p-debounce/p-debounce-tests.ts b/types/p-debounce/p-debounce-tests.ts deleted file mode 100644 index 5e7b7a49ac..0000000000 --- a/types/p-debounce/p-debounce-tests.ts +++ /dev/null @@ -1,26 +0,0 @@ -import pDebounce = require('p-debounce'); - -const expensiveCall = (input: number) => Promise.resolve(input); - -const debouncedFn = pDebounce(expensiveCall, 200); -const debouncedFn2 = pDebounce(expensiveCall, 200, {leading: true}); - -for (const i of [1, 2, 3]) { - debouncedFn(i).then(i => { - const num: number = i; - }); -} - -pDebounce(() => true, 2)(); -pDebounce((n: number, s: string) => true, 2)(1, 's'); -pDebounce((n: number, s: string, b: boolean) => true, 2)(1, 's', true); -pDebounce((n: number, s: string, b: boolean, n2: number) => true, 2)(1, 's', true, 1); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string) => true, 2)(1, 's', true, 1, 's'); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean) => true, 2)(1, 's', true, 1, 's', false); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean, n3: number) => true, 2)(1, 's', true, 1, 's', false, 1); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean, n3: number, n4: number) => true, 2)(1, 's', true, 1, 's', false, 1, 2); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean, n3: number, n4: number, n5: number) => true, 2)(1, 's', true, 1, 's', false, 1, 2, 3); -pDebounce((n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean, n3: number, n4: number, n5: number, n6: number) => true, 2)(1, 's', true, 1, 's', false, 1, 2, 3, 4); -pDebounce( - (n: number, s: string, b: boolean, n2: number, s2: string, b2: boolean, n3: number, n4: number, n5: number, n6: number, s3: string) => true, - 2)(1, 's', true, 1, 's', false, 1, 2, 3, 4, 'as'); diff --git a/types/p-debounce/tsconfig.json b/types/p-debounce/tsconfig.json deleted file mode 100644 index 4de0f115d8..0000000000 --- a/types/p-debounce/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-debounce-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-debounce/tslint.json b/types/p-debounce/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-debounce/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-each-series/index.d.ts b/types/p-each-series/index.d.ts deleted file mode 100644 index 7cf91112b8..0000000000 --- a/types/p-each-series/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for p-each-series 1.0 -// Project: https://github.com/sindresorhus/p-each-series#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pEachSeries; - -declare function pEachSeries(input: Iterable | T>, iterator: (element: T, index: number) => any): Promise; diff --git a/types/p-each-series/p-each-series-tests.ts b/types/p-each-series/p-each-series-tests.ts deleted file mode 100644 index 3766842e81..0000000000 --- a/types/p-each-series/p-each-series-tests.ts +++ /dev/null @@ -1,19 +0,0 @@ -import pEachSeries = require('p-each-series'); - -const keywords = [ - Promise.resolve('foo'), - 'rainbow', - 'pony' -]; - -const keywordSet = new Set(keywords); - -pEachSeries(keywords, el => Promise.resolve(el)).then(result => { - result; // $ExpectType string[] - const str: string = result[0]; -}); - -pEachSeries(keywordSet, (el, idx) => Promise.resolve(idx)).then(result => { - result; // $ExpectType string[] - const str: string = result[0]; -}); diff --git a/types/p-each-series/tsconfig.json b/types/p-each-series/tsconfig.json deleted file mode 100644 index e8cd900d05..0000000000 --- a/types/p-each-series/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-each-series-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-each-series/tslint.json b/types/p-each-series/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-each-series/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-every/index.d.ts b/types/p-every/index.d.ts deleted file mode 100644 index 57b41f0a4e..0000000000 --- a/types/p-every/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for p-every 1.0 -// Project: https://github.com/kevva/p-every#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pEvery; - -declare function pEvery(input: Iterable | T>, - testFn: (element: T, index: number) => boolean | Promise, - options?: pEvery.Options): Promise; - -declare namespace pEvery { - interface Options { - concurrency?: number; - } -} diff --git a/types/p-every/p-every-tests.ts b/types/p-every/p-every-tests.ts deleted file mode 100644 index df06fdf899..0000000000 --- a/types/p-every/p-every-tests.ts +++ /dev/null @@ -1,26 +0,0 @@ -import pEvery = require('p-every'); - -const places = [ - Promise.resolve('Norway'), - 'Bangkok, Thailand', - 'Berlin, Germany', - 'Tokyo, Japan' -]; - -pEvery(places, x => Promise.resolve(true)).then(result => { - const bool: boolean = result; -}); - -const places2 = [ - Promise.resolve('Norway'), - 'Bangkok, Thailand', - 'Berlin, Germany', - 5 -]; - -pEvery(places2, x => { - const strnum: string | number = x; - return Promise.resolve(true); -}, {concurrency: 2}).then(result => { - const bool: boolean = result; -}); diff --git a/types/p-every/tsconfig.json b/types/p-every/tsconfig.json deleted file mode 100644 index 979927093f..0000000000 --- a/types/p-every/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-every-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-every/tslint.json b/types/p-every/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-every/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-locate/index.d.ts b/types/p-locate/index.d.ts deleted file mode 100644 index 9ddc11197c..0000000000 --- a/types/p-locate/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for p-locate 2.0 -// Project: https://github.com/sindresorhus/p-locate#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pLocate; - -declare function pLocate(input: Iterable | T>, tester: (element: T) => Promise | boolean, options?: pLocate.Options): Promise; - -declare namespace pLocate { - interface Options { - concurrency?: number; - preserveOrder?: boolean; - } -} diff --git a/types/p-locate/p-locate-tests.ts b/types/p-locate/p-locate-tests.ts deleted file mode 100644 index acceb0376a..0000000000 --- a/types/p-locate/p-locate-tests.ts +++ /dev/null @@ -1,14 +0,0 @@ -import pLocate = require('p-locate'); - -const files = [ - 'unicorn.png', - 'rainbow.png', - 'pony.png' -]; - -let str: string | undefined; -pLocate(files, file => Promise.resolve(file === 'rainbow.png')).then(foundPath => { - str = foundPath; -}); - -pLocate(files, file => Promise.resolve(file === 'rainbow.png'), {concurrency: 2, preserveOrder: false}); diff --git a/types/p-locate/tsconfig.json b/types/p-locate/tsconfig.json deleted file mode 100644 index 1f3e8a7711..0000000000 --- a/types/p-locate/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-locate-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-locate/tslint.json b/types/p-locate/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-locate/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-log/index.d.ts b/types/p-log/index.d.ts deleted file mode 100644 index 66fe1ceace..0000000000 --- a/types/p-log/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for p-log 1.0 -// Project: https://github.com/sindresorhus/p-log#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pLog; - -declare const pLog: pLog; - -interface pLog { - (): (value: T) => Promise; - catch(): (value: any) => Promise; -} diff --git a/types/p-log/p-log-tests.ts b/types/p-log/p-log-tests.ts deleted file mode 100644 index 58e9aa17d7..0000000000 --- a/types/p-log/p-log-tests.ts +++ /dev/null @@ -1,15 +0,0 @@ -import pLog = require('p-log'); - -Promise.resolve('unicorn') - .then(pLog()) - .then(val => { - val; // $ExpectType string - }); - -Promise.resolve() - .then(() => { - throw new Error('pony'); - }) - .catch(pLog.catch()) - .catch(error => { - }); diff --git a/types/p-log/tsconfig.json b/types/p-log/tsconfig.json deleted file mode 100644 index 891d94fce3..0000000000 --- a/types/p-log/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-log-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-log/tslint.json b/types/p-log/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-log/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-map-series/index.d.ts b/types/p-map-series/index.d.ts deleted file mode 100644 index d7767278f5..0000000000 --- a/types/p-map-series/index.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for p-map-series 1.0 -// Project: https://github.com/sindresorhus/p-map-series#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = pMapSeries; - -declare function pMapSeries(input: Iterable | T>, mapper: (element: T, index: number) => PromiseLike | U): Promise; diff --git a/types/p-map-series/p-map-series-tests.ts b/types/p-map-series/p-map-series-tests.ts deleted file mode 100644 index c9c2831b0f..0000000000 --- a/types/p-map-series/p-map-series-tests.ts +++ /dev/null @@ -1,19 +0,0 @@ -import pMapSeries = require('p-map-series'); - -const keywords = [ - Promise.resolve('foo'), - 'rainbow', - 'pony' -]; - -const keywordSet = new Set(keywords); - -pMapSeries(keywords, (keyword, idx) => Promise.resolve({keyword, idx})).then(result => { - result; // $ExpectType { keyword: string; idx: number; }[] - const res1: { keyword: string; idx: number; } = result[0]; -}); - -pMapSeries(keywordSet, (keyword) => Promise.resolve({keyword})).then(result => { - result; // $ExpectType { keyword: string; }[] - const res1: { keyword: string; } = result[0]; -}); diff --git a/types/p-map-series/tsconfig.json b/types/p-map-series/tsconfig.json deleted file mode 100644 index b06e222983..0000000000 --- a/types/p-map-series/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-map-series-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-map-series/tslint.json b/types/p-map-series/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-map-series/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-memoize/index.d.ts b/types/p-memoize/index.d.ts deleted file mode 100644 index 0b997b4b19..0000000000 --- a/types/p-memoize/index.d.ts +++ /dev/null @@ -1,56 +0,0 @@ -// Type definitions for p-memoize 1.0 -// Project: https://github.com/sindresorhus/p-memoize#readme -// Definitions by: forabi -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -interface MemOptions { - /** - * Milliseconds until the cache expires. - * @default Infinity - */ - maxAge?: number; - - /** - * Determines the cache key for storing the result based on the - * function arguments. By default, if there's only one argument and - * it's a primitive, it's used directly as a key, otherwise it's all - * the function arguments JSON stringified as an array. - * - * You could for example change it to only cache on the first argument - * `x => JSON.stringify(x)`. - */ - cacheKey?: (...args: any[]) => string; - - /** - * Use a different cache storage. - * Must implement the following methods: - * `.has(key)`, `.get(key)`, `.set(key, value)`, `.delete(key)`, and optionally `.clear()` - * You could for example use a `WeakMap` instead or `quick-lru` for a LRU cache. - * - * @default new Map() - */ - cache?: pMemoize.Cache; - - /** Cache rejected promises. */ - cachePromiseRejection?: boolean; -} - -type PMemoize = any>( - f: T, - memoizeOptions?: MemOptions -) => T; - -declare const pMemoize: PMemoize; - -declare namespace pMemoize { - interface Cache { - get(key: K): V; - set(key: K, value: V): void; - has(key: K): boolean; - delete(key: K): void; - clear?(): void; - } -} - -export = pMemoize; diff --git a/types/p-memoize/p-memoize-tests.ts b/types/p-memoize/p-memoize-tests.ts deleted file mode 100644 index 8626482dab..0000000000 --- a/types/p-memoize/p-memoize-tests.ts +++ /dev/null @@ -1,13 +0,0 @@ -import pMemoize = require('p-memoize'); -import { Cache } from 'p-memoize'; - -const a = pMemoize(async () => Promise.resolve('Hello world!')); - -const b = pMemoize(async () => Promise.resolve(1), { - maxAge: 1000, - cache: new Map() -}); - -a(); - -b(); diff --git a/types/p-memoize/tslint.json b/types/p-memoize/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-memoize/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-one/index.d.ts b/types/p-one/index.d.ts deleted file mode 100644 index 14408b4cd7..0000000000 --- a/types/p-one/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for p-one 1.0 -// Project: https://github.com/kevva/p-one#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pOne; - -declare function pOne(input: Iterable | T>, - testFn: (element: T, index: number) => boolean | Promise, - options?: pOne.Options): Promise; - -declare namespace pOne { - interface Options { - concurrency?: number; - } -} diff --git a/types/p-one/p-one-tests.ts b/types/p-one/p-one-tests.ts deleted file mode 100644 index 99c2536dec..0000000000 --- a/types/p-one/p-one-tests.ts +++ /dev/null @@ -1,26 +0,0 @@ -import pOne = require('p-one'); - -const places = [ - Promise.resolve('Norway'), - 'Bangkok, Thailand', - 'Berlin, Germany', - 'Tokyo, Japan' -]; - -pOne(places, x => Promise.resolve(true)).then(result => { - const bool: boolean = result; -}); - -const places2 = [ - Promise.resolve('Norway'), - 'Bangkok, Thailand', - 'Berlin, Germany', - 5 -]; - -pOne(places2, x => { - const strnum: string | number = x; - return Promise.resolve(true); -}, {concurrency: 2}).then(result => { - const bool: boolean = result; -}); diff --git a/types/p-one/tsconfig.json b/types/p-one/tsconfig.json deleted file mode 100644 index 27a6a05ac7..0000000000 --- a/types/p-one/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-one-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-one/tslint.json b/types/p-one/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-one/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-progress/index.d.ts b/types/p-progress/index.d.ts deleted file mode 100644 index 8eb745683c..0000000000 --- a/types/p-progress/index.d.ts +++ /dev/null @@ -1,175 +0,0 @@ -// Type definitions for p-progress 0.2 -// Project: https://github.com/sindresorhus/p-progress#readme -// Definitions by: icopp -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -declare namespace pProgress { - interface Options { - /** - * Number of concurrently pending promises. - * - * To run the promises in series, set it to 1. - * - * When this option is set, the first argument must be an array of - * promise-returning functions. - * - * Minimum 1. - * - * @default {Infinity} - */ - concurrency?: number; - } -} - -type PromiseFactory = () => Promise | PromiseLike; - -declare class PProgress extends Promise { - /** - * The current progress percentage of the promise as a number between 0 and - * 1. - */ - progress: number; - - /** - * Convenience method to run multiple promises and get a total progress of - * all of them. It counts normal promises with progress `0` when pending and - * progress `1` when resolved. For PProgress type promises, it listens to - * their onProgress() method for more fine grained progress reporting. You - * can mix and match normal promises and PProgress promises. - * - * @param promises Array of promises or promise-returning functions. - * @throws {TypeError} - */ - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5, T6, T7, T8]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5, T6, T7]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5, T6]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4, T5]>; - static all( - promises: [ - PromiseFactory, - PromiseFactory, - PromiseFactory, - PromiseFactory - ], - options?: pProgress.Options - ): PProgress<[T1, T2, T3, T4]>; - static all( - promises: [PromiseFactory, PromiseFactory, PromiseFactory], - options?: pProgress.Options - ): PProgress<[T1, T2, T3]>; - static all( - promises: [PromiseFactory, PromiseFactory], - options?: pProgress.Options - ): PProgress<[T1, T2]>; - static all( - promises: [PromiseFactory], - options?: pProgress.Options - ): PProgress<[T1]>; - static all( - promises: Array>, - options?: pProgress.Options - ): PProgress; - - /** - * Same as the Promise constructor, but with an appended `progress` - * parameter in `executor`. - * - * @param progress - * Call this with progress updates. It expects a number between 0 and 1. - * - * Multiple calls with the same number will result in only one - * `onProgress()` event. - * - * Progress percentage `1` is reported for you when the promise resolves. - * If you set it yourself, it will simply be ignored. - */ - constructor( - executor: ( - resolve: (value?: T | PromiseLike) => void, - reject: (reason?: any) => void, - progress: (progress: number) => void - ) => void - ); - - /** - * Accepts a function that gets `instance.progress` as an argument and is - * called for every progress event. - * - * @throws {TypeError} - */ - onProgress(cb: (progress: number) => void): void; -} - -export = PProgress; diff --git a/types/p-progress/p-progress-tests.ts b/types/p-progress/p-progress-tests.ts deleted file mode 100644 index eb70dec355..0000000000 --- a/types/p-progress/p-progress-tests.ts +++ /dev/null @@ -1,31 +0,0 @@ -import PProgress = require("p-progress"); - -new PProgress(async (resolve, reject, progress) => { - try { - await Promise.resolve("sindresorhus.com"); - progress(0.5); - - await Promise.resolve("ava.li"); - progress(1); - - resolve(); - } catch (e) { - reject(e); - } -}).onProgress(progress => { - progress; -}); - -PProgress.all( - [ - () => Promise.resolve("sindresorhus.com"), - () => Promise.resolve("ava.li"), - () => Promise.resolve(), - () => Promise.resolve(1) - ], - { concurrency: 2 } -).then(result => { - const str: string = result[0]; - const str2: string = result[1]; - const num: number = result[3]; -}); diff --git a/types/p-progress/tslint.json b/types/p-progress/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-progress/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-props/index.d.ts b/types/p-props/index.d.ts deleted file mode 100644 index 3fa293ef69..0000000000 --- a/types/p-props/index.d.ts +++ /dev/null @@ -1,10 +0,0 @@ -// Type definitions for p-props 1.0 -// Project: https://github.com/sindresorhus/p-props#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = pProps; - -declare function pProps | V }>(input: M): Promise>; -declare function pProps(input: Map | V>): Promise>; diff --git a/types/p-props/p-props-tests.ts b/types/p-props/p-props-tests.ts deleted file mode 100644 index 651d613193..0000000000 --- a/types/p-props/p-props-tests.ts +++ /dev/null @@ -1,21 +0,0 @@ -import pProps = require('p-props'); -import got = require('got'); - -const fetch = (url: string): Promise => got(url).then(res => res.body); - -const sites = { - ava: fetch('ava.li'), - todomvc: fetch('todomvc.com'), - github: fetch('github.com'), - foo: 'bar' -}; - -pProps(sites).then(result => { - const str: string = result.github; -}); - -const map = new Map>([[1, Promise.resolve('1')], [2, '2']]); - -pProps(map).then(result => { - const str: string | undefined = result.get(1); -}); diff --git a/types/p-props/tsconfig.json b/types/p-props/tsconfig.json deleted file mode 100644 index 8ef73ae141..0000000000 --- a/types/p-props/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-props-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-props/tslint.json b/types/p-props/tslint.json deleted file mode 100644 index 71ee04c4e1..0000000000 --- a/types/p-props/tslint.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "extends": "dtslint/dt.json", - "rules": { - "no-unnecessary-generics": false - } -} diff --git a/types/p-reduce/index.d.ts b/types/p-reduce/index.d.ts deleted file mode 100644 index 6434eda06a..0000000000 --- a/types/p-reduce/index.d.ts +++ /dev/null @@ -1,11 +0,0 @@ -// Type definitions for p-reduce 1.0 -// Project: https://github.com/sindresorhus/p-reduce#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = pReduce; - -declare function pReduce(input: Iterable | T>, - reducer: (previousValue: U, currentValue: T, index: number) => Promise | U, - initialValue?: U): Promise; diff --git a/types/p-reduce/p-reduce-tests.ts b/types/p-reduce/p-reduce-tests.ts deleted file mode 100644 index 113b6040fc..0000000000 --- a/types/p-reduce/p-reduce-tests.ts +++ /dev/null @@ -1,27 +0,0 @@ -import pReduce = require('p-reduce'); - -const names = [ - Promise.resolve('sindresorhus'), - 'Addy Osmani', - 'Pascal Hartig', - 'Stephen Sawchuk' -]; - -pReduce(names, (total, name) => { - return Promise.resolve(total + 1); -}, 0).then(count => { - const num: number = count; -}); - -const names2 = [ - Promise.resolve('sindresorhus'), - 'Addy Osmani', - 'Pascal Hartig', - 5 -]; - -pReduce(names2, (allNames, name) => { - return Promise.resolve(`${allNames},${name}`); -}, '').then(allNames => { - const str: string = allNames; -}); diff --git a/types/p-reduce/tsconfig.json b/types/p-reduce/tsconfig.json deleted file mode 100644 index d06d04e5e7..0000000000 --- a/types/p-reduce/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-reduce-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-reduce/tslint.json b/types/p-reduce/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-reduce/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-retry/index.d.ts b/types/p-retry/index.d.ts deleted file mode 100644 index b2c9100b68..0000000000 --- a/types/p-retry/index.d.ts +++ /dev/null @@ -1,28 +0,0 @@ -// Type definitions for p-retry 3.0 -// Project: https://github.com/sindresorhus/p-retry#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -import { OperationOptions } from 'retry'; - -export = pRetry; - -declare function pRetry(input: (attemptCount: number) => PromiseLike | T, options?: pRetry.Options): Promise; - -declare namespace pRetry { - class AbortError extends Error { - readonly name: 'AbortError'; - readonly originalError: Error; - constructor(message: string | Error); - } - - interface FailedAttemptError extends Error { - attemptNumber: number; - retriesLeft: number; - } - - interface Options extends OperationOptions { - onFailedAttempt?: (error: FailedAttemptError) => void; - } -} diff --git a/types/p-retry/p-retry-tests.ts b/types/p-retry/p-retry-tests.ts deleted file mode 100644 index 19d3fbbfef..0000000000 --- a/types/p-retry/p-retry-tests.ts +++ /dev/null @@ -1,20 +0,0 @@ -import pRetry = require('p-retry'); -import fetch from 'node-fetch'; - -const run = () => fetch('https://sindresorhus.com/unicorn') - .then(response => { - // abort retrying if the resource doesn't exist - if (response.status === 404) { - throw new pRetry.AbortError(response.statusText); - } - return response.text(); - }); - -pRetry(run, { - retries: 5, - onFailedAttempt: error => { - console.log(`Attempt ${error.attemptNumber} failed. There are ${error.retriesLeft} attempts left.`); - } -}).then(result => { - const str: string = result; -}); diff --git a/types/p-retry/tsconfig.json b/types/p-retry/tsconfig.json deleted file mode 100644 index 8bd6ddd6b5..0000000000 --- a/types/p-retry/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-retry-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-retry/tslint.json b/types/p-retry/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-retry/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-series/index.d.ts b/types/p-series/index.d.ts deleted file mode 100644 index ecc7b19cd8..0000000000 --- a/types/p-series/index.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -// Type definitions for p-series 1.0 -// Project: https://github.com/sindresorhus/p-series#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.3 - -export = pSeries; - -declare function pSeries(tasks: Iterable<() => Promise | T>): Promise; diff --git a/types/p-series/p-series-tests.ts b/types/p-series/p-series-tests.ts deleted file mode 100644 index 1b97ca3a48..0000000000 --- a/types/p-series/p-series-tests.ts +++ /dev/null @@ -1,18 +0,0 @@ -import pSeries = require('p-series'); -import got = require('got'); - -pSeries | number | boolean>([ - () => got('sindresorhus.com'), - () => Promise.resolve(1), - () => true -]).then(result => { - result[0]; // $ExpectType number | boolean | Response -}); - -pSeries | number | boolean>(new Set<(() => Promise>) | (() => Promise) | (() => Promise)>([ - () => got('sindresorhus.com'), - () => Promise.resolve(1), - () => Promise.resolve(true) -])).then(result => { - result[0]; // $ExpectType number | boolean | Response -}); diff --git a/types/p-series/tsconfig.json b/types/p-series/tsconfig.json deleted file mode 100644 index 7ac0ed4d4c..0000000000 --- a/types/p-series/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-series-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-series/tslint.json b/types/p-series/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-series/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-tap/index.d.ts b/types/p-tap/index.d.ts deleted file mode 100644 index 38996963fc..0000000000 --- a/types/p-tap/index.d.ts +++ /dev/null @@ -1,13 +0,0 @@ -// Type definitions for p-tap 1.0 -// Project: https://github.com/sindresorhus/p-tap#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pTap; - -declare const pTap: pTap; - -interface pTap { - (fn: (value: T) => any): (value: T) => Promise; - catch(fn: (value: any) => any): (value: any) => Promise; -} diff --git a/types/p-tap/p-tap-tests.ts b/types/p-tap/p-tap-tests.ts deleted file mode 100644 index c0db33e3cc..0000000000 --- a/types/p-tap/p-tap-tests.ts +++ /dev/null @@ -1,26 +0,0 @@ -import pTap = require('p-tap'); - -Promise.resolve('unicorn') - .then(pTap(val => { - const str: string = val; - return 1; - })) - .then(val => { - const str: string = val; - }); - -Promise.resolve('unicorn') - .then(pTap(val => { - const str: string = val; - return Promise.resolve(1); - })) - .then(val => { - const str: string = val; - }); - -Promise.reject(new Error()) - .catch(pTap.catch(val => { - const num: number = val; - })) - .then(() => 1) - .catch(() => {}); diff --git a/types/p-tap/tsconfig.json b/types/p-tap/tsconfig.json deleted file mode 100644 index 1d4042647f..0000000000 --- a/types/p-tap/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-tap-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-tap/tslint.json b/types/p-tap/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-tap/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/p-timeout/index.d.ts b/types/p-timeout/index.d.ts deleted file mode 100644 index 40e1dc6410..0000000000 --- a/types/p-timeout/index.d.ts +++ /dev/null @@ -1,16 +0,0 @@ -// Type definitions for p-timeout 1.2 -// Project: https://github.com/sindresorhus/p-timeout#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pTimeout; - -declare function pTimeout(input: PromiseLike, ms: number, message?: string | pTimeout.TimeoutError): Promise; -declare function pTimeout(input: PromiseLike, ms: number, fallback: () => R | Promise): Promise; - -declare namespace pTimeout { - class TimeoutError extends Error { - readonly name: 'TimeoutError'; - constructor(message?: string); - } -} diff --git a/types/p-timeout/p-timeout-tests.ts b/types/p-timeout/p-timeout-tests.ts deleted file mode 100644 index 455ed2204f..0000000000 --- a/types/p-timeout/p-timeout-tests.ts +++ /dev/null @@ -1,29 +0,0 @@ -/// - -import pTimeout = require('p-timeout'); - -const delayedPromise: () => Promise = () => new Promise(resolve => setTimeout(() => resolve('foo'), 200)); - -let str: string; -let num: number; -pTimeout(delayedPromise(), 50).then(() => 'foo'); -pTimeout(delayedPromise(), 50, () => { - return pTimeout(delayedPromise(), 300); -}); -pTimeout(delayedPromise(), 50).then(res => str = res); -pTimeout(delayedPromise(), 50, 'error').then(res => str = res); -pTimeout(delayedPromise(), 50, new pTimeout.TimeoutError('error')).then(res => str = res); -pTimeout(delayedPromise(), 50, () => Promise.resolve(10)).then(res => { - if (typeof res === 'string') { - str = res; - } else { - num = res; - } -}); -pTimeout(delayedPromise(), 50, () => 10).then(res => { - if (typeof res === 'string') { - str = res; - } else { - num = res; - } -}); diff --git a/types/p-timeout/tsconfig.json b/types/p-timeout/tsconfig.json deleted file mode 100644 index d16042504a..0000000000 --- a/types/p-timeout/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "p-timeout-tests.ts" - ] -} \ No newline at end of file diff --git a/types/p-timeout/tslint.json b/types/p-timeout/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/p-timeout/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/package-json/index.d.ts b/types/package-json/index.d.ts deleted file mode 100644 index 9089b19d0a..0000000000 --- a/types/package-json/index.d.ts +++ /dev/null @@ -1,77 +0,0 @@ -// Type definitions for package-json 5.0 -// Project: https://github.com/sindresorhus/package-json#readme -// Definitions by: Jinwoo Lee -// BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = packageJson; - -/** - * Get metadata of a package from the npm registry. - * - * @param name Name of the package. - */ -declare function packageJson( - name: string, - options?: packageJson.Options -): Promise; - -declare namespace packageJson { - interface Options { - /** - * Package version such as `1.0.0` or a [dist tag](https://docs.npmjs.com/cli/dist-tag) such as `latest`. - * - * The version can also be in any format supported by the [semver](https://github.com/npm/node-semver) module. - * For example: - * - `1` - Get the latest `1.x.x` - * - `1.2` - Get the latest `1.2.x` - * - `^1.2.3` - Get the latest `1.x.x` but at least `1.2.3` - * - `~1.2.3` - Get the latest `1.2.x` but at least `1.2.3` - * - * @default 'latest' - */ - version?: string; - /** - * By default, only an abbreviated metadata object is returned for performance reasons. - * [Read more.](https://github.com/npm/registry/blob/master/docs/responses/package-metadata.md) - * @default false - */ - fullMetadata?: boolean; - /** - * Return the [main entry](https://registry.npmjs.org/ava) containing all versions. - * @default false - */ - allVersions?: boolean; - } - - interface PackageJson { - [k: string]: any; - name?: string; - version?: string; - files?: string[]; - bin?: { [k: string]: string }; - man?: string[]; - keywords?: string[]; - author?: Person; - maintainers?: Person[]; - contributors?: Person[]; - bundleDependencies?: { [name: string]: string }; - dependencies?: { [name: string]: string }; - devDependencies?: { [name: string]: string }; - optionalDependencies?: { [name: string]: string }; - description?: string; - engines?: { [type: string]: string }; - license?: string; - repository?: { type: string; url: string }; - bugs?: { url: string; email?: string } | { url?: string; email: string }; - homepage?: string; - scripts?: { [k: string]: string }; - readme?: string; - } - - interface Person { - name?: string; - email?: string; - url?: string; - } -} diff --git a/types/package-json/package-json-tests.ts b/types/package-json/package-json-tests.ts deleted file mode 100644 index 7255351933..0000000000 --- a/types/package-json/package-json-tests.ts +++ /dev/null @@ -1,6 +0,0 @@ -import packageJson = require('package-json'); - -packageJson('package-json'); // $ExpectType Promise -packageJson('package-json', { version: '1.2.3' }); // $ExpectType Promise -packageJson('package-json', { fullMetadata: true }); // $ExpectType Promise -packageJson('package-json', { allVersions: true }); // $ExpectType Promise diff --git a/types/package-json/tsconfig.json b/types/package-json/tsconfig.json deleted file mode 100644 index 7bca217f58..0000000000 --- a/types/package-json/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "package-json-tests.ts" - ] -} \ No newline at end of file diff --git a/types/package-json/tslint.json b/types/package-json/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/package-json/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/parse/index.d.ts b/types/parse/index.d.ts index 008ce67def..1aa9cb1546 100644 --- a/types/parse/index.d.ts +++ b/types/parse/index.d.ts @@ -9,6 +9,7 @@ // Andrew Goldis // Alexandre Hétu Rivard // Diamond Lewis +// Jong Eun Lee // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.4 @@ -622,6 +623,7 @@ subscription.on('close', () => {}); class User extends Object { static current(): User | undefined; + static currentAsync(): Promise; static signUp(username: string, password: string, attrs: any, options?: SignUpOptions): Promise; static logIn(username: string, password: string, options?: SuccessFailureOptions): Promise; static logOut(): Promise; diff --git a/types/parse/parse-tests.ts b/types/parse/parse-tests.ts index cb80764cd4..1c430b1807 100644 --- a/types/parse/parse-tests.ts +++ b/types/parse/parse-tests.ts @@ -222,6 +222,15 @@ function test_user() { user.signUp(null, { useMasterKey: true }); } +async function test_user_currentAsync() { + const asyncUser = await Parse.User.currentAsync(); + if (asyncUser) { + asyncUser.set('email', 'email@example.com'); + } else if (asyncUser === null) { + Parse.User.logIn('email@example.com', 'my pass'); + } +} + function test_user_acl_roles() { const user = new Parse.User(); diff --git a/types/path-type/index.d.ts b/types/path-type/index.d.ts deleted file mode 100644 index d67856f85e..0000000000 --- a/types/path-type/index.d.ts +++ /dev/null @@ -1,15 +0,0 @@ -// Type definitions for path-type 3.0 -// Project: https://github.com/sindresorhus/path-type#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export const file: PathTypeFn; -export const dir: PathTypeFn; -export const symlink: PathTypeFn; - -export const fileSync: PathTypeSyncFn; -export const dirSync: PathTypeSyncFn; -export const symlinkSync: PathTypeSyncFn; - -export type PathTypeFn = (path: string) => Promise; -export type PathTypeSyncFn = (path: string) => boolean; diff --git a/types/path-type/path-type-tests.ts b/types/path-type/path-type-tests.ts deleted file mode 100644 index d070731523..0000000000 --- a/types/path-type/path-type-tests.ts +++ /dev/null @@ -1,15 +0,0 @@ -import pathType = require('path-type'); - -// $ExpectType Promise -pathType.file('package.json'); -// $ExpectType Promise -pathType.dir('package.json'); -// $ExpectType Promise -pathType.symlink('package.json'); - -// $ExpectType boolean -pathType.fileSync('package.json'); -// $ExpectType boolean -pathType.dirSync('package.json'); -// $ExpectType boolean -pathType.symlinkSync('package.json'); diff --git a/types/path-type/tsconfig.json b/types/path-type/tsconfig.json deleted file mode 100644 index f2c7533a5d..0000000000 --- a/types/path-type/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "compilerOptions": { - "module": "commonjs", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictNullChecks": true, - "strictFunctionTypes": true, - "baseUrl": "../", - "typeRoots": [ - "../" - ], - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "path-type-tests.ts" - ] -} diff --git a/types/path-type/tslint.json b/types/path-type/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/path-type/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/pkg-dir/index.d.ts b/types/pkg-dir/index.d.ts deleted file mode 100644 index 7d8b714f0b..0000000000 --- a/types/pkg-dir/index.d.ts +++ /dev/null @@ -1,12 +0,0 @@ -// Type definitions for pkg-dir 2.0 -// Project: https://github.com/sindresorhus/pkg-dir#readme -// Definitions by: NK-WEB-Git -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pkgDir; - -declare function pkgDir(cwd?: string): Promise; - -declare namespace pkgDir { - function sync(cwd?: string): string | null; -} diff --git a/types/pkg-dir/pkg-dir-tests.ts b/types/pkg-dir/pkg-dir-tests.ts deleted file mode 100644 index 487310a6a2..0000000000 --- a/types/pkg-dir/pkg-dir-tests.ts +++ /dev/null @@ -1,11 +0,0 @@ -import pkgDir = require('pkg-dir'); - -pkgDir('/Users/project/pkg-dir').then(rootDir => { - rootDir; // $ExpectType string | null -}); - -pkgDir().then(rootDir => { - rootDir; -}); - -pkgDir.sync('/Users/project/pkg-dir'); // $ExpectType string | null diff --git a/types/pkg-dir/tsconfig.json b/types/pkg-dir/tsconfig.json deleted file mode 100644 index a5647ed0eb..0000000000 --- a/types/pkg-dir/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "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-dir-tests.ts" - ] -} \ No newline at end of file diff --git a/types/pkg-dir/tslint.json b/types/pkg-dir/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/pkg-dir/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/pkg-versions/index.d.ts b/types/pkg-versions/index.d.ts deleted file mode 100644 index a271a57485..0000000000 --- a/types/pkg-versions/index.d.ts +++ /dev/null @@ -1,8 +0,0 @@ -// Type definitions for pkg-versions 1.1 -// Project: https://github.com/sindresorhus/pkg-versions#readme -// Definitions by: BendingBender -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped - -export = pkgVersions; - -declare function pkgVersions(name: string): Promise>; diff --git a/types/pkg-versions/pkg-versions-tests.ts b/types/pkg-versions/pkg-versions-tests.ts deleted file mode 100644 index f0b963b998..0000000000 --- a/types/pkg-versions/pkg-versions-tests.ts +++ /dev/null @@ -1,3 +0,0 @@ -import pkgVersions = require('pkg-versions'); - -pkgVersions('ava'); // $ExpectType Promise> diff --git a/types/pkg-versions/tsconfig.json b/types/pkg-versions/tsconfig.json deleted file mode 100644 index cc9bffbcd4..0000000000 --- a/types/pkg-versions/tsconfig.json +++ /dev/null @@ -1,23 +0,0 @@ -{ - "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-versions-tests.ts" - ] -} diff --git a/types/pkg-versions/tslint.json b/types/pkg-versions/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/pkg-versions/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/qrcode/index.d.ts b/types/qrcode/index.d.ts index 54d53e7b1c..817943693d 100644 --- a/types/qrcode/index.d.ts +++ b/types/qrcode/index.d.ts @@ -102,7 +102,7 @@ export interface QRCodeRenderersOptions extends QRCodeOptions { export interface QRCodeSegment { data: string; - mode: 'alphanumeric' | 'numeric'; + mode: 'alphanumeric' | 'numeric' | 'kanji' | 'byte'; } export interface QRCode { diff --git a/types/qrcode/qrcode-tests.ts b/types/qrcode/qrcode-tests.ts index 363367cc28..01dc9ca194 100644 --- a/types/qrcode/qrcode-tests.ts +++ b/types/qrcode/qrcode-tests.ts @@ -21,7 +21,9 @@ QRCode.toDataURL('some text', { version: 2 }, (err, url) => { QRCode.toDataURL([ { data: 'ABCDEFG', mode: 'alphanumeric' }, - { data: '0123456', mode: 'numeric' } + { data: '0123456', mode: 'numeric' }, + { data: '\x87\x90', mode: 'kanji' }, + { data: 'abc\ndef?', mode: 'byte' } ], (err, url) => { console.log(url); }); diff --git a/types/react-big-calendar/index.d.ts b/types/react-big-calendar/index.d.ts index 465c0a722c..0298b276e8 100644 --- a/types/react-big-calendar/index.d.ts +++ b/types/react-big-calendar/index.d.ts @@ -7,6 +7,7 @@ // Paul Potsides // janb87 // Daniel Thorne +// Panagiotis Rikarnto Siavelis // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Validator } from 'prop-types'; @@ -204,6 +205,7 @@ export interface Messages { today?: string; agenda?: string; showMore?: (count: number) => string; + noEventsInRange?: string; } export type Culture = string | string[]; diff --git a/types/react-big-calendar/react-big-calendar-tests.tsx b/types/react-big-calendar/react-big-calendar-tests.tsx index bfcd9d3f0e..02652609b1 100644 --- a/types/react-big-calendar/react-big-calendar-tests.tsx +++ b/types/react-big-calendar/react-big-calendar-tests.tsx @@ -131,7 +131,24 @@ class CalendarResource { agendaDateFormat: (date: Date, culture?: string, localizer?: object) => "some-format", dayRangeHeaderFormat: (range: DateRange, culture?: string, localizer?: object) => "some-format" }} - messages={{}} + messages={{ + date: 'Date', + time: 'Time', + event: 'Event', + allDay: 'All Day', + week: 'Week', + work_week: 'Work Week', + day: 'Day', + month: 'Month', + previous: 'Back', + next: 'Next', + yesterday: 'Yesterday', + tomorrow: 'Tomorrow', + today: 'Today', + agenda: 'Agenda', + noEventsInRange: 'There are no events in this range.', + showMore: total => `+${total} more`, + }} timeslots={24} defaultView={'month'} className={'my-calendar'} diff --git a/types/react-datepicker/index.d.ts b/types/react-datepicker/index.d.ts index c957411347..522f1faaf9 100644 --- a/types/react-datepicker/index.d.ts +++ b/types/react-datepicker/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for react-datepicker 2.0 +// Type definitions for react-datepicker 2.2 // Project: https://github.com/Hacker0x01/react-datepicker // Definitions by: Rajab Shakirov , // Andrey Balokha , @@ -10,6 +10,7 @@ // Justin Grant // Jake Boone // Roman Nuritdinov +// Avi Klaiman // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 @@ -127,6 +128,10 @@ export interface ReactDatePickerProps { weekLabel?: string; withPortal?: boolean; yearDropdownItemNumber?: number; + timeInputLabel?: string; + inlineFocusSelectedMonth?: boolean; + onDayMouseEnter?: (date: Date) => void; + onMonthMouseLeave?: () => void; } declare class ReactDatePicker extends React.Component { diff --git a/types/react-datepicker/react-datepicker-tests.tsx b/types/react-datepicker/react-datepicker-tests.tsx index 1188f53763..d7ea788bc7 100644 --- a/types/react-datepicker/react-datepicker-tests.tsx +++ b/types/react-datepicker/react-datepicker-tests.tsx @@ -116,6 +116,10 @@ const defaultLocale = getDefaultLocale(); weekLabel="" withPortal yearDropdownItemNumber={1} + timeInputLabel="" + inlineFocusSelectedMonth={false} + onDayMouseEnter={(date: Date) => {}} + onMonthMouseLeave={() => {}} >
diff --git a/types/react-highcharts/index.d.ts b/types/react-highcharts/index.d.ts index 26a74e28a9..b8f47af4fb 100644 --- a/types/react-highcharts/index.d.ts +++ b/types/react-highcharts/index.d.ts @@ -20,6 +20,11 @@ interface ReactHighchartsProps { * @param after-render callback. */ callback?(chart: Highcharts.ChartObject): void; + + /** + * Chart will not rerender if the config is referentially equal to previous and this property is true + */ + isPureConfig?: boolean; } /** diff --git a/types/react-highcharts/react-highcharts-tests.tsx b/types/react-highcharts/react-highcharts-tests.tsx index 7c0841e566..f3e31bd534 100644 --- a/types/react-highcharts/react-highcharts-tests.tsx +++ b/types/react-highcharts/react-highcharts-tests.tsx @@ -6,9 +6,12 @@ const config: Highcharts.Options = {}; function callback(chart: Highcharts.ChartObject): void {} +const isPureConfig = true; + export const _ = () => ( <> + ); diff --git a/types/react-medium-image-zoom/index.d.ts b/types/react-medium-image-zoom/index.d.ts new file mode 100644 index 0000000000..b3e9fcf14e --- /dev/null +++ b/types/react-medium-image-zoom/index.d.ts @@ -0,0 +1,43 @@ +// Type definitions for react-medium-image-zoom 3.0 +// Project: https://github.com/rpearce/react-medium-image-zoom#readme +// Definitions by: James Bellamy +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 3.3 + +import * as React from "react"; + +export interface ImageZoom_Image { + src: string; + alt?: string; + className?: string; + style?: object; +} + +export interface ImageZoom_ZoomImage { + src?: string; + alt?: string; + className?: string; + style?: object; +} + +export interface ImageZoomDefaultStyles { + zoomContainer?: object; + overlay?: object; + image?: object; + zoomImage?: object; +} + +export interface ImageZoomProps { + image: ImageZoom_Image; + zoomImage?: ImageZoom_ZoomImage; + zoomMargin?: number; + isZoomed?: boolean; + shouldHandleZoom?: () => boolean; + shouldReplaceImage?: boolean; + shouldRespectMaxDimension?: boolean; + defaultStyles?: ImageZoomDefaultStyles; + onZoom?: () => object; + onUnzoom?: () => object; +} + +export default class ImageZoom extends React.Component {} diff --git a/types/react-medium-image-zoom/react-medium-image-zoom-tests.tsx b/types/react-medium-image-zoom/react-medium-image-zoom-tests.tsx new file mode 100644 index 0000000000..45d3ef1138 --- /dev/null +++ b/types/react-medium-image-zoom/react-medium-image-zoom-tests.tsx @@ -0,0 +1,23 @@ +import * as React from "react"; +import ImageZoom from "react-medium-image-zoom"; + +const component: React.FC = () => { + return ( +
+ +
+ ); +}; + +export default component; diff --git a/types/element-ready/tsconfig.json b/types/react-medium-image-zoom/tsconfig.json similarity index 87% rename from types/element-ready/tsconfig.json rename to types/react-medium-image-zoom/tsconfig.json index e5067c7ccf..4b1dd42ee0 100644 --- a/types/element-ready/tsconfig.json +++ b/types/react-medium-image-zoom/tsconfig.json @@ -10,6 +10,7 @@ "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], @@ -19,6 +20,6 @@ }, "files": [ "index.d.ts", - "element-ready-tests.ts" + "react-medium-image-zoom-tests.tsx" ] -} \ No newline at end of file +} diff --git a/types/filenamify-url/tslint.json b/types/react-medium-image-zoom/tslint.json similarity index 100% rename from types/filenamify-url/tslint.json rename to types/react-medium-image-zoom/tslint.json diff --git a/types/react-native/index.d.ts b/types/react-native/index.d.ts index 2316ee63c9..1c6d6437d9 100644 --- a/types/react-native/index.d.ts +++ b/types/react-native/index.d.ts @@ -1143,6 +1143,11 @@ export interface TextInputAndroidProps { * The color of the textInput underline. */ underlineColorAndroid?: string; + + /** + * Vertically align text when `multiline` is set to true + */ + textAlignVertical?: "auto" | "top" | "bottom" | "center"; } export type KeyboardType = "default" | "email-address" | "numeric" | "phone-pad"; diff --git a/types/react-native/test/index.tsx b/types/react-native/test/index.tsx index 74f8b6a9b5..49e1bab1ac 100644 --- a/types/react-native/test/index.tsx +++ b/types/react-native/test/index.tsx @@ -648,7 +648,7 @@ class TextInputTest extends React.Component<{}, { username: string }> { - + ); } diff --git a/types/react-redux/index.d.ts b/types/react-redux/index.d.ts index 3ef1005cd8..f97fd11b9d 100644 --- a/types/react-redux/index.d.ts +++ b/types/react-redux/index.d.ts @@ -43,7 +43,7 @@ import { Store } from 'redux'; -import { NonReactStatics } from 'hoist-non-react-statics'; +import hoistNonReactStatics = require('hoist-non-react-statics'); // Omit taken from https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-8.html export type Omit = Pick>; @@ -100,7 +100,7 @@ export type GetProps = C extends ComponentType ? P : never; export type ConnectedComponentClass< C extends ComponentType, P -> = ComponentClass> & NonReactStatics & { +> = ComponentClass> & hoistNonReactStatics.NonReactStatics & { WrappedComponent: C; }; diff --git a/types/react-sortable-tree/package.json b/types/react-sortable-tree/package.json index 2e009d2f82..41eb88b180 100644 --- a/types/react-sortable-tree/package.json +++ b/types/react-sortable-tree/package.json @@ -1,6 +1,6 @@ { "private": true, "dependencies": { - "react-dnd": "^5.0.0" + "react-dnd": "5 || 6 || 7" } } diff --git a/types/react-text-truncate/index.d.ts b/types/react-text-truncate/index.d.ts new file mode 100644 index 0000000000..21b4c537a1 --- /dev/null +++ b/types/react-text-truncate/index.d.ts @@ -0,0 +1,25 @@ +// Type definitions for react-text-truncate 0.14 +// Project: https://github.com/ShinyChang/react-text-truncate +// Definitions by: Adrien Antoine +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +import * as React from 'react'; + +export interface TextTruncateProps { + containerClassName?: string; + element?: string; + line?: number | boolean; + onCalculated?: () => void; + onTruncated?: () => void; + onToggled?: (truncated: boolean) => void; + text?: string; + textElement?: React.ReactNode; + textTruncateChild?: React.ReactNode; + truncateText?: string; + maxCalculateTimes?: number; +} + +declare class TextTruncate extends React.Component {} + +export default TextTruncate; diff --git a/types/react-text-truncate/react-text-truncate-tests.tsx b/types/react-text-truncate/react-text-truncate-tests.tsx new file mode 100644 index 0000000000..b5c77ee28f --- /dev/null +++ b/types/react-text-truncate/react-text-truncate-tests.tsx @@ -0,0 +1,18 @@ +import * as React from 'react'; +import TextTruncate from 'react-text-truncate'; + +const TruncatedText = () => ( + {}} + onTruncated={() => {}} + onToggled={(truncate: boolean) => {}} + textElement={
} + textTruncateChild={
} + truncateText="..." + maxCalculateTimes={5} + /> +); diff --git a/types/dom-loaded/tsconfig.json b/types/react-text-truncate/tsconfig.json similarity index 88% rename from types/dom-loaded/tsconfig.json rename to types/react-text-truncate/tsconfig.json index 7d17914d86..9dd3530bc3 100644 --- a/types/dom-loaded/tsconfig.json +++ b/types/react-text-truncate/tsconfig.json @@ -10,6 +10,7 @@ "strictNullChecks": true, "strictFunctionTypes": true, "baseUrl": "../", + "jsx": "react", "typeRoots": [ "../" ], @@ -19,6 +20,6 @@ }, "files": [ "index.d.ts", - "dom-loaded-tests.ts" + "react-text-truncate-tests.tsx" ] } diff --git a/types/fkill/tslint.json b/types/react-text-truncate/tslint.json similarity index 100% rename from types/fkill/tslint.json rename to types/react-text-truncate/tslint.json diff --git a/types/resolve-options/index.d.ts b/types/resolve-options/index.d.ts new file mode 100644 index 0000000000..d2b8610011 --- /dev/null +++ b/types/resolve-options/index.d.ts @@ -0,0 +1,36 @@ +// Type definitions for resolve-options 1.1 +// Project: https://github.com/gulpjs/resolve-options +// Definitions by: Przemysław Struciński +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped +// TypeScript Version: 2.8 + +interface Options { + cwd?: string | ((...args: any[]) => string); + buffer?: boolean | ((...args: any[]) => boolean); + read?: boolean | ((...args: any[]) => boolean); + base?: string | ((...args: any[]) => string); + since?: Date | number | ((...args: any[]) => Date | number); + passthrough?: boolean | ((...args: any[]) => boolean); + allowEmpty?: boolean | ((...args: any[]) => boolean); + mode?: string | number | ((...args: any[]) => string | number); + dirMode?: string | number | ((...args: any[]) => string | number); + overwrite?: boolean | ((...args: any[]) => boolean); + deep?: boolean | ((...args: any[]) => boolean); +} + +interface ConfigItem { + type: string | string[]; + default?: any; +} + +interface Resolver { + resolve: (key: string) => number | string | boolean | Date | undefined | null; +} + +interface Config { + [par: string]: ConfigItem; +} + +declare function createResolver(config: Config, options: Options): Resolver; + +export = createResolver; diff --git a/types/resolve-options/resolve-options-tests.ts b/types/resolve-options/resolve-options-tests.ts new file mode 100644 index 0000000000..86b28241a6 --- /dev/null +++ b/types/resolve-options/resolve-options-tests.ts @@ -0,0 +1,32 @@ +import resolveOptions = require("resolve-options"); + +const config = { + cwd: { + default: "C/test", + type: 'string' + }, + read: { + type: 'boolean' + }, + since: { + type: ['date', 'number'] + }, + sourcemaps: { + default: false, + type: 'boolean' + }, + }; + + const options = { + read() { + return true; + }, + since: Date.now(), + sourcemaps: true, + }; + + const resolver = resolveOptions(config, options); + + const cwd = resolver.resolve('cwd'); + const sourcemaps = resolver.resolve('sourcemaps'); + const read = resolver.resolve('read'); diff --git a/types/filenamify-url/tsconfig.json b/types/resolve-options/tsconfig.json similarity index 92% rename from types/filenamify-url/tsconfig.json rename to types/resolve-options/tsconfig.json index dd7225304e..3d410dd3c4 100644 --- a/types/filenamify-url/tsconfig.json +++ b/types/resolve-options/tsconfig.json @@ -6,8 +6,8 @@ ], "noImplicitAny": true, "noImplicitThis": true, - "strictNullChecks": true, "strictFunctionTypes": true, + "strictNullChecks": true, "baseUrl": "../", "typeRoots": [ "../" @@ -18,6 +18,6 @@ }, "files": [ "index.d.ts", - "filenamify-url-tests.ts" + "resolve-options-tests.ts" ] } diff --git a/types/has-yarn/tslint.json b/types/resolve-options/tslint.json similarity index 100% rename from types/has-yarn/tslint.json rename to types/resolve-options/tslint.json diff --git a/types/serverless/classes/Service.d.ts b/types/serverless/classes/Service.d.ts index 040a45f825..573663603b 100644 --- a/types/serverless/classes/Service.d.ts +++ b/types/serverless/classes/Service.d.ts @@ -12,6 +12,9 @@ declare class Service { provider: { compiledCloudFormationTemplate: { Resources: any[]; + Outputs?: { + [key: string]: any; + }; }; name: string; diff --git a/types/sindresorhus__df/index.d.ts b/types/sindresorhus__df/index.d.ts deleted file mode 100644 index af7a6c8d20..0000000000 --- a/types/sindresorhus__df/index.d.ts +++ /dev/null @@ -1,21 +0,0 @@ -// Type definitions for sindresorhus__df 2.10 -// Project: https://github.com/sindresorhus/df -// Definitions by: Matt Thompson -// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped -// TypeScript Version: 2.1 - -declare function df(): Promise; -declare namespace df { - function fs(filesystem: string): Promise; - function file(file: string): Promise; - interface SpaceInfo { - filesystem: string; - size: number; - used: number; - available: number; - capacity: number; - mountpoint: string; - } -} - -export = df; diff --git a/types/sindresorhus__df/sindresorhus__df-tests.ts b/types/sindresorhus__df/sindresorhus__df-tests.ts deleted file mode 100644 index 970c8b8a1f..0000000000 --- a/types/sindresorhus__df/sindresorhus__df-tests.ts +++ /dev/null @@ -1,37 +0,0 @@ -import df = require('@sindresorhus/df'); - -(async () => { - const disks = await df(); - disks.forEach((disk: df.SpaceInfo) => { - const {filesystem, size, used, available, capacity, mountpoint} = disk; - return { - filesystem, size, used, available, capacity, mountpoint - }; - }); - /* - [{ - filesystem: '/dev/disk1', - size: 499046809600, - used: 443222245376, - available: 55562420224, - capacity: 0.89, - mountpoint: '/' - }, …] - */ - - let {filesystem, size, used, available, capacity, mountpoint} = await df.fs('/dev/disk1'); - /* - { - filesystem: '/dev/disk1', - … - } - */ - - ({filesystem, size, used, available, capacity, mountpoint} = await df.file('./simple.txt')); - /* - { - filesystem: '/dev/disk1', - … - } - */ -})(); diff --git a/types/sindresorhus__df/tslint.json b/types/sindresorhus__df/tslint.json deleted file mode 100644 index 3db14f85ea..0000000000 --- a/types/sindresorhus__df/tslint.json +++ /dev/null @@ -1 +0,0 @@ -{ "extends": "dtslint/dt.json" } diff --git a/types/stripe/index.d.ts b/types/stripe/index.d.ts index 0c35712f71..2a93740f3f 100644 --- a/types/stripe/index.d.ts +++ b/types/stripe/index.d.ts @@ -2284,12 +2284,32 @@ declare namespace Stripe { } interface IInvoiceListOptions extends IListOptions { + /** + * The billing mode of the invoice to retrieve. Either `charge_automatically` or `send_invoice` + */ + billing?: "charge_automatically" | "send_invoice"; + + /** + * A filter on the list based on the object created field. The value can be a string with an integer Unix timestamp, + * or it can be a dictionary with the following options: + */ + created?: IDateFilter; + /** * The identifier of the customer whose invoices to return. If none is provided, all invoices will be returned. */ customer?: string; - date?: IDateFilter; + /** + * A filter on the list based on the object due_date field. The value can be a string with an integer Unix timestamp, + * or it can be a dictionary with the following options: + */ + due_date?: IDateFilter; + + /** + * Only return invoices for the subscription specified by this subscription ID + */ + subscription?: string; } interface IInvoiceLineItemRetrievalOptions extends IListOptions { @@ -3901,6 +3921,17 @@ declare namespace Stripe { * Only return products with the given url */ url?: string; + + /** + * Only return products of this type + */ + type?: string; + + /** + * A filter on the list based on the object created field. The value can be a string with an integer Unix timestamp, + * or it can be a dictionary with the following options: + */ + created?: IDateFilter; } /** @@ -5126,6 +5157,13 @@ declare namespace Stripe { * invoice with payment instructions. */ billing: SubscriptionBilling; + + /** + * ID of the default payment source for the subscription. + * It must belong to the customer associated with the subscription and be in a chargeable state. + * If not set, defaults to the customer’s default source. [Expandable] + */ + default_source: string; } interface ISubscriptionCustCreationOptions extends IDataOptionsWithMetadata { @@ -5787,18 +5825,6 @@ declare namespace Stripe { subscription_item: string; total_usage: number; } - - interface IUsageRecordSummariesListOptions extends IListOptions { - /** - * Only summary items for the given subscription item. - */ - subscription_item: string; - /** - * A limit on the number of objects to be returned. The limit can range between 1 and 100. - * @default 10 - */ - limit?: number; - } } // tslint:disable-next-line:no-unnecessary-class @@ -5819,8 +5845,8 @@ declare namespace Stripe { /** * Creates a usage record for a specified subscription item and date, and fills it with a quantity. */ - list(data: usageRecordSummaries.IUsageRecordSummariesListOptions, options: HeaderOptions, response?: IResponseFn): Promise; - list(data: usageRecordSummaries.IUsageRecordSummariesListOptions, response?: IResponseFn): Promise; + list(subscriptionItem: string, options: IListOptions, response?: IResponseFn): Promise; + list(subscriptionItem: string, response?: IResponseFn): Promise; } class Accounts extends StripeResource { @@ -7145,10 +7171,10 @@ declare namespace Stripe { * @param id The id of the invoice containing the lines to be retrieved * @param data Filtering options */ - retrieveLines(id: string, data: invoices.IInvoiceLineItemRetrievalOptions, options: HeaderOptions, response?: IResponseFn>): Promise; - retrieveLines(id: string, data: invoices.IInvoiceLineItemRetrievalOptions, response?: IResponseFn>): Promise; - retrieveLines(id: string, options: HeaderOptions, response?: IResponseFn>): Promise; - retrieveLines(id: string, response?: IResponseFn>): Promise; + retrieveLines(id: string, data: invoices.IInvoiceLineItemRetrievalOptions, options: HeaderOptions, response?: IResponseFn>): Promise>; + retrieveLines(id: string, data: invoices.IInvoiceLineItemRetrievalOptions, response?: IResponseFn>): Promise>; + retrieveLines(id: string, options: HeaderOptions, response?: IResponseFn>): Promise>; + retrieveLines(id: string, response?: IResponseFn>): Promise>; /** * At any time, you can preview the upcoming invoice for a customer. This will show you all the charges that are pending, diff --git a/types/stripe/stripe-tests.ts b/types/stripe/stripe-tests.ts index 3cfe1e9f5f..2b122caa1b 100644 --- a/types/stripe/stripe-tests.ts +++ b/types/stripe/stripe-tests.ts @@ -1381,8 +1381,8 @@ stripe.ephemeralKeys.create({ customer: "cus_5rfJKDJkuxzh5Q" }, { stripe_version stripe.usageRecords.create('sub_8QwCiwZ9tmMSpt', { action: 'set', quantity: 10000, timestamp: 1537006853 }).then((usageRecord: Stripe.usageRecords.IUsageRecord) => {}); stripe.usageRecords.create('sub_8QwCiwZ9tmMSpt', { action: 'set', quantity: 10000, timestamp: 1537006853 }, (err, usageRecord: Stripe.usageRecords.IUsageRecord) => {}); -stripe.usageRecordSummaries.list({ subscription_item: 'si_C9gimdd2l9qvCU', limit: 10 }).then((usageRecordSummaries: Stripe.usageRecordSummaries.IUsageRecordSummaries) => {}); -stripe.usageRecordSummaries.list({ subscription_item: 'si_C9gimdd2l9qvCU', limit: 10 }, (err, usageRecordSummaries: Stripe.usageRecordSummaries.IUsageRecordSummaries) => {}); +stripe.usageRecordSummaries.list('si_C9gimdd2l9qvCU', { limit: 10 }).then((usageRecordSummaries: Stripe.usageRecordSummaries.IUsageRecordSummaries) => {}); +stripe.usageRecordSummaries.list('si_C9gimdd2l9qvCU', { limit: 10 }, (err, usageRecordSummaries: Stripe.usageRecordSummaries.IUsageRecordSummaries) => {}); //#region Errors // ################################################################################## diff --git a/types/styled-system/index.d.ts b/types/styled-system/index.d.ts index ec7686ab89..b91f9c1707 100644 --- a/types/styled-system/index.d.ts +++ b/types/styled-system/index.d.ts @@ -1,4 +1,4 @@ -// Type definitions for styled-system 3.2 +// Type definitions for styled-system 4.0 // Project: https://github.com/jxnblk/styled-system#readme // Definitions by: Marshall Bowers // Ben McCormick @@ -51,7 +51,7 @@ export type TLengthStyledSystem = string | 0 | number; export type ResponsiveValue = T | Array | { [key: string]: T }; /** - * Converts shorthand margin and padding props to margin and padding CSS declarations + * Converts shorthand or longhand margin and padding props to margin and padding CSS declarations * * - Numbers from 0-4 (or the length of theme.space) are converted to values on the spacing scale. * - Negative values can be used for negative margins. @@ -59,32 +59,51 @@ export type ResponsiveValue = T | Array | { [key: string]: T }; * - String values are passed as raw CSS values. * - Array values are converted into responsive values. */ - export interface SpaceProps { /** Margin on top, left, bottom and right */ m?: ResponsiveValue>; + /** Margin on top, left, bottom and right */ + margin?: ResponsiveValue>; /** Margin for the top */ mt?: ResponsiveValue>; + /** Margin for the top */ + marginTop?: ResponsiveValue>; /** Margin for the right */ mr?: ResponsiveValue>; + /** Margin for the right */ + marginRight?: ResponsiveValue>; /** Margin for the bottom */ mb?: ResponsiveValue>; + /** Margin for the bottom */ + marginBottom?: ResponsiveValue>; /** Margin for the left */ ml?: ResponsiveValue>; + /** Margin for the left */ + marginLeft?: ResponsiveValue>; /** Margin for the left and right */ mx?: ResponsiveValue>; /** Margin for the top and bottom */ my?: ResponsiveValue>; /** Padding on top, left, bottom and right */ p?: ResponsiveValue>; + /** Padding on top, left, bottom and right */ + padding?: ResponsiveValue>; /** Padding for the top */ pt?: ResponsiveValue>; + /** Padding for the top */ + paddingTop?: ResponsiveValue>; /** Padding for the right */ pr?: ResponsiveValue>; + /** Padding for the right */ + paddingRight?: ResponsiveValue>; /** Padding for the bottom */ pb?: ResponsiveValue>; + /** Padding for the bottom */ + paddingBottom?: ResponsiveValue>; /** Padding for the left */ pl?: ResponsiveValue>; + /** Padding for the left */ + paddingLeft?: ResponsiveValue>; /** Padding for the left and right */ px?: ResponsiveValue>; /** Padding for the top and bottom */ diff --git a/types/styled-system/styled-system-tests.tsx b/types/styled-system/styled-system-tests.tsx index ae2f87b7ab..c99a15c8f2 100644 --- a/types/styled-system/styled-system-tests.tsx +++ b/types/styled-system/styled-system-tests.tsx @@ -328,8 +328,30 @@ const test = () => ( // responsive margin + + + + + + + + + + + // responsive padding + + + + + + + + + + + // examples (margin prop) // sets margin value of `theme.space[2]` diff --git a/types/three/test/docs/scenes/bones_browser.ts b/types/three/test/docs/scenes/bones_browser.ts index c04a788cde..116af826d8 100644 --- a/types/three/test/docs/scenes/bones_browser.ts +++ b/types/three/test/docs/scenes/bones_browser.ts @@ -42,7 +42,7 @@ initBones(); } function createGeometry(sizing: any) { - var geometry = new THREE.CylinderGeometry( + var geometry = new THREE.CylinderBufferGeometry( 5, // radiusTop 5, // radiusBottom sizing.height, // height @@ -50,14 +50,29 @@ sizing.segmentCount * 3, // heightSegments true // openEnded ); - for (var i = 0; i < geometry.vertices.length; i++) { - var vertex = geometry.vertices[i]; + + var position = geometry.attributes.position as THREE.BufferAttribute; + + var vertex = new THREE.Vector3(); + + var skinIndices = []; + var skinWeights = []; + + for (var i = 0; i < position.count; i++) { + vertex.fromBufferAttribute(position, i); + var y = (vertex.y + sizing.halfHeight); + var skinIndex = Math.floor(y / sizing.segmentHeight); var skinWeight = (y % sizing.segmentHeight) / sizing.segmentHeight; - geometry.skinIndices.push(new THREE.Vector4(skinIndex, skinIndex + 1, 0, 0)); - geometry.skinWeights.push(new THREE.Vector4(1 - skinWeight, skinWeight, 0, 0)); + + skinIndices.push(skinIndex, skinIndex + 1, 0, 0); + skinWeights.push(1 - skinWeight, skinWeight, 0, 0); } + + geometry.addAttribute('skinIndex', new THREE.Uint16BufferAttribute(skinIndices, 4)); + geometry.addAttribute('skinWeight', new THREE.Float32BufferAttribute(skinWeights, 4)); + return geometry; } function createBones(sizing: any) { @@ -74,7 +89,7 @@ } return bones; } - function createMesh(geometry: THREE.Geometry, bones: THREE.Bone[]) { + function createMesh(geometry: THREE.BufferGeometry, bones: THREE.Bone[]) { var material = new THREE.MeshPhongMaterial({ skinning: true, color: 0x156289, diff --git a/types/three/test/references.ts b/types/three/test/references.ts index e2068d68a5..d966799943 100644 --- a/types/three/test/references.ts +++ b/types/three/test/references.ts @@ -2,3 +2,4 @@ /// /// +/// diff --git a/types/three/test/webgl/webgl_animation_skinning_morph.ts b/types/three/test/webgl/webgl_animation_skinning_morph.ts index 835d7a6ea5..e9129084ba 100644 --- a/types/three/test/webgl/webgl_animation_skinning_morph.ts +++ b/types/three/test/webgl/webgl_animation_skinning_morph.ts @@ -1,228 +1,209 @@ -// https://github.com/mrdoob/three.js/blob/master/examples/webgl_sprites.html +// https://github.com/mrdoob/three.js/blob/master/examples/webgl_animation_skinning_morph.html () => { // ------- variable definitions that does not exist in the original code. These are for typescript. + interface WEBGL { + isWebGLAvailable(): boolean; + + isWebGL2Available(): boolean; + + getWebGLErrorMessage(): HTMLDivElement; + + getWebGL2ErrorMessage(): HTMLDivElement; + + getErrorMessage(version: 1 | 2): HTMLDivElement; + } + + var WEBGL: WEBGL; // ------- - var SCREEN_WIDTH = window.innerWidth; - var SCREEN_HEIGHT = window.innerHeight; - var FLOOR = -250; - - var container: HTMLElement; + if (WEBGL.isWebGLAvailable() === false) { + document.body.appendChild(WEBGL.getWebGLErrorMessage()); + } + var container: HTMLElement var stats: Stats; + var clock: THREE.Clock; + var gui: dat.GUI; + var mixer: THREE.AnimationMixer; + var actions: { [name: string]: THREE.AnimationAction }; + var activeAction: THREE.AnimationAction; + var previousAction: THREE.AnimationAction; + var camera: THREE.PerspectiveCamera; var scene: THREE.Scene; var renderer: THREE.WebGLRenderer; - var mesh: THREE.Mesh; - var helper: THREE.SkeletonHelper; - var mixer: THREE.AnimationMixer; + var model: THREE.Scene; + var face: THREE.Mesh; - var mouseX = 0, mouseY = 0; + type Emote = 'Jump' | 'Yes' | 'No' | 'Wave' | 'Punch' | 'ThumbsUp'; - var windowHalfX = window.innerWidth / 2; - var windowHalfY = window.innerHeight / 2; - - var clock = new THREE.Clock(); - - document.addEventListener( 'mousemove', onDocumentMouseMove, false ); + var api: { [name in Emote]?: () => void; } & { state: string; } = {state: 'Walking'}; init(); animate(); function init() { + container = document.createElement('div'); + document.body.appendChild(container); - container = document.getElementById( 'container' ); - - camera = new THREE.PerspectiveCamera( 30, SCREEN_WIDTH / SCREEN_HEIGHT, 1, 10000 ); - camera.position.z = 2200; + camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.25, 100); + camera.position.set(-5, 3, 10); + camera.lookAt(new THREE.Vector3(0, 2, 0)); scene = new THREE.Scene(); + scene.background = new THREE.Color(0xe0e0e0); + scene.fog = new THREE.Fog(0xe0e0e0, 20, 100); - scene.fog = new THREE.Fog( 0xffffff, 2000, 10000 ); + clock = new THREE.Clock(); - scene.add( camera ); + // lights + var light: THREE.Light = new THREE.HemisphereLight(0xffffff, 0x444444); + light.position.set(0, 20, 0); + scene.add(light); - // GROUND + light = new THREE.DirectionalLight(0xffffff); + light.position.set(0, 20, 10); + scene.add(light); - var geometry = new THREE.PlaneBufferGeometry( 16000, 16000 ); - var material = new THREE.MeshPhongMaterial( { emissive: 0x888888 } ); + // ground + var mesh = new THREE.Mesh(new THREE.PlaneBufferGeometry(2000, 2000), new THREE.MeshPhongMaterial({ + color: 0x999999, + depthWrite: false + })); + mesh.rotation.x = -Math.PI / 2; + scene.add(mesh); - var ground = new THREE.Mesh( geometry, material ); - ground.position.set( 0, FLOOR, 0 ); - ground.rotation.x = -Math.PI/2; - scene.add( ground ); + var grid = new THREE.GridHelper(200, 40, 0x000000, 0x000000); + (grid.material as THREE.LineBasicMaterial).opacity = 0.2; + (grid.material as THREE.LineBasicMaterial).transparent = true; + scene.add(grid); - ground.receiveShadow = true; + // model + var loader = new THREE.GLTFLoader(); + loader.load('models/gltf/RobotExpressive/RobotExpressive.glb', function (gltf) { + model = gltf.scene; + scene.add(model); + createGUI(model, gltf.animations); + }, undefined, function (e) { + console.error(e); + }); - // LIGHTS - - scene.add( new THREE.HemisphereLight( 0x111111, 0x444444 ) ); - - var light = new THREE.DirectionalLight( 0xebf3ff, 1.5 ); - light.position.set( 0, 140, 500 ).multiplyScalar( 1.1 ); - scene.add( light ); - - light.castShadow = true; - - light.shadowMapWidth = 1024; - light.shadowMapHeight = 1024; - - var d = 390; - - light.shadowCameraLeft = -d; - light.shadowCameraRight = d; - light.shadowCameraTop = d * 1.5; - light.shadowCameraBottom = -d; - - light.shadowCameraFar = 3500; - //light.shadowCameraVisible = true; - - // RENDERER - - renderer = new THREE.WebGLRenderer( { antialias: true } ); - renderer.setClearColor( scene.fog.color ); - renderer.setPixelRatio( window.devicePixelRatio ); - renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT ); - renderer.domElement.style.position = "relative"; - - container.appendChild( renderer.domElement ); - - renderer.gammaInput = true; + renderer = new THREE.WebGLRenderer({antialias: true}); + renderer.setPixelRatio(window.devicePixelRatio); + renderer.setSize(window.innerWidth, window.innerHeight); renderer.gammaOutput = true; + renderer.gammaFactor = 2.2; + container.appendChild(renderer.domElement); - renderer.shadowMap.enabled = true; - - - // STATS + window.addEventListener('resize', onWindowResize, false); + // stats stats = new Stats(); - container.appendChild( stats.dom ); + container.appendChild(stats.dom); + } - // + function createGUI(model: THREE.Scene, animations: THREE.AnimationClip[]) { + var states = ['Idle', 'Walking', 'Running', 'Dance', 'Death', 'Sitting', 'Standing']; + var emotes: Emote[] = ['Jump', 'Yes', 'No', 'Wave', 'Punch', 'ThumbsUp']; - var loader = new THREE.JSONLoader(); - loader.load( "models/skinned/knight.js", function ( geometry, materials ) { + gui = new dat.GUI(); - createScene( geometry, materials as THREE.MeshPhongMaterial[], 0, FLOOR, -300, 60 ) + mixer = new THREE.AnimationMixer(model); - } ); + actions = {}; - // GUI + for (var i = 0; i < animations.length; i++) { + var clip = animations[i]; + var action = mixer.clipAction(clip); + actions[clip.name] = action; - initGUI(); + if (emotes.indexOf(clip.name as Emote) >= 0 || states.indexOf(clip.name) >= 4) { + action.clampWhenFinished = true; + action.loop = THREE.LoopOnce; + } + } - // + // states + var statesFolder = gui.addFolder('States'); - window.addEventListener( 'resize', onWindowResize, false ); + var clipCtrl = statesFolder.add(api, 'state').options(states); + clipCtrl.onChange(function () { + fadeToAction(api.state, 0.5); + }); + + statesFolder.open(); + + // emotes + var emoteFolder = gui.addFolder('Emote'); + + function createEmoteCallback(name: Emote) { + api[name] = function () { + fadeToAction(name, 0.2); + mixer.addEventListener('finished', restoreState); + }; + + emoteFolder.add(api, name); + } + + function restoreState() { + mixer.removeEventListener('finished', restoreState); + + fadeToAction(api.state, 0.2); + } + + for (var i = 0; i < emotes.length; i++) { + createEmoteCallback(emotes[i]); + } + + emoteFolder.open(); + + // expressions + face = model.getObjectByName('Head_2') as THREE.Mesh; + + var expressions = Object.keys(face.morphTargetDictionary); + var expressionFolder = gui.addFolder('Expressions'); + + for (var i = 0; i < expressions.length; i++) { + expressionFolder.add(face.morphTargetInfluences, i.toString(), 0, 1, 0.01).name(expressions[i]); + } + + activeAction = actions['Walking']; + activeAction.play(); + + expressionFolder.open(); + } + + function fadeToAction(name: string, duration: number) { + previousAction = activeAction; + activeAction = actions[name]; + + if (previousAction !== activeAction) { + previousAction.fadeOut(duration); + } + + activeAction + .reset() + .setEffectiveTimeScale(1) + .setEffectiveWeight(1) + .fadeIn(duration) + .play(); } function onWindowResize() { - - windowHalfX = window.innerWidth / 2; - windowHalfY = window.innerHeight / 2; - camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); - renderer.setSize( window.innerWidth, window.innerHeight ); - - } - - function createScene( geometry: THREE.Geometry, materials: THREE.MeshPhongMaterial[], x: number, y: number, z: number, s: number ) { - - //ensureLoop( geometry.animation ); - - geometry.computeBoundingBox(); - var bb = geometry.boundingBox; - - var path = "textures/cube/Park2/"; - var format = '.jpg'; - var urls = [ - path + 'posx' + format, path + 'negx' + format, - path + 'posy' + format, path + 'negy' + format, - path + 'posz' + format, path + 'negz' + format - ]; - - for ( var i = 0; i < materials.length; i ++ ) { - - var m = materials[ i ]; - m.skinning = true; - m.morphTargets = true; - - m.specular.setHSL( 0, 0, 0.1 ); - - m.color.setHSL( 0.6, 0, 0.6 ); - - //m.map = map; - //m.envMap = envMap; - //m.bumpMap = bumpMap; - //m.bumpScale = 2; - - //m.combine = THREE.MixOperation; - //m.reflectivity = 0.75; - - } - - mesh = new THREE.SkinnedMesh( geometry, new THREE.MeshFaceMaterial( materials ) ); - mesh.position.set( x, y - bb.min.y * s, z ); - mesh.scale.set( s, s, s ); - scene.add( mesh ); - - mesh.castShadow = true; - mesh.receiveShadow = true; - - helper = new THREE.SkeletonHelper( mesh ); - //helper.material.linewidth = 3; - helper.visible = false; - scene.add( helper ); - - - var clipMorpher = THREE.AnimationClip.CreateFromMorphTargetSequence( 'facialExpressions', (mesh.geometry as THREE.Geometry).morphTargets, 3, true ); - var clipBones = geometry.animations[0]; - - mixer = new THREE.AnimationMixer( mesh ); - } - - function initGUI() { - mesh.visible = true; - helper.visible = true; - } - - function onDocumentMouseMove( event: MouseEvent ) { - - mouseX = ( event.clientX - windowHalfX ); - mouseY = ( event.clientY - windowHalfY ); - + renderer.setSize(window.innerWidth, window.innerHeight); } // - function animate() { - - requestAnimationFrame( animate ); - - render(); + var dt = clock.getDelta(); + if (mixer) mixer.update(dt); + requestAnimationFrame(animate); + renderer.render(scene, camera); stats.update(); - } - - function render() { - - var delta = 0.75 * clock.getDelta(); - - camera.position.x += ( mouseX - camera.position.x ) * .05; - camera.position.y = THREE.Math.clamp( camera.position.y + ( - mouseY - camera.position.y ) * .05, 0, 1000 ); - - camera.lookAt( scene.position ); - - if( mixer ) { - mixer.update( delta ); - helper.update(); - } - - renderer.render( scene, camera ); - - } -} \ No newline at end of file +} diff --git a/types/three/three-core.d.ts b/types/three/three-core.d.ts index 96c40c7496..f39d28b565 100755 --- a/types/three/three-core.d.ts +++ b/types/three/three-core.d.ts @@ -224,7 +224,7 @@ type TypedArray = Int8Array | Uint8Array | Uint8ClampedArray | Int16Array | Uint // Animation //////////////////////////////////////////////////////////////////////////////////////// export class AnimationAction { - loop: boolean; + loop: AnimationActionLoopStyles; time: number; timeScale: number; weight: number; diff --git a/types/turbolinks/index.d.ts b/types/turbolinks/index.d.ts new file mode 100644 index 0000000000..e5e450a292 --- /dev/null +++ b/types/turbolinks/index.d.ts @@ -0,0 +1,22 @@ +// Type definitions for turbolinks 5.2 +// Project: https://github.com/turbolinks/turbolinks +// Definitions by: evankim390 +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +export = Turbolinks; +export as namespace Turbolinks; + +declare const Turbolinks: Turbolinks.TurbolinksStatic; + +declare namespace Turbolinks { + interface Action { + action: "advance" | "replace"; + } + interface TurbolinksStatic { + start(): void; + visit(location: string, options?: Action): void; + clearCache(): void; + setProgressBarDelay(delayInMilliseconds: number): void; + supported: boolean; + } +} diff --git a/types/turbolinks/tsconfig.json b/types/turbolinks/tsconfig.json new file mode 100644 index 0000000000..d77954199b --- /dev/null +++ b/types/turbolinks/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", + "turbolinks-tests.ts" + ] +} diff --git a/types/filenamify/tslint.json b/types/turbolinks/tslint.json similarity index 100% rename from types/filenamify/tslint.json rename to types/turbolinks/tslint.json diff --git a/types/turbolinks/turbolinks-tests.ts b/types/turbolinks/turbolinks-tests.ts new file mode 100644 index 0000000000..aa69ee4a62 --- /dev/null +++ b/types/turbolinks/turbolinks-tests.ts @@ -0,0 +1,13 @@ +import Turbolinks = require("turbolinks"); + +Turbolinks.start(); +Turbolinks.visit("/new/path"); +Turbolinks.visit("/new/path", { + action: "replace", +}); +Turbolinks.visit("/new/path", { + action: "advance", +}); +Turbolinks.setProgressBarDelay(100); +Turbolinks.clearCache(); +Turbolinks.supported; diff --git a/types/uni-app/index.d.ts b/types/uni-app/index.d.ts new file mode 100644 index 0000000000..960a3e8061 --- /dev/null +++ b/types/uni-app/index.d.ts @@ -0,0 +1,6232 @@ +// Type definitions for non-npm package uni-app 1.0 +// Project: https://github.com/dcloudio/uni-app +// Definitions by: DCloud +// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped + +// TypeScript Version: 2.3 + +/** + * Uni 实例变量 + */ +declare const uni: Uni; + +declare class Uni { + /** + * 发起网络请求 + * + * 参考: [http://uniapp.dcloud.io/api/request/request?id=request](http://uniapp.dcloud.io/api/request/request?id=request) + */ + request(options: RequestOptions): RequestTask; + /** + * 上传文件 + * + * 参考: [http://uniapp.dcloud.io/api/request/network-file?id=uploadfile](http://uniapp.dcloud.io/api/request/network-file?id=uploadfile) + */ + uploadFile(options: UploadFileOption): UploadTask; + /** + * 下载文件 + * + * 参考: [http://uniapp.dcloud.io/api/request/network-file?id=downloadfile](http://uniapp.dcloud.io/api/request/network-file?id=downloadfile) + */ + downloadFile(options: DownloadFileOption): DownloadTask; + /** + * 导入原生插件 + * + * 参考: [http://uniapp.dcloud.io/api/request/network-file?id=downloadfile](http://uniapp.dcloud.io/api/request/network-file?id=downloadfile) + */ + requireNativePlugin(moduleName: string): void; + /** + * upx 换算为 px + * + * 参考: [http://uniapp.dcloud.io/frame?id=upx2px](http://uniapp.dcloud.io/frame?id=upx2px) + */ + upx2px(): number; + /** + * 创建一个 WebSocket 连接 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=connectsocket](http://uniapp.dcloud.io/api/request/websocket?id=connectsocket) + */ + connectSocket(options: ConnectSocketOption): SocketTask; + /** + * 监听WebSocket连接打开事件 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketopen](http://uniapp.dcloud.io/api/request/websocket?id=onsocketopen) + */ + onSocketOpen(options: (result: OnSocketOpenCallbackResult) => void): void; + /** + * 监听WebSocket错误 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketerror](http://uniapp.dcloud.io/api/request/websocket?id=onsocketerror) + */ + onSocketError(callback: (result: GeneralCallbackResult) => void): void; + /** + * 通过 WebSocket 连接发送数据 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=sendsocketmessage](http://uniapp.dcloud.io/api/request/websocket?id=sendsocketmessage) + */ + sendSocketMessage(options: SendSocketMessageOptions): void; + /** + * 监听WebSocket接受到服务器的消息事件 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketmessage](http://uniapp.dcloud.io/api/request/websocket?id=onsocketmessage) + */ + onSocketMessage(callback: (result: OnSocketMessageCallbackResult) => void): void; + /** + * 关闭 WebSocket 连接 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=closesocket](http://uniapp.dcloud.io/api/request/websocket?id=closesocket) + */ + closeSocket(options: CloseSocketOptions): void; + /** + * 监听WebSocket关闭 + * + * 参考: [http://uniapp.dcloud.io/api/request/websocket?id=onsocketclose](http://uniapp.dcloud.io/api/request/websocket?id=onsocketclose) + */ + onSocketClose(callback: (result: GeneralCallbackResult) => void): void; + /** + * 从本地相册选择图片或使用相机拍照 + * + * 参考: [http://uniapp.dcloud.io/api/media/image?id=chooseimage](http://uniapp.dcloud.io/api/media/image?id=chooseimage) + */ + chooseImage(options: ChooseImageOptions): void; + /** + * 预览图片 + * + * 参考: [http://uniapp.dcloud.io/api/media/image?id=previewimage](http://uniapp.dcloud.io/api/media/image?id=previewimage) + */ + previewImage(options: PreviewImageOptions): void; + /** + * 预览图片 + * + * 参考: [http://uniapp.dcloud.io/api/media/image?id=getimageinfo](http://uniapp.dcloud.io/api/media/image?id=getimageinfo) + */ + getImageInfo(options: GetImageInfoOptions): void; + /** + * 保存图片到系统相册 + * + * 参考: [http://uniapp.dcloud.io/api/media/image?id=saveimagetophotosalbum](http://uniapp.dcloud.io/api/media/image?id=saveimagetophotosalbum) + */ + saveImageToPhotosAlbum(options: SaveImageToPhotosAlbumOptions): void; + /** + * 录音管理 + * + * 参考: [http://uniapp.dcloud.io/api/media/record-manager?id=getrecordermanager](http://uniapp.dcloud.io/api/media/record-manager?id=getrecordermanager) + */ + getRecorderManager(): RecorderManager; + /** + * 获取全局唯一的背景音频管理器 backgroundAudioManager + * + * 参考: [http://uniapp.dcloud.io/api/media/background-audio-manager?id=getbackgroundaudiomanager](http://uniapp.dcloud.io/api/media/background-audio-manager?id=getbackgroundaudiomanager) + */ + getBackgroundAudioManager(): BackgroundAudioManager; + /** + * 创建并返回 audio 上下文 audioContext 对象 + * + * 参考: [http://uniapp.dcloud.io/api/media/audio-context?id=createinneraudiocontext](http://uniapp.dcloud.io/api/media/audio-context?id=createinneraudiocontext) + */ + createInnerAudioContext(): CreateInnerAudioContext; + /** + * 拍摄视频或从手机相册中选视频,返回视频的临时文件路径。 + * + * 参考: [http://uniapp.dcloud.io/api/media/video?id=choosevideo](http://uniapp.dcloud.io/api/media/video?id=choosevideo) + */ + chooseVideo(options: ChooseVideoOptions): void; + /** + * 保存视频到系统相册 + * + * 参考: [http://uniapp.dcloud.io/api/media/video?id=savevideotophotosalbum](http://uniapp.dcloud.io/api/media/video?id=savevideotophotosalbum) + */ + saveVideoToPhotosAlbum(options: SaveVideoToPhotosAlbumOptions): void; + /** + * 创建并返回 video 上下文 videoContext 对象 + * + * 参考: [http://uniapp.dcloud.io/api/media/video-context?id=createvideocontext](http://uniapp.dcloud.io/api/media/video-context?id=createvideocontext) + */ + createVideoContext(): VideoContext; + /** + * 保存文件到本地 + * + * 参考: [http://uniapp.dcloud.io/api/file/file?id=savefile](http://uniapp.dcloud.io/api/file/file?id=savefile) + */ + saveFile(options: SaveFileOptions): void; + /** + * 获取文件信息 + */ + getFileInfo(options: GetFileInfoOptions): void; + /** + * 获取本地已保存的文件列表 + * + * 参考: [http://uniapp.dcloud.io/api/file/file?id=getsavedfilelist](http://uniapp.dcloud.io/api/file/file?id=getsavedfilelist) + */ + getSavedFileList(options: GetSavedFileListOptions): void; + /** + * 获取本地文件的文件信息 + * + * 参考: [http://uniapp.dcloud.io/api/file/file?id=getsavedfileinfo](http://uniapp.dcloud.io/api/file/file?id=getsavedfileinfo) + */ + getSavedFileInfo(options: GetSavedFileInfoOptions): void; + /** + * 删除本地存储的文件 + * + * 参考: [http://uniapp.dcloud.io/api/file/file?id=removesavedfile](http://uniapp.dcloud.io/api/file/file?id=removesavedfile) + */ + removeSavedFile(options: RemoveSavedFileOptions): void; + /** + * 新开页面打开文档,支持格式:doc, xls, ppt, pdf, docx, xlsx, pptx + * + * 参考: [http://uniapp.dcloud.io/api/file/file?id=opendocument](http://uniapp.dcloud.io/api/file/file?id=opendocument) + */ + openDocument(options: OpenDocumentOptions): void; + /** + * 将数据存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个异步接口 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=setstorage](http://uniapp.dcloud.io/api/storage/storage?id=setstorage) + */ + setStorage(options: SetStorageOptions): void; + /** + * 将 data 存储在本地缓存中指定的 key 中,会覆盖掉原来该 key 对应的内容,这是一个同步接口 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=setstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=setstoragesync) + */ + setStorageSync(): void; + /** + * 从本地缓存中异步获取指定 key 对应的内容 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorage](http://uniapp.dcloud.io/api/storage/storage?id=getstorage) + */ + getStorage(options: GetStorageOptions): void; + /** + * 从本地缓存中同步获取指定 key 对应的内容 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=getstoragesync) + */ + getStorageSync(): void; + /** + * 异步获取当前storage的相关信息 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfo](http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfo) + */ + getStorageInfo(options: GetStorageInfoOptions): void; + /** + * 同步获取当前storage的相关信息 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfosync](http://uniapp.dcloud.io/api/storage/storage?id=getstorageinfosync) + */ + getStorageInfoSync(): void; + /** + * 从本地缓存中异步移除指定 key + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=removestorage](http://uniapp.dcloud.io/api/storage/storage?id=removestorage) + */ + removeStorage(options: RemoveStorageOptions): void; + /** + * 从本地缓存中同步移除指定 key + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=removestoragesync](http://uniapp.dcloud.io/api/storage/storage?id=removestoragesync) + */ + removeStorageSync(): void; + /** + * 清理本地数据缓存 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=clearstorage](http://uniapp.dcloud.io/api/storage/storage?id=clearstorage) + */ + clearStorage(): void; + /** + * 同步清理本地数据缓存 + * + * 参考: [http://uniapp.dcloud.io/api/storage/storage?id=clearstoragesync](http://uniapp.dcloud.io/api/storage/storage?id=clearstoragesync) + */ + clearStorageSync(): void; + /** + * 获取当前的地理位置、速度 + * + * 参考: [http://uniapp.dcloud.io/api/location/location?id=getlocation](http://uniapp.dcloud.io/api/location/location?id=getlocation) + */ + getLocation(options: GetLocationOptions): void; + /** + * 打开地图选择位置。 + * + * 参考: [http://uniapp.dcloud.io/api/location/location?id=chooselocation](http://uniapp.dcloud.io/api/location/location?id=chooselocation) + */ + chooseLocation(options: ChooseLocationOptions): void; + /** + * 使用地图查看位置 + * + * 参考: [http://uniapp.dcloud.io/api/location/open-location?id=openlocation](http://uniapp.dcloud.io/api/location/open-location?id=openlocation) + */ + openLocation(options: OpenLocationOptions): void; + /** + * 创建并返回 map 上下文 mapContext 对象 + * + * 参考: [http://uniapp.dcloud.io/api/location/map?id=createmapcontext](http://uniapp.dcloud.io/api/location/map?id=createmapcontext) + */ + createMapContext(): MapContext; + /** + * 获取系统信息 + * + * 参考: [http://uniapp.dcloud.io/api/system/info?id=getsysteminfo](http://uniapp.dcloud.io/api/system/info?id=getsysteminfo) + */ + getSystemInfo(options: GetSystemInfoOptions): void; + /** + * 获取系统信息 + * + * 参考: [http://uniapp.dcloud.io/api/system/info?id=getsysteminfosync](http://uniapp.dcloud.io/api/system/info?id=getsysteminfosync) + */ + getSystemInfoSync(): GetSystemInfoSuccess; + /** + * 判断uni-app的API,回调,参数,组件等是否在当前版本可用 + * + * 参考: [http://uniapp.dcloud.io/api/system/info?id=caniuse](http://uniapp.dcloud.io/api/system/info?id=caniuse) + */ + canIUse(options: string): boolean; + /** + * 获取网络类型 + * + * 参考: [http://uniapp.dcloud.io/api/system/network?id=getnetworktype](http://uniapp.dcloud.io/api/system/network?id=getnetworktype) + */ + getNetworkType(options: GetNetworkTypeOptions): void; + /** + * 监听网络状态变化 + * + * 参考: [http://uniapp.dcloud.io/api/system/network?id=onnetworkstatuschange](http://uniapp.dcloud.io/api/system/network?id=onnetworkstatuschange) + */ + onNetworkStatusChange(callback: (result: OnNetworkStatusChangeSuccess) => void): void; + /** + * 监听加速度数据,频率:5次/秒,接口调用后会自动开始监听,可使用 uni.stopAccelerometer 停止监听 + * + * 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=onaccelerometerchange](http://uniapp.dcloud.io/api/system/accelerometer?id=onaccelerometerchange) + */ + onAccelerometerChange(callback: (result: OnAccelerometerChangeSuccess) => void): void; + /** + * 开始监听加速度数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=startaccelerometer](http://uniapp.dcloud.io/api/system/accelerometer?id=startaccelerometer) + */ + startAccelerometer(options: StartAccelerometerOptions): void; + /** + * 停止监听加速度数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/accelerometer?id=stopaccelerometer](http://uniapp.dcloud.io/api/system/accelerometer?id=stopaccelerometer) + */ + stopAccelerometer(options: StopAccelerometerOptions): void; + /** + * 监听罗盘数据,频率:5次/秒,接口调用后会自动开始监听,可使用uni.stopCompass停止监听 + * + * 参考: [http://uniapp.dcloud.io/api/system/compass?id=oncompasschange](http://uniapp.dcloud.io/api/system/compass?id=oncompasschange) + */ + onCompassChange(callback: (result: OnCompassChangeSuccess) => void): void; + /** + * 开始监听罗盘数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/compass?id=startcompass](http://uniapp.dcloud.io/api/system/compass?id=startcompass) + */ + startCompass(options: StartCompassOptions): void; + /** + * 停止监听罗盘数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/compass?id=stopcompass](http://uniapp.dcloud.io/api/system/compass?id=stopcompass) + */ + stopCompass(options: StopCompassOptions): void; + /** + * 拨打电话 + * + * 参考: [http://uniapp.dcloud.io/api/system/phone?id=makephonecall](http://uniapp.dcloud.io/api/system/phone?id=makephonecall) + */ + makePhoneCall(options: MakePhoneCallOptions): void; + /** + * 调用扫码界面,扫码成功后返回对应的结果 + * + * 参考: [http://uniapp.dcloud.io/api/system/barcode?id=scancode](http://uniapp.dcloud.io/api/system/barcode?id=scancode) + */ + scanCode(options: ScanCodeOptions): void; + /** + * 设置系统剪贴板的内容 + * + * 参考: [http://uniapp.dcloud.io/api/system/clipboard?id=setclipboarddata](http://uniapp.dcloud.io/api/system/clipboard?id=setclipboarddata) + */ + setClipboardData(options: SetClipboardDataOptions): void; + /** + * 获得系统剪贴板的内容 + * + * 参考: [http://uniapp.dcloud.io/api/system/clipboard?id=getclipboarddata](http://uniapp.dcloud.io/api/system/clipboard?id=getclipboarddata) + */ + getClipboardData(options: GetClipboardDataOptions): void; + /** + * 隐藏软键盘 + * + * 参考: [http://uniapp.dcloud.io/api/keyboard?id=hidekeyboard](http://uniapp.dcloud.io/api/keyboard?id=hidekeyboard) + */ + hideKeyboard(): void; + /** + * 设置屏幕亮度 + * + * 参考: [http://uniapp.dcloud.io/api/system/brightness?id=setscreenbrightness](http://uniapp.dcloud.io/api/system/brightness?id=setscreenbrightness) + */ + setScreenBrightness(options: SetScreenBrightnessOptions): void; + /** + * 获取屏幕亮度 + * + * 参考: [http://uniapp.dcloud.io/api/system/brightness?id=getscreenbrightness](http://uniapp.dcloud.io/api/system/brightness?id=getscreenbrightness) + */ + getScreenBrightness(options: GetScreenBrightnessOptions): void; + /** + * 设置是否保持常亮状态 + * + * 参考: [http://uniapp.dcloud.io/api/system/brightness?id=setkeepscreenon](http://uniapp.dcloud.io/api/system/brightness?id=setkeepscreenon) + */ + setKeepScreenOn(options: SetKeepScreenOnOptions): void; + /** + * 使手机发生较长时间的振动(400ms) + * + * 参考: [http://uniapp.dcloud.io/api/system/vibrate?id=vibratelong](http://uniapp.dcloud.io/api/system/vibrate?id=vibratelong) + */ + vibrateLong(options: VibrateLongOptions): void; + /** + * 使手机发生较短时间的振动(15ms) + * + * 参考: [http://uniapp.dcloud.io/api/system/vibrate?id=vibrateshort](http://uniapp.dcloud.io/api/system/vibrate?id=vibrateshort) + */ + vibrateShort(options: VibrateShortOptions): void; + /** + * 手机通讯录联系人和联系方式的增加 + * + * 参考: [http://uniapp.dcloud.io/api/system/contact?id=addphonecontact](http://uniapp.dcloud.io/api/system/contact?id=addphonecontact) + */ + addPhoneContact(options: AddPhoneContactOptions): void; + /** + * 获取已搜索到的iBeacon设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=getbeacons](http://uniapp.dcloud.io/api/system/ibeacon?id=getbeacons) + */ + getBeacons(options: GetBeaconsOptions): void; + /** + * 开始搜索附近的iBeacon设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=startbeacondiscovery](http://uniapp.dcloud.io/api/system/ibeacon?id=startbeacondiscovery) + */ + startBeaconDiscovery(options: StartBeaconDiscoveryOptions): void; + /** + * 停止搜索附近的iBeacon设备 + * + * 参考: [http://uniapp.dcloud.io//api/system/ibeacon?id=stopbeacondiscovery](http://uniapp.dcloud.io//api/system/ibeacon?id=stopbeacondiscovery) + */ + stopBeaconDiscovery(options: StopBeaconDiscoveryOptions): void; + /** + * 监听iBeacon设备更新 + * + * 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconupdate](http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconupdate) + */ + onBeaconUpdate(callback: (result: GetBeaconsRes) => void): void; + /** + * 监听iBeacon服务状态变化 + * + * 参考: [http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconservicechange](http://uniapp.dcloud.io/api/system/ibeacon?id=onbeaconservicechange) + */ + onBeaconServiceChange(callback: (result: BeaconService) => void): void; + /** + * 关闭蓝牙模块 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=closebluetoothadapter](http://uniapp.dcloud.io/api/system/bluetooth?id=closebluetoothadapter) + */ + closeBluetoothAdapter(options: CloseBluetoothAdapterOptions): void; + /** + * 获取本机蓝牙适配器状态 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothadapterstate](http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothadapterstate) + */ + getBluetoothAdapterState(options: GetBluetoothAdapterStateOptions): void; + /** + * 获取已搜索到的蓝牙设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothdevices](http://uniapp.dcloud.io/api/system/bluetooth?id=getbluetoothdevices) + */ + getBluetoothDevices(options: GetBluetoothDevicesOptions): void; + /** + * 根据uuid获取处于已连接的设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=getconnectedbluetoothdevices](http://uniapp.dcloud.io/api/system/bluetooth?id=getconnectedbluetoothdevices) + */ + getConnectedBluetoothDevices(options: GetConnectedBluetoothDevicesOptions): void; + /** + * 监听蓝牙适配器状态变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothadapterstatechange](http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothadapterstatechange) + */ + onBluetoothAdapterStateChange(callback: (result: OnBluetoothAdapterStateChangeResult) => void): void; + /** + * 监听搜索到新设备的事件 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothdevicefound](http://uniapp.dcloud.io/api/system/bluetooth?id=onbluetoothdevicefound) + */ + onBluetoothDeviceFound(callback: (result: OnBluetoothDeviceFoundResult) => void): void; + /** + * 初始化蓝牙模块 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter](http://uniapp.dcloud.io/api/system/bluetooth?id=openbluetoothadapter) + */ + openBluetoothAdapter(options: OpenBluetoothAdapterOptions): void; + /** + * 开始搜索附近的蓝牙设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=startbluetoothdevicesdiscovery](http://uniapp.dcloud.io/api/system/bluetooth?id=startbluetoothdevicesdiscovery) + */ + startBluetoothDevicesDiscovery(options: StartBluetoothDevicesDiscoveryOptions): void; + /** + * 停止搜寻附近的蓝牙外围设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/bluetooth?id=stopbluetoothdevicesdiscovery](http://uniapp.dcloud.io/api/system/bluetooth?id=stopbluetoothdevicesdiscovery) + */ + stopBluetoothDevicesDiscovery(options: StopBluetoothDevicesDiscoveryOptions): void; + /** + * 断开与低功耗蓝牙设备的连接 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=closebleconnection](http://uniapp.dcloud.io/api/system/ble?id=closebleconnection) + */ + closeBLEConnection(options: CloseBLEConnectionOptions): void; + /** + * 连接低功耗蓝牙设备 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=createbleconnection](http://uniapp.dcloud.io/api/system/ble?id=createbleconnection) + */ + createBLEConnection(options: CreateBLEConnectionOptions): void; + /** + * 获取蓝牙设备指定服务中所有特征值 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=getbledevicecharacteristics](http://uniapp.dcloud.io/api/system/ble?id=getbledevicecharacteristics) + */ + getBLEDeviceCharacteristics(options: GetBLEDeviceCharacteristicsOptions): void; + /** + * 获取蓝牙设备的所有服务 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=getbledeviceservices](http://uniapp.dcloud.io/api/system/ble?id=getbledeviceservices) + */ + getBLEDeviceServices(options: GetBLEDeviceServicesOptions): void; + /** + * 启用低功耗蓝牙设备特征值变化时的notify功能,订阅特征值 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=notifyblecharacteristicvaluechange](http://uniapp.dcloud.io/api/system/ble?id=notifyblecharacteristicvaluechange) + */ + notifyBLECharacteristicValueChange(options: NotifyBLECharacteristicValueChangeOptions): void; + /** + * 监听低功耗蓝牙设备的特征值变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=onblecharacteristicvaluechange](http://uniapp.dcloud.io/api/system/ble?id=onblecharacteristicvaluechange) + */ + onBLECharacteristicValueChange(callback: (result: OnBLECharacteristicValueChangeSuccess) => void): void; + /** + * 监听低功耗蓝牙设备连接状态变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=onbleconnectionstatechange](http://uniapp.dcloud.io/api/system/ble?id=onbleconnectionstatechange) + */ + onBLEConnectionStateChange(callback: (result: OnBLEConnectionStateChangeSuccess) => void): void; + /** + * 读取低功耗蓝牙设备指定特征值的二进制数据值 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=readblecharacteristicvalue](http://uniapp.dcloud.io/api/system/ble?id=readblecharacteristicvalue) + */ + readBLECharacteristicValue(options: ReadBLECharacteristicValueOptions): void; + /** + * 向低功耗蓝牙设备指定特征值写入二进制数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/ble?id=writeblecharacteristicvalue](http://uniapp.dcloud.io/api/system/ble?id=writeblecharacteristicvalue) + */ + writeBLECharacteristicValue(options: WriteBLECharacteristicValueOptions): void; + /** + * 显示消息提示框 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showtoast](http://uniapp.dcloud.io/api/ui/prompt?id=showtoast) + */ + showToast(options: ShowToastOptions): void; + /** + * 显示 loading 提示框 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showloading](http://uniapp.dcloud.io/api/ui/prompt?id=showloading) + */ + showLoading(options: ShowLoadingOptions): void; + /** + * 隐藏消息提示框 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=hidetoast](http://uniapp.dcloud.io/api/ui/prompt?id=hidetoast) + */ + hideToast(): void; + /** + * 隐藏 loading 提示框 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=hideloading](http://uniapp.dcloud.io/api/ui/prompt?id=hideloading) + */ + hideLoading(): void; + /** + * 显示模态弹窗 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showmodal](http://uniapp.dcloud.io/api/ui/prompt?id=showmodal) + */ + showModal(options: ShowModalOptions): void; + /** + * 显示操作菜单 + * + * 参考: [http://uniapp.dcloud.io/api/ui/prompt?id=showactionsheet](http://uniapp.dcloud.io/api/ui/prompt?id=showactionsheet) + */ + showActionSheet(options: ShowActionSheetOptions): void; + /** + * 动态设置当前页面的标题 + * + * 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle](http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbartitle) + */ + setNavigationBarTitle(options: SetNavigationBarTitleOptions): void; + /** + * 在当前页面显示导航条加载动画 + * + * 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=shownavigationbarloading](http://uniapp.dcloud.io/api/ui/navigationbar?id=shownavigationbarloading) + */ + showNavigationBarLoading(): void; + /** + * 隐藏导航条加载动画 + * + * 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=hidenavigationbarloading](http://uniapp.dcloud.io/api/ui/navigationbar?id=hidenavigationbarloading) + */ + hideNavigationBarLoading(): void; + /** + * 设置导航条颜色 + * + * 参考: [http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbarcolor](http://uniapp.dcloud.io/api/ui/navigationbar?id=setnavigationbarcolor) + */ + setNavigationBarColor(options: SetNavigationbarColorOptions): void; + /** + * 动态设置 tabBar 某一项的内容 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbaritem](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbaritem) + */ + setTabBarItem(options: SetTabBarItemOptions): void; + /** + * 动态设置 tabBar 的整体样式 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarstyle](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarstyle) + */ + setTabBarStyle(options: SetTabBarStyleOptions): void; + /** + * 隐藏 tabBar + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbar](http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbar) + */ + hideTabBar(options: HideTabBarOptions): void; + /** + * 显示 tabBar + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbar](http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbar) + */ + showTabBar(options: ShowTabBarOptions): void; + /** + * 为 tabBar 某一项的右上角添加文本 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarbadge](http://uniapp.dcloud.io/api/ui/tabbar?id=settabbarbadge) + */ + setTabBarBadge(options: SetTabBarBadgeOptions): void; + /** + * 移除 tabBar 某一项右上角的文本 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=removetabbarbadge](http://uniapp.dcloud.io/api/ui/tabbar?id=removetabbarbadge) + */ + removeTabBarBadge(options: RemoveTabBarBadgeOptions): void; + /** + * 显示 tabBar 某一项的右上角的红点 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbarreddot](http://uniapp.dcloud.io/api/ui/tabbar?id=showtabbarreddot) + */ + showTabBarRedDot(options: ShowTabBarRedDotOptions): void; + /** + * 隐藏 tabBar 某一项的右上角的红点 + * + * 参考: [http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbarreddot](http://uniapp.dcloud.io/api/ui/tabbar?id=hidetabbarreddot) + */ + hideTabBarRedDot(options: HideTabBarRedDotOptions): void; + /** + * 保留当前页面,跳转到应用内的某个页面 + * + * 参考: [http://uniapp.dcloud.io/api/router?id=navigateto](http://uniapp.dcloud.io/api/router?id=navigateto) + */ + navigateTo(options: NavigateToOptions): void; + /** + * 关闭当前页面,跳转到应用内的某个页面 + * + * 参考: [http://uniapp.dcloud.io/api/router?id=redirectto](http://uniapp.dcloud.io/api/router?id=redirectto) + */ + redirectTo(options: RedirectToOptions): void; + /** + * 关闭所有页面,打开到应用内的某个页面 + * + * 参考: [http://uniapp.dcloud.io/api/router?id=relaunch](http://uniapp.dcloud.io/api/router?id=relaunch) + */ + reLaunch(options: ReLaunchOptions): void; + /** + * 跳转到 tabBar 页面,并关闭其他所有非 tabBar 页面 + * + * 参考: [http://uniapp.dcloud.io/api/router?id=switchtab](http://uniapp.dcloud.io/api/router?id=switchtab) + */ + switchTab(options: SwitchTabOptions): void; + /** + * 关闭当前页面,返回上一页面或多级页面 + * + * 参考: [http://uniapp.dcloud.io/api/router?id=navigateback](http://uniapp.dcloud.io/api/router?id=navigateback) + */ + navigateBack(options: NavigateBackOptions): void; + /** + * 创建一个动画实例 + * + * 参考: [http://uniapp.dcloud.io/api/ui/animation?id=createanimation](http://uniapp.dcloud.io/api/ui/animation?id=createanimation) + */ + createAnimation(options: CreateAnimationOptions): Animation; + /** + * 将页面滚动到目标位置 + * + * 参考: [http://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto](http://uniapp.dcloud.io/api/ui/scroll?id=pagescrollto) + */ + pageScrollTo(options: PageScrollToOptions): void; + /** + * 开始下拉刷新 + * + * 参考: [http://uniapp.dcloud.io/api/ui/pulldown?id=startpulldownrefresh](http://uniapp.dcloud.io/api/ui/pulldown?id=startpulldownrefresh) + */ + startPullDownRefresh(options: StartPullDownRefreshOptions): void; + /** + * 停止当前页面下拉刷新 + * + * 参考: [http://uniapp.dcloud.io/api/ui/pulldown?id=stoppulldownrefresh](http://uniapp.dcloud.io/api/ui/pulldown?id=stoppulldownrefresh) + */ + stopPullDownRefresh(): void; + /** + * 返回一个SelectorQuery对象实例 + * + * 参考: [http://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery](http://uniapp.dcloud.io/api/ui/nodes-info?id=createselectorquery) + */ + createSelectorQuery(): SelectorQuery; + /** + * 创建并返回一个 IntersectionObserver 对象实例 + * + * 参考: [http://uniapp.dcloud.io/api/ui/intersection-observer?id=createintersectionobserver](http://uniapp.dcloud.io/api/ui/intersection-observer?id=createintersectionobserver) + */ + createIntersectionObserver(options: CreateIntersectionObserverOptions): IntersectionObserver; + /** + * 创建 canvas 绘图上下文 + * + * 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=createcanvascontext](http://uniapp.dcloud.io/api/ui/canvas?id=createcanvascontext) + */ + createCanvasContext(canvasId: string, componentInstance: any): CanvasContext; + /** + * 把当前画布指定区域的内容导出生成指定大小的图片 + * + * 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvastotempfilepath](http://uniapp.dcloud.io/api/ui/canvas?id=canvastotempfilepath) + */ + canvasToTempFilePath(options: CanvasToTempFilePathOptions): void; + /** + * 描述 canvas 区域隐含的像素数据 + * + * 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvasgetimagedata](http://uniapp.dcloud.io/api/ui/canvas?id=canvasgetimagedata) + */ + canvasGetImageData(options: CanvasGetImageDataOptions): void; + /** + * 将像素数据绘制到画布 + * + * 参考: [http://uniapp.dcloud.io/api/ui/canvas?id=canvasputimagedata](http://uniapp.dcloud.io/api/ui/canvas?id=canvasputimagedata) + */ + canvasPutImageData(options: CanvasPutImageDataOptions): void; + /** + * 监听窗口尺寸变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/ui/window?id=onwindowresize](http://uniapp.dcloud.io/api/ui/window?id=onwindowresize) + */ + onWindowResize(callback: (result: WindowResizeResult) => void): void; + /** + * 取消监听窗口尺寸变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/ui/window?id=offwindowresize](http://uniapp.dcloud.io/api/ui/window?id=offwindowresize) + */ + offWindowResize(callback: () => void): void; + /** + * 获取服务供应商 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/provider?id=getprovider](http://uniapp.dcloud.io/api/plugins/provider?id=getprovider) + */ + getProvider(options: GetProviderOptions): void; + /** + * 登录 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/login?id=login](http://uniapp.dcloud.io/api/plugins/login?id=login) + */ + login(options: LoginOptions): void; + /** + * 获取用户信息 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/login?id=getuserinfo](http://uniapp.dcloud.io/api/plugins/login?id=getuserinfo) + */ + getUserInfo(options: GetUserInfoOptions): void; + /** + * 分享 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/share?id=share](http://uniapp.dcloud.io/api/plugins/share?id=share) + */ + share(options: ShareOptions): void; + /** + * 开启推送 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/push?id=subscribepush](http://uniapp.dcloud.io/api/plugins/push?id=subscribepush) + */ + subscribePush(options: SubscribePushOptions): void; + /** + * 关闭推送 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/push?id=unsubscribepush](http://uniapp.dcloud.io/api/plugins/push?id=unsubscribepush) + */ + unsubscribePush(options: UnscribePushOptions): void; + /** + * 监听透传数据 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/push?id=onpush](http://uniapp.dcloud.io/api/plugins/push?id=onpush) + */ + onPush(options: OnPushOptions): void; + /** + * 移除监听透传数据 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/push?id=offpush](http://uniapp.dcloud.io/api/plugins/push?id=offpush) + */ + offPush(options: OffPushOptions): void; + /** + * 支付 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/payment?id=requestpayment](http://uniapp.dcloud.io/api/plugins/payment?id=requestpayment) + */ + requestPayment(options: RequestPaymentOptions): void; + /** + * 提前向用户发起授权请求 + * + * 参考: [http://uniapp.dcloud.io/api/other/authorize?id=authorize](http://uniapp.dcloud.io/api/other/authorize?id=authorize) + */ + authorize(options: AuthorizeOptions): void; + /** + * 调起客户端小程序设置界面,返回用户设置的操作结果 + * + * 参考: [http://uniapp.dcloud.io/api/other/authorize?id=opensetting](http://uniapp.dcloud.io/api/other/authorize?id=opensetting) + */ + openSetting(options: OpenSettingOptions): void; + /** + * 获取用户的当前设置 + * + * 参考: [http://uniapp.dcloud.io/api/other/setting?id=getsetting](http://uniapp.dcloud.io/api/other/setting?id=getsetting) + */ + getSetting(options: GetSettingOptions): void; + /** + * 获取用户收货地址。调起用户编辑收货地址原生界面,并在编辑完成后返回用户选择的地址,需要用户授权 scope.address + * + * 参考: [http://uniapp.dcloud.io/api/other/choose-address?id=chooseaddress](http://uniapp.dcloud.io/api/other/choose-address?id=chooseaddress) + */ + chooseAddress(options: ChooseAddressOptions): void; + /** + * 选择用户的发票抬头,需要用户授权 scope.invoiceTitle + * + * 参考: [http://uniapp.dcloud.io/api/other/invoice-title?id=chooseinvoicetitle](http://uniapp.dcloud.io/api/other/invoice-title?id=chooseinvoicetitle) + */ + chooseInvoiceTitle(options: ChooseInvoiceTitleOptions): void; + /** + * 调起客户端小程序设置界面,返回用户设置的操作结果 + * + * 参考: [http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatetominiprogram](http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatetominiprogram) + */ + navigateToMiniProgram(options: NavigateToMiniProgramOptions): void; + /** + * 跳转回上一个小程序,只有当另一个小程序跳转到当前小程序时才会能调用成功 + * + * 参考: [http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatebackminiprogram](http://uniapp.dcloud.io/api/other/open-miniprogram?id=navigatebackminiprogram) + */ + navigateBackMiniProgram(options: NavigateBackMiniProgramOptions): void; + /** + * 返回全局唯一的版本更新管理器对象: updateManager,用于管理小程序更新 + * + * 参考: [http://uniapp.dcloud.io/api/other/update?id=getupdatemanager](http://uniapp.dcloud.io/api/other/update?id=getupdatemanager) + */ + getUpdateManager(): UpdateManager; + /** + * 设置是否打开调试开关。此开关对正式版也能生效 + * + * 参考: [http://uniapp.dcloud.io/api/other/set-enable-debug?id=setenabledebug](http://uniapp.dcloud.io/api/other/set-enable-debug?id=setenabledebug) + */ + setEnableDebug(options: SetEnableDebugOptions): void; + /** + * 获取第三方平台自定义的数据字段 + * + * 参考: [http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfig](http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfig) + */ + getExtConfig(options: GetExtConfigOptions): GetExtConfigRes; + /** + * uni.getExtConfig() 的同步版本 + * + * 参考: [http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfigsync](http://uniapp.dcloud.io/api/other/get-extconfig?id=getextconfigsync) + */ + getExtConfigSync(): GetExtConfigSyncRes; + /** + * 隐藏分享按钮 + * + * 参考: [http://uniapp.dcloud.io/api/plugins/share?id=hidesharemenu](http://uniapp.dcloud.io/api/plugins/share?id=hidesharemenu) + */ + hideShareMenu(options: HideShareMenuOptions): void; + /** + * 动态设置窗口的背景色 + * + * 参考: [http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundcolor](http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundcolor) + */ + setBackgroundColor(options: SetBackgroundColorOptions): void; + /** + * 动态设置窗口的背景色 + * + * 参考: [http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundtextstyle](http://uniapp.dcloud.io/api/ui/bgcolor?id=setbackgroundtextstyle) + */ + setBackgroundTextStyle(options: SetBackgroundTextStyleOptions): void; + /** + * 监听陀螺仪数据变化事件 + * + * 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=ongyroscopechange](http://uniapp.dcloud.io/api/system/gyroscope?id=ongyroscopechange) + */ + onGyroscopeChange(callback: (result: OnGyroscopeChangeSuccess) => void): void; + /** + * 开始监听陀螺仪数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=startgyroscope](http://uniapp.dcloud.io/api/system/gyroscope?id=startgyroscope) + */ + startGyroscope(options: StartGyroscopeOptions): void; + /** + * 停止监听陀螺仪数据 + * + * 参考: [http://uniapp.dcloud.io/api/system/gyroscope?id=stopgyroscope](http://uniapp.dcloud.io/api/system/gyroscope?id=stopgyroscope) + */ + stopGyroscope(options: StopGyroscopeOptions): void; +} + +interface GeneralCallbackResult { + /** + * 错误信息 + */ + errMsg?: string; +} + +interface RequestPaymentOptions { + /** + * 分享服务提供商,通过 uni.getProvider 获取 + */ + provider?: string; + /** + * 订单数据 + */ + orderInfo?: string; + /** + * 时间戳从1970年1月1日至今的秒数,即当前的时间,微信小程序独有 + */ + timeStamp?: string; + /** + * 随机字符串,长度为32个字符以下,微信小程序独有 。 + */ + nonceStr?: string; + /** + * 统一下单接口返回的 prepay_id 参数值,提交格式如:prepay_id=xx,微信小程序独有 + */ + package?: string; + /** + * 签名算法,暂支持 MD5 ,微信小程序独有 + */ + signType?: string; + /** + * 签名,具体签名方案参见小程序支付接口文档,微信小程序独有 + */ + paySign?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface RequestOptions { + /** + * 资源url + */ + url?: string; + /** + * 请求的参数 + */ + data?: string | object | ArrayBuffer; + /** + * 设置请求的 header,header 中不能设置 Referer。 + */ + header?: any; + /** + * 默认为 GET + * 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT + */ + method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'; + /** + * 如果设为json,会尝试对返回的数据做一次 JSON.parse + */ + dataType?: string; + /** + * 设置响应的数据类型。合法值:text、arraybuffer + */ + responseType?: string; + /** + * 成功返回的回调函数 + */ + success?: (result: RequestSuccessCallbackResult) => void; + /** + * 失败的回调函数 + */ + fail?: (result: GeneralCallbackResult) => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: (result: GeneralCallbackResult) => void; +} + +interface RequestSuccessCallbackResult { + /** + * 开发者服务器返回的数据 + */ + data?: string; + /** + * 开发者服务器返回的 HTTP 状态码 + */ + statusCode?: number; + /** + * 开发者服务器返回的 HTTP Response Header + */ + header?: any; +} + +interface RequestTask { + /** + * 中断请求任务 + */ + abort(): void; +} + +interface UploadFileOption { + /** + * 开发者服务器 url + */ + url?: string; + /** + * 文件类型,image/video/audio,仅支付宝小程序,且必填。 + * - image: 图像 + * - video: 视频 + * - audio: 音频 + */ + fileType?: 'image' | 'video' | 'audio'; + /** + * 要上传文件资源的路径 + */ + filePath?: string; + /** + * 文件对应的 key , 开发者在服务器端通过这个 key 可以获取到文件二进制内容 + */ + name?: string; + /** + * 需要上传的文件列表。使用 files 时,filePath 和 name 不生效。仅 5+App 支持 + */ + files?: UploadFileOptionFiles []; + /** + * HTTP 请求 Header, header 中不能设置 Referer + */ + header?: any; + /** + * HTTP 请求中其他额外的 form data + */ + formData?: any; + /** + * 成功返回的回调函数 + */ + success?: (result: UploadFileSuccessCallbackResult) => void; + /** + * 失败的回调函数 + */ + fail?: (result: GeneralCallbackResult) => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: (result: GeneralCallbackResult) => void; +} + +interface UploadFileOptionFiles { + /** + * multipart 提交时,表单的项目名,默认为 file,如果 name 不填或填的值相同,可能导致服务端读取文件时只能读取到一个文件。 + */ + name?: string; + /** + * 要上传文件资源的路径 + */ + uri?: string; +} + +interface UploadTask { + /** + * 监听上传进度变化 + */ + onProgressUpdate(callback: (result: OnProgressUpdateResult) => void): void; + /** + * 中断上传任务 + */ + abort(): void; +} + +interface OnProgressUpdateResult { + /** + * 上传进度百分比 + */ + progress?: number; + /** + * 已经上传的数据长度,单位 Bytes + */ + totalBytesSent?: number; + /** + * 预期需要上传的数据总长度,单位 Bytes + */ + totalBytesExpectedToSend?: number; +} + +interface DownloadFileOption { + /** + * 下载资源的 url + */ + url?: string; + /** + * HTTP 请求 Header,header 中不能设置 Referer + */ + header?: any; + /** + * 下载成功后以 tempFilePath 的形式传给页面,res = {tempFilePath: '文件的临时路径'} + */ + success?: (result: DownloadSuccessData) => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface DownloadTask { + /** + * 监听下载进度变化 + */ + onProgressUpdate(callback: (result: OnProgressDownloadResult) => void): void; + /** + * 中断下载任务 + */ + abort(): void; +} + +interface OnProgressDownloadResult { + /** + * 下载进度百分比 + */ + progress?: number; + /** + * 已经下载的数据长度,单位 Bytes + */ + totalBytesWritten?: number; + /** + * 预期需要下载的数据总长度,单位 Bytes + */ + totalBytesExpectedToWrite?: number; +} + +interface UploadFileSuccessCallbackResult { + /** + * 开发者服务器返回的数据 + */ + data?: string; + /** + * 开发者服务器返回的 HTTP 状态码 + */ + statusCode?: number; +} + +interface DownloadSuccessData { + /** + * 临时文件路径,下载后的文件会存储到一个临时文件 + */ + tempFilePath?: string; + /** + * 开发者服务器返回的 HTTP 状态码 + */ + statusCode?: number; +} + +interface ConnectSocketOption { + /** + * 开发者服务器接口地址,必须是 wss 协议,且域名必须是后台配置的合法域名 + */ + url?: string; + /** + * HTTP 请求 Header,header 中不能设置 Referer + */ + header?: any; + /** + * 默认为 GET + * 可以是:OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT + */ + method?: 'OPTIONS' | 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'TRACE' | 'CONNECT'; + /** + * 子协议数组 + */ + protocols?: string []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SendSocketMessageOptions { + /** + * 需要发送的内容 + */ + data?: string | ArrayBuffer; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GeneralCallbackResult) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: (result: GeneralCallbackResult) => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: (result: GeneralCallbackResult) => void; +} + +interface CloseSocketOptions { + /** + * 一个数字值表示关闭连接的状态号,表示连接被关闭的原因。如果这个参数没有被指定,默认的取值是1000 (表示正常连接关闭) + */ + code?: number; + /** + * 一个可读的字符串,表示连接被关闭的原因。这个字符串必须是不长于123字节的UTF-8 文本(不是字符) + */ + reason?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GeneralCallbackResult) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: (result: GeneralCallbackResult) => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: (result: GeneralCallbackResult) => void; +} + +interface SocketTask { + /** + * 通过 WebSocket 连接发送数据 + */ + send(options: SendSocketMessageOptions): void; + /** + * 关闭 WebSocket 连接 + */ + close(options: CloseSocketOptions): void; + /** + * 监听 WebSocket 连接打开事件 + */ + onOpen(callback: (result: OnSocketOpenCallbackResult) => void): void; + /** + * 监听 WebSocket 连接关闭事件 + */ + onClose(callback: () => void): void; + /** + * 监听 WebSocket 错误 + */ + onError(callback: (result: GeneralCallbackResult) => void): void; + /** + * 监听WebSocket接受到服务器的消息事件 + */ + onMessage(callback: (result: OnSocketMessageCallbackResult) => void): void; +} + +interface OnSocketMessageCallbackResult { + /** + * 服务器返回的消息 + */ + data?: string | ArrayBuffer; +} + +interface OnSocketOpenCallbackResult { + /** + * 连接成功的 HTTP 响应 Header + */ + header?: any; +} + +interface ChooseImageOptions { + /** + * 最多可以选择的图片张数,默认9 + */ + count?: number; + /** + * original 原图,compressed 压缩图,默认二者都有 + */ + sizeType?: string | string []; + /** + * album 从相册选图,camera 使用相机,默认二者都有 + */ + sourceType?: string | string []; + /** + * 成功则返回图片的本地文件路径列表 tempFilePaths + */ + success?: (result: ChooseImageSuccessCallbackResult) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseImageSuccessCallbackResult { + /** + * 图片的本地文件路径列表 + */ + tempFilePaths?: string | any []; + /** + * 图片的本地文件列表,每一项是一个 File 对象 + */ + tempFiles?: ChooseImageSuccessCallbackResultFile | ChooseImageSuccessCallbackResultFile []; +} + +interface ChooseImageSuccessCallbackResultFile { + /** + * 本地文件路径 + */ + path?: string; + /** + * 本地文件大小,单位:B + */ + size?: number; +} + +interface PreviewImageOptions { + /** + * 当前显示图片的链接,不填则默认为 urls 的第一张 + */ + count?: string; + /** + * 需要预览的图片链接列表 + */ + urls?: string | any []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetImageInfoOptions { + /** + * 图片的路径,可以是相对路径,临时文件路径,存储文件路径,网络图片路径 + */ + src?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetImageInfoSuccessData) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetImageInfoSuccessData { + /** + * 图片宽度,单位px + */ + width?: number; + /** + * 图片高度,单位px + */ + height?: number; + /** + * 返回图片的本地路径 + */ + path?: string; + /** + * 返回图片的方向 + */ + orientation?: string; + /** + * 返回图片的格式 + */ + type?: string; +} + +interface SaveImageToPhotosAlbumOptions { + /** + * 图片文件路径,可以是临时文件路径也可以是永久文件路径,不支持网络图片路径 + */ + filePath?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StartRecordOptions { + /** + * 录音成功后调用,返回录音文件的临时文件路径,res = {tempFilePath: '录音文件的临时路径'} + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface RecorderManager { + /** + * 开始录音 + */ + start(options: RecorderManagerStartOptions): void; + /** + * 暂停录音 + */ + pause(): void; + /** + * 暂停录音 + */ + resume(): void; + /** + * 停止录音 + */ + stop(): void; + /** + * 录音开始事件 + */ + onStart(options: () => void): void; + /** + * 录音暂停事件 + */ + onPause(options: () => void): void; + /** + * 录音停止事件,会回调文件地址 + */ + onStop(options: () => void): void; + /** + * 已录制完指定帧大小的文件,会回调录音分片结果数据。如果设置了 frameSize ,则会回调此事件 + */ + onFrameRecorded(options: () => void): void; + /** + * 录音错误事件, 会回调错误信息 + */ + onError(options: () => void): void; +} + +interface RecorderManagerStartOptions { + /** + * 指定录音的时长,单位 ms ,如果传入了合法的 duration ,在到达指定的 duration 后会自动停止录音,最大值 600000(10 分钟),默认值 60000(1 分钟) + */ + duration?: number; + /** + * 采样率,有效值 8000/16000/44100 + */ + sampleRate?: number; + /** + * 录音通道数,有效值 1/2 + */ + numberOfChannels?: number; + /** + * 编码码率,有效值见下表格 + */ + encodeBitRate?: number; + /** + * 音频格式,有效值 aac/mp3 + */ + format?: string; + /** + * 指定帧大小,单位 KB。传入 frameSize 后,每录制指定帧大小的内容后,会回调录制的文件内容,不指定则不会回调。暂仅支持 mp3 格式。 + */ + frameSize?: number; +} + +interface PlayVoiceOptions { + /** + * 需要播放的语音文件的文件路径 + */ + filePath?: string; + /** + * original 原图,compressed 压缩图,默认二者都有 + */ + duration?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBackgroundAudioPlayerStateOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetBackgroundAudioPlayerStateSuccessData) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBackgroundAudioPlayerStateSuccessData { + /** + * 选定音频的长度(单位:s),只有在当前有音乐播放时返回 + */ + duration?: number; + /** + * 选定音频的播放位置(单位:s),只有在当前有音乐播放时返回 + */ + currentPosition?: number; + /** + * 播放状态(2:没有音乐在播放,1:播放中,0:暂停中) + */ + status?: number; + /** + * 音频的下载进度(整数,80 代表 80%),只有在当前有音乐播放时返回 + */ + downloadPercent?: number; + /** + * 歌曲数据链接,只有在当前有音乐播放时返回 + */ + dataUrl?: string; +} + +interface GetBackgroundAudioOptions { + /** + * 音乐链接,目前支持的格式有 m4a, aac, mp3, wav + */ + dataUrl?: string; + /** + * 音乐标题 + */ + title?: string; + /** + * 封面url + */ + coverImgUrl?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SeekBackgroundAudioOptions { + /** + * 音乐位置,单位:秒 + */ + position?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface BackgroundAudioManager { + /** + * 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 + */ + duration?: number; + /** + * 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 + */ + currentTime?: number; + /** + * 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 + */ + paused?: boolean; + /** + * 音频的数据源,默认为空字符串,当设置了新的 src 时,会自动开始播放 ,目前支持的格式有 m4a, aac, mp3, wav + */ + src?: string; + /** + * 音频开始播放的位置(单位:s) + */ + startTime?: number; + /** + * 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲 + */ + buffered?: number; + /** + * 音频标题,用于做原生音频播放器音频标题。原生音频播放器中的分享功能,分享出去的卡片标题,也将使用该值。 + */ + title?: string; + /** + * 专辑名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 + */ + epname?: string; + /** + * 歌手名,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 + */ + singer?: string; + /** + * 封面图url,用于做原生音频播放器背景图。原生音频播放器中的分享功能,分享出去的卡片配图及背景也将使用该图。 + */ + coverImgUrl?: string; + /** + * 页面链接,原生音频播放器中的分享功能,分享出去的卡片简介,也将使用该值 + */ + webUrl?: string; + /** + * 音频协议。默认值为 'http',设置 'hls' 可以支持播放 HLS 协议的直播音频 + */ + protocol?: string; + /** + * 播放 + */ + play(): void; + /** + * 暂停 + */ + pause(): void; + /** + * 跳转到指定位置,单位 s + */ + seek(): void; + /** + * 停止 + */ + stop(): void; + /** + * 背景音频进入可以播放状态,但不保证后面可以流畅播放 + */ + onCanplay(callback: () => void): void; + /** + * 背景音频播放事件 + */ + onPlay(callback: () => void): void; + /** + * 背景音频暂停事件 + */ + onPause(callback: () => void): void; + /** + * 背景音频停止事件 + */ + onStop(callback: () => void): void; + /** + * 背景音频自然播放结束事件 + */ + onEnded(callback: () => void): void; + /** + * 背景音频播放进度更新事件 + */ + onTimeUpdate(callback: () => void): void; + /** + * 用户在系统音乐播放面板点击上一曲事件(iOS only) + */ + onPrev(callback: () => void): void; + /** + * 用户在系统音乐播放面板点击下一曲事件(iOS only) + */ + onNext(callback: () => void): void; + /** + * 背景音频播放错误事件 + */ + onNext(callback: () => void): void; + /** + * 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 + */ + onWaiting(callback: () => void): void; +} + +interface CreateAudioContext { + /** + * 音频的地址 + */ + setSrc(): void; + /** + * 暂停 + */ + pause(): void; + /** + * 播放 + */ + play(): void; + /** + * 跳转到指定位置,单位 s + */ + seek(): void; +} + +interface CreateInnerAudioContext { + /** + * 当前音频的长度(单位:s),只有在当前有合法的 src 时返回 + */ + duration?: number; + /** + * 当前音频的播放位置(单位:s),只有在当前有合法的 src 时返回 + */ + currentTime?: number; + /** + * 当前是是否暂停或停止状态,true 表示暂停或停止,false 表示正在播放 + */ + paused?: boolean; + /** + * 音频的数据链接,用于直接播放。 + */ + src?: string; + /** + * 音频开始播放的位置(单位:s) + */ + startTime?: number; + /** + * 音频缓冲的时间点,仅保证当前播放时间点到此时间点内容已缓冲 + */ + buffered?: number; + /** + * 是否自动开始播放,默认 false + */ + autoplay?: boolean; + /** + * 是否循环播放,默认 false + */ + loop?: boolean; + /** + * 是否遵循系统静音开关,当此参数为 false 时,即使用户打开了静音开关,也能继续发出声音,默认值 true + */ + obeyMuteSwitch?: boolean; + /** + * 音量。范围 0~1。 + */ + volume?: number; + /** + * 暂停 + */ + pause(): void; + /** + * 停止 + */ + stop(): void; + /** + * 播放 + */ + play(): void; + /** + * 跳转到指定位置,单位 s + */ + seek(): void; + /** + * 销毁当前实例 + */ + destroy(): void; + /** + * 音频进入可以播放状态,但不保证后面可以流畅播放 + */ + onCanplay(callback: () => void): void; + /** + * 音频播放事件 + */ + onPlay(callback: () => void): void; + /** + * 音频暂停事件 + */ + onPause(callback: () => void): void; + /** + * 音频停止事件 + */ + onStop(callback: () => void): void; + /** + * 音频自然播放结束事件 + */ + onEnded(callback: () => void): void; + /** + * 音频播放进度更新事件 + */ + onTimeUpdate(callback: () => void): void; + /** + * 音频播放错误事件 + */ + onError(callback: () => void): void; + /** + * 音频加载中事件,当音频因为数据不足,需要停下来加载时会触发 + */ + onWaiting(callback: () => void): void; + /** + * 音频进行 seek 操作事件 + */ + onSeeking(callback: () => void): void; + /** + * 音频完成 seek 操作事件 + */ + onSeeked(callback: () => void): void; + /** + * 取消监听 onCanplay 事件 + */ + offCanplay(callback: () => void): void; + /** + * 取消监听 onPlay 事件 + */ + offPlay(callback: () => void): void; + /** + * 取消监听 onPause 事件 + */ + offPause(callback: () => void): void; + /** + * 取消监听 onStop 事件 + */ + offStop(callback: () => void): void; + /** + * 取消监听 onEnded 事件 + */ + offEnded(callback: () => void): void; + /** + * 取消监听 onTimeUpdate 事件 + */ + offTimeUpdate(callback: () => void): void; + /** + * 取消监听 onWaiting 事件 + */ + offError(callback: () => void): void; + /** + * 取消监听 onWaiting 事件 + */ + offWaiting(callback: () => void): void; + /** + * 取消监听 onSeeking 事件 + */ + offSeeking(callback: () => void): void; + /** + * 取消监听 onSeeked 事件 + */ + offSeeked(callback: () => void): void; +} + +interface ChooseVideoOptions { + /** + * album 从相册选视频,camera 使用相机拍摄,默认为:['album', 'camera'] + */ + sourceType?: string | any []; + /** + * 是否压缩所选的视频源文件,默认值为true,需要压缩 + */ + compressed?: boolean; + /** + * 拍摄视频最长拍摄时间,单位秒。最长支持 60 秒 + */ + maxDuration?: number; + /** + * 接口调用成功,返回视频文件的临时文件路径,详见返回参数说明 + */ + success?: (result: ChooseVideoSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SaveVideoToPhotosAlbumOptions { + /** + * 视频文件路径,可以是临时文件路径也可以是永久文件路径 + */ + filePath?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseVideoSuccess { + /** + * 临时文件路径,下载后的文件会存储到一个临时文件 + */ + tempFilePath?: string; + /** + * 选定视频的时间长度 + */ + duration?: number; + /** + * 选定视频的数据量大小 + */ + size?: number; + /** + * 返回选定视频的长 + */ + height?: number; + /** + * 返回选定视频的宽 + */ + width?: number; +} + +interface VideoContext { + /** + * 暂停 + */ + pause(): void; + /** + * 播放 + */ + play(): void; + /** + * 跳转到指定位置,单位 s + */ + seek(): void; + /** + * 发送弹幕,danmu 包含两个属性 text, color。 + */ + sendDanmu(): void; + /** + * 设置倍速播放,支持的倍率有 0.5/0.8/1.0/1.25/1.5 + */ + playbackRate(): void; + /** + * 进入全屏,可传入{direction}参数(1.7.0起支持),详见video组件文档 + */ + requestFullScreen(): void; + /** + * 退出全屏 + */ + exitFullScreen(): void; +} + +interface CameraContext { + /** + * 拍照,可指定质量,成功则返回图片 + */ + takePhoto(options: CameraContextTakePhotoOptions): void; + /** + * 开始录像 + */ + startRecord(options: CameraContextStartRecordOptions): void; + /** + * 结束录像,成功则返回封面与视频 + */ + stopRecord(options: CameraContextStopRecordOptions): void; +} + +interface CameraContextTakePhotoOptions { + /** + * 成像质量,值为high, normal, low,默认normal + */ + quality?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CameraContextStartRecordOptions { + /** + * 超过30s或页面onHide时会结束录像,res = { tempThumbPath, tempVideoPath } + */ + timeoutCallback?: () => void; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CameraContextStopRecordOptions { + /** + * 接口调用成功的回调函数 ,res = { tempThumbPath, tempVideoPath } + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SaveFileOptions { + /** + * 需要保存的文件的临时路径 + */ + tempFilePath?: string; + /** + * 返回文件的保存路径,res = {savedFilePath: '文件的保存路径'} + */ + success?: (result: SaveFileSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SaveFileSuccess { + /** + * 文件的保存路径 + */ + savedFilePath?: string; +} + +interface GetFileInfoOptions { + /** + * 本地路径 + */ + filePath?: string; + /** + * 计算文件摘要的算法,默认值 md5,有效值:md5,sha1 + */ + digestAlgorithm?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetFileInfoSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetFileInfoSuccess { + /** + * 文件大小,单位:B + */ + size?: number; + /** + * 按照传入的 digestAlgorithm 计算得出的的文件摘要 + */ + digest?: string; + /** + * 调用结果 + */ + errMsg?: string; +} + +interface GetSavedFileListOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetSavedFileListSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetSavedFileListSuccess { + /** + * 接口调用结果 + */ + errMsg?: number; + /** + * 文件列表 + */ + fileList?: string; +} + +interface GetSavedFileInfoOptions { + /** + * 文件路径 + */ + filePath?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetSavedFileInfoSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetSavedFileInfoSuccess { + /** + * 接口调用结果 + */ + errMsg?: string; + /** + * 文件大小,单位B + */ + size?: number; + /** + * 文件保存时的时间戳,从1970/01/01 08:00:00 到该时刻的秒数 + */ + createTime?: number; +} + +interface RemoveSavedFileOptions { + /** + * 文件路径 + */ + filePath?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OpenDocumentOptions { + /** + * 文件路径 + */ + filePath?: string; + /** + * 文件类型,指定文件类型打开文件,有效值 doc, xls, ppt, pdf, docx, xlsx, pptx + */ + fileType?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetStorageOptions { + /** + * 本地缓存中的指定的 key + */ + key?: string; + /** + * 需要存储的内容 + */ + data?: object | string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetStorageOptions { + /** + * 本地缓存中的指定的 key + */ + key?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetStorageInfoOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetStorageInfoSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetStorageInfoSuccess { + /** + * 当前storage中所有的key + */ + keys?: string | any []; + /** + * 当前占用的空间大小, 单位kb + */ + currentSize?: number; + /** + * 限制的空间大小,单位kb + */ + limitSize?: number; +} + +interface RemoveStorageOptions { + /** + * 本地缓存中的指定的 key + */ + key?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetLocationOptions { + /** + * 默认为 wgs84 返回 gps 坐标,gcj02 返回可用于uni.openLocation的坐标 + */ + type?: string; + /** + * 传入 true 会返回高度信息,由于获取高度需要较高精确度,会减慢接口返回速度 + */ + altitude?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetLocationSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetLocationSuccess { + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude?: number; + /** + * 经度,范围为-180~180,负数表示西经 + */ + longitude?: number; + /** + * 速度,浮点数,单位m/s + */ + speed?: number; + /** + * 位置的精确度 + */ + accuracy?: string; + /** + * 高度,单位 m + */ + altitude?: number; + /** + * 垂直精度,单位 m(Android 无法获取,返回 0) + */ + verticalAccuracy?: number; + /** + * 水平精度,单位 m + */ + horizontalAccuracy?: number; +} + +interface ChooseLocationOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: ChooseLocationSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseLocationSuccess { + /** + * 位置名称 + */ + name?: string; + /** + * 详细地址 + */ + address?: string; + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude?: number; + /** + * 经度,范围为-180~180,负数表示西经 + */ + longitude?: number; +} + +interface OpenLocationOptions { + /** + * 纬度,范围为-90~90,负数表示南纬 + */ + latitude?: number; + /** + * 经度,范围为-180~180,负数表示西经 + */ + longitude?: number; + /** + * 缩放比例,范围5~18,默认为18 + */ + scale?: number; + /** + * 位置名称 + */ + name?: string; + /** + * 地址的详细说明 + */ + address?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface MapContext { + /** + * 获取当前地图中心的经纬度,返回的是 gcj02 坐标系,可以用于 uni.openLocation + */ + getCenterLocation(options: MapContextGetCenterLocationOptions): void; + /** + * 将地图中心移动到当前定位点,需要配合map组件的show-location使用 + */ + moveToLocation(): void; + /** + * 平移marker,带动画 + */ + translateMarker(options: MapContextTranslateMarkerOptions): void; + /** + * 缩放视野展示所有经纬度 + */ + includePoints(options: MapContextIncludePointsOptions): void; + /** + * 获取当前地图的视野范围 + */ + getRegion(options: MapContextGetRegionOptions): void; + /** + * 获取当前地图的缩放级别 + */ + getScale(options: MapContextGetScaleOptions): void; +} + +interface MapContextGetCenterLocationOptions { + /** + * 接口调用成功的回调函数 ,res = { longitude: "经度", latitude: "纬度"} + */ + success?: (result: MapContextGetLocationSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface MapContextGetLocationSuccess { + /** + * 纬度,浮点数,范围为-90~90,负数表示南纬 + */ + latitude?: number; + /** + * 经度,范围为-180~180,负数表示西经 + */ + longitude?: number; +} + +interface MapContextTranslateMarkerOptions { + /** + * 指定marker + */ + markerId?: number; + /** + * 指定marker移动到的目标点 + */ + destination?: any; + /** + * 移动过程中是否自动旋转marker + */ + autoRotate?: boolean; + /** + * marker的旋转角度 + */ + rotate?: number; + /** + * 动画持续时长,默认值1000ms,平移与旋转分别计算 + */ + duration?: number; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 动画结束回调函数 + */ + animationEnd?: () => void; +} + +interface MapContextIncludePointsOptions { + /** + * 要显示在可视区域内的坐标点列表,[{latitude, longitude}] + */ + points?: any []; + /** + * 坐标点形成的矩形边缘到地图边缘的距离,单位像素。格式为[上,右,下,左],安卓上只能识别数组第一项,上下左右的padding一致。开发者工具暂不支持padding参数。 + */ + padding?: any []; +} + +interface MapContextGetRegionOptions { + /** + * 接口调用成功的回调函数,res = {southwest, northeast},西南角与东北角的经纬度 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface MapContextGetScaleOptions { + /** + * 接口调用成功的回调函数,res = {scale} + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetSystemInfoOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetSystemInfoSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetSystemInfoSuccess { + /** + * 手机品牌 + */ + brand?: string; + /** + * 手机型号 + */ + model?: string; + /** + * 设备像素比 + */ + pixelRatio?: string; + /** + * 屏幕宽度 + */ + screenWidth?: number; + /** + * 屏幕高度 + */ + screenHeight?: number; + /** + * 可使用窗口宽度 + */ + windowWidth?: number; + /** + * 可使用窗口高度 + */ + windowHeight?: number; + /** + * 状态栏的高度 + */ + statusBarHeight?: number; + /** + * 程序设置的语言 + */ + language?: string; + /** + * 5+版本号 + */ + version?: number; + /** + * 操作系统版本 + */ + system?: string; + /** + * 客户端平台 + */ + platform?: string; + /** + * 用户字体大小设置 + */ + fontSizeSetting?: number; +} + +interface GetNetworkTypeOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetNetworkTypeSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetNetworkTypeSuccess { + /** + * 网络类型 + */ + networkType?: string; +} + +interface OnNetworkStatusChangeSuccess { + /** + * 当前是否有网络连接 + */ + isConnected?: number; + /** + * 网络类型 + */ + networkType?: string; +} + +interface OnAccelerometerChangeSuccess { + /** + * X 轴 + */ + x?: number; + /** + * Y 轴 + */ + y?: number; + /** + * Z 轴 + */ + z?: number; +} + +interface StartAccelerometerOptions { + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopAccelerometerOptions { + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OnCompassChangeSuccess { + /** + * 面对的方向度数 + */ + direction?: number; +} + +interface StartCompassOptions { + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopCompassOptions { + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface MakePhoneCallOptions { + /** + * 需要拨打的电话号码 + */ + phoneNumber?: string; + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ScanCodeOptions { + /** + * 是否只能从相机扫码,不允许从相册选择图片 + */ + onlyFromCamera?: boolean; + /** + * 扫码类型,参数类型是数组,二维码是'qrCode',一维码是'barCode',DataMatrix是‘datamatrix’,pdf417是‘pdf417’。 + */ + scanType?: any []; + /** + * 成功返回的回调函数 + */ + success?: (result: ScanCodeSuccessRes) => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ScanCodeSuccessRes { + /** + * 所扫码的内容 + */ + result?: string; + /** + * 所扫码的类型 + */ + scanType?: string; + /** + * 所扫码的字符集 + */ + charSet?: string; + /** + * 当所扫的码为当前应用的合法二维码时,会返回此字段,内容为二维码携带的 path。 + */ + path?: string; +} + +interface SetClipboardDataOptions { + /** + * 需要设置的内容 + */ + data?: string; + /** + * 成功返回的回调函数 + */ + success?: () => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetClipboardDataOptions { + /** + * 成功返回的回调函数 + */ + success?: (result: GetClipboardDataSuccessRes) => void; + /** + * 失败的回调函数 + */ + fail?: () => void; + /** + * 结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetClipboardDataSuccessRes { + /** + * 剪贴板的内容 + */ + data?: string; +} + +interface OpenBluetoothAdapterOptions { + /** + * 成功则返回成功初始化信息 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CloseBluetoothAdapterOptions { + /** + * 成功则返回成功关闭模块信息 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBluetoothAdapterStateOptions { + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: GetBluetoothAdapterStateSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBluetoothAdapterStateSuccess { + /** + * 是否正在搜索设备 + */ + discovering?: boolean; + /** + * 蓝牙适配器是否可用 + */ + available?: boolean; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface OnBluetoothAdapterStateChangeResult { + /** + * 是否正在搜索设备 + */ + discovering?: boolean; + /** + * 蓝牙适配器是否可用 + */ + available?: boolean; +} + +interface OnBluetoothDeviceFoundResult { + /** + * 设备列表信息 + */ + devices?: BluetoothDeviceInfo []; +} + +interface StartBluetoothDevicesDiscoveryOptions { + /** + * 蓝牙设备主 service 的 uuid 列表 + */ + services?: any []; + /** + * 是否允许重复上报同一设备, 如果允许重复上报,则onDeviceFound 方法会多次上报同一设备,但是 RSSI 值会有不同 + */ + allowDuplicatesKey?: boolean; + /** + * 上报设备的间隔,默认为0,意思是找到新设备立即上报,否则根据传入的间隔上报 + */ + interval?: number; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopBluetoothDevicesDiscoveryOptions { + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: StopBluetoothDevicesDiscoverySuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopBluetoothDevicesDiscoverySuccess { + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface GetBluetoothDevicesOptions { + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: GetBluetoothDevicesSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBluetoothDevicesSuccess { + /** + * uuid 对应的的已连接设备列表 + */ + devices?: BluetoothDeviceInfo []; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface BluetoothDeviceInfo { + /** + * 蓝牙设备名称,某些设备可能没有 + */ + name?: string; + /** + * 用于区分设备的 id + */ + deviceId?: string; + /** + * 当前蓝牙设备的信号强度 + */ + RSSI?: number; + /** + * 当前蓝牙设备的广播数据段中的ManufacturerData数据段 (注意:vConsole 无法打印出 ArrayBuffer 类型数据) + */ + advertisData?: any []; + /** + * 当前蓝牙设备的广播数据段中的ServiceUUIDs数据段 + */ + advertisServiceUUIDs?: any []; + /** + * 当前蓝牙设备的广播数据段中的LocalName数据段 + */ + localName?: string; + /** + * 当前蓝牙设备的广播数据段中的ServiceData数据段 + */ + serviceData?: any []; +} + +interface GetConnectedBluetoothDevicesOptions { + /** + * 蓝牙设备主 service 的 uuid 列表 + */ + services?: any []; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: GetConnectedBluetoothDevicesSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetConnectedBluetoothDevicesSuccess { + /** + * 搜索到的设备列表 + */ + devices?: GetConnectedBluetoothDevicesSuccessData []; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface GetConnectedBluetoothDevicesSuccessData { + /** + * 蓝牙设备名称,某些设备可能没有 + */ + name?: string; + /** + * 用于区分设备的 id + */ + deviceId?: string; +} + +interface CloseBLEConnectionOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; +} + +interface CreateBLEConnectionOptions { + /** + * 蓝牙设备 id,参考 getDevices 接口 + */ + deviceId?: string; + /** + * 超时时间 + */ + timeout?: number; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OnBLEConnectionStateChangeSuccess { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 连接目前的状态 + */ + connected?: boolean; +} + +interface GetBLEDeviceServicesOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: GetBLEDeviceServicesSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBLEDeviceServicesSuccess { + /** + * 设备服务列表 + */ + services?: GetBLEDeviceServicesSuccessData []; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface GetBLEDeviceServicesSuccessData { + /** + * 蓝牙设备服务的 uuid + */ + uuid?: string; + /** + * 该服务是否为主服务 + */ + isPrimary?: boolean; +} + +interface GetBLEDeviceCharacteristicsOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 蓝牙服务 uuid + */ + serviceId?: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: GetBLEDeviceCharacteristicsSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBLEDeviceCharacteristicsSuccess { + /** + * 设备特征值列表 + */ + characteristics?: GetBLEDeviceCharacteristicsSuccessData []; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface GetBLEDeviceCharacteristicsSuccessData { + /** + * 蓝牙设备服务的 uuid + */ + uuid?: string; + /** + * 该特征值支持的操作类型 + */ + properties?: any; +} + +interface ReadBLECharacteristicValueOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId?: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId?: string; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: ReadBLECharacteristicValueSuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ReadBLECharacteristicValueSuccess { + /** + * 错误码 + */ + errCode?: string; + /** + * 成功:ok,错误:详细信息 + */ + errMsg?: string; +} + +interface WriteBLECharacteristicValueOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId?: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId?: string; + /** + * 蓝牙设备特征值对应的二进制值 + */ + value?: any []; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: StopBluetoothDevicesDiscoverySuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface NotifyBLECharacteristicValueChangeOptions { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId?: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId?: string; + /** + * true: 启用 notify; false: 停用 notify + */ + state?: boolean; + /** + * 成功则返回本机蓝牙适配器状态 + */ + success?: (result: StopBluetoothDevicesDiscoverySuccess) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OnBLECharacteristicValueChangeSuccess { + /** + * 蓝牙设备 id,参考 device 对象 + */ + deviceId?: string; + /** + * 蓝牙特征值对应服务的 uuid + */ + serviceId?: string; + /** + * 蓝牙特征值的 uuid + */ + characteristicId?: string; + /** + * 特征值最新的值 (注意:vConsole 无法打印出 ArrayBuffer 类型数据) + */ + value?: any []; +} + +interface StartBeaconDiscoveryOptions { + /** + * iBeacon设备广播的 uuids + */ + uuids?: any []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopBeaconDiscoveryOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBeaconsOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetBeaconsRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetBeaconsRes { + /** + * 接口调用成功的回调函数 + */ + beacons?: Beacon []; + /** + * 调用结果 + */ + errMsg?: string; +} + +interface Beacon { + /** + * iBeacon 设备广播的 uuid + */ + uuid?: string; + /** + * iBeacon 设备的主 id + */ + major?: string; + /** + * iBeacon 设备的次 id + */ + minor?: string; + /** + * 表示设备距离的枚举值 + */ + proximity?: number; + /** + * iBeacon 设备的距离 + */ + accuracy?: number; + /** + * 表示设备的信号强度 + */ + rssi?: number; +} + +interface BeaconService { + /** + * 服务目前是否可用 + */ + available?: boolean; + /** + * 目前是否处于搜索状态 + */ + discovering?: boolean; +} + +interface GetHCEStateOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StartHCEOptions { + /** + * 需要注册到系统的 AID 列表,每个 AID 为 String 类型 + */ + aid_list?: any []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopHCEOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface HCEMessageRes { + /** + * 消息类型 + */ + messageType?: number; + /** + * 客户端接收到 NFC 设备的指令 + */ + data?: any []; + /** + * 此参数当且仅当 messageType=2 时有效 + */ + reason?: number; +} + +interface SendHCEMessageOptions { + /** + * 二进制数据 + */ + data?: any []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StartWifiOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopWifiOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ConnectWifiOptions { + /** + * Wi-Fi 设备ssid + */ + SSID?: string; + /** + * Wi-Fi 设备bssid + */ + BSSID?: string; + /** + * Wi-Fi 设备密码 + */ + password?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetWifiListOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface WiFi { + /** + * Wi-Fi 的SSID + */ + SSID?: string; + /** + * Wi-Fi 的BSSID + */ + BSSID?: string; + /** + * Wi-Fi 是否安全 + */ + secure?: boolean; + /** + * Wi-Fi 信号强度 + */ + signalStrength?: number; +} + +interface SetWifiListOptions { + /** + * Wi-Fi 的SSID + */ + wifiList?: WiFiItem []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface WiFiItem { + /** + * Wi-Fi 的SSID + */ + SSID?: string; + /** + * Wi-Fi 的BSSID + */ + BSSID?: string; + /** + * Wi-Fi 设备密码 + */ + password?: string; +} + +interface GetConnectedWifiOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetConnectedWifiRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetConnectedWifiRes { + /** + * 接口调用成功的回调函数 + */ + wifi?: WiFi; +} + +interface ShowToastOptions { + /** + * 提示的内容 + */ + title?: string; + /** + * 图标 + * - success: 显示成功图标 + * - loading: 显示加载图标 + * - none: 不显示图标 + */ + icon?: 'success' | 'loading' | 'none'; + /** + * 自定义图标的本地路径,image 的优先级高于 icon + */ + image?: string; + /** + * 提示的延迟时间,单位毫秒,默认:1500 + */ + duration?: number; + /** + * 是否显示透明蒙层,防止触摸穿透,默认:false + */ + mask?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowLoadingOptions { + /** + * 提示的内容 + */ + title?: string; + /** + * 是否显示透明蒙层,防止触摸穿透,默认:false + */ + mask?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowModalOptions { + /** + * 提示的标题 + */ + title?: string; + /** + * 提示的内容 + */ + content?: string; + /** + * 是否显示取消按钮,默认为 true + */ + showCancel?: boolean; + /** + * 取消按钮的文字,默认为"取消" + */ + cancelText?: string; + /** + * 取消按钮的文字颜色,默认为"#000000" + */ + cancelColor?: string; + /** + * 确定按钮的文字,默认为"确定" + */ + confirmText?: string; + /** + * 确定按钮的文字颜色,默认为"#3CC51F" + */ + confirmColor?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: ShowModalRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowModalRes { + /** + * 为 true 时,表示用户点击了确定按钮 + */ + confirm?: boolean; + /** + * 为 true 时,表示用户点击了取消 + */ + cancel?: boolean; +} + +interface ShowActionSheetOptions { + /** + * 按钮的文字数组 + */ + itemList?: any []; + /** + * 按钮的文字颜色,默认为"#000000" + */ + itemColor?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: ShowActionSheetRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowActionSheetRes { + /** + * 用户点击的按钮,从上到下的顺序,从0开始 + */ + tapIndex?: number; +} + +interface SetNavigationBarTitleOptions { + /** + * 页面标题 + */ + title?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetNavigationbarColorOptions { + /** + * 前景颜色值,包括按钮、标题、状态栏的颜色 + */ + frontColor?: string; + /** + * 背景颜色值,有效值为十六进制颜色 + */ + backgroundColor?: string; + /** + * 动画效果 + */ + animation?: NavigationBarAnimation; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetTabBarBadgeOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 显示的文本,不超过 3 个半角字符 + */ + text?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface RemoveTabBarBadgeOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowTabBarRedDotOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface HideTabBarRedDotOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface NavigationBarAnimation { + /** + * 动画变化时间,默认0,单位:毫秒 + */ + duration?: number; + /** + * 动画变化方式,默认 linear + * - linear: 动画从头到尾的速度是相同的 + * - easeIn: 动画以低速开始 + * - easeOut: 动画以低速结束 + * - easeInOut: 动画以低速开始和结束 + */ + timingFunc?: 'linear' | 'easeIn' | 'easeOut' | 'easeInOut'; +} + +interface WindowResizeResult { + /** + * 变化后的窗口宽度,单位 px + */ + windowWidth?: number; + /** + * 变化后的窗口高度,单位 px + */ + windowHeight?: number; +} + +interface SetTabBarBadgeOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 显示的文本 + */ + text?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface RemoveTabBarBadgeOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowTabBarRedDotOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface HideTabBarRedDotOptions { + /** + * tabBar的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetTabBarStyleOptions { + /** + * tab 上的文字默认颜色 + */ + color?: string; + /** + * tab 上的文字选中时的颜色 + */ + selectedColor?: string; + /** + * tab 的背景色 + */ + backgroundColor?: string; + /** + * tabbar上边框的颜色 + */ + borderStyle?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetTabBarItemOptions { + /** + * tabBar 的哪一项,从左边算起,索引从0开始 + */ + index?: number; + /** + * tab 上按钮文字 + */ + text?: string; + /** + * 图片路径 + */ + iconPath?: string; + /** + * 选中时的图片路径 + */ + selectedIconPath?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowTabBarOptions { + /** + * 是否需要动画效果 + */ + animation?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface HideTabBarOptions { + /** + * 是否需要动画效果 + */ + animation?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetTopBarTextOptions { + /** + * 置顶栏文字内容 + */ + text?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface NavigateToOptions { + /** + * 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数 + */ + url?: string | string; + /** + * 窗口显示的动画类型 + * - auto: 自动选择动画效果 + * - none: 无动画效果 + * - slide-in-right: 从右侧横向滑动效果 + * - slide-in-left: 左侧横向滑动效果 + * - slide-in-top: 从上侧竖向滑动效果 + * - slide-in-bottom: 从下侧竖向滑动效果 + * - fade-in: 从透明到不透明逐渐显示效果 + * - zoom-out: 从小到大逐渐放大显示效果 + * - zoom-fade-out: 从小到大逐渐放大并且从透明到不透明逐渐显示效果 + * - pop-in: 从右侧平移入栈动画效果 + */ + animationType?: 'auto' | 'none' | 'slide-in-right' | 'slide-in-left' | 'slide-in-top' | 'slide-in-bottom' | 'fade-in' | 'zoom-out' | 'zoom-fade-out' | 'pop-in'; + /** + * 窗口显示动画的持续时间,单位为 ms + */ + animationDuration?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface RedirectToOptions { + /** + * 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数 + */ + url?: string | string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ReLaunchOptions { + /** + * 需要跳转的应用内非 tabBar 的页面的路径 , 路径后可以带参数 + */ + url?: string | string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SwitchTabOptions { + /** + * 需要跳转的 tabBar 页面的路径,路径后不能带参数 + */ + url?: string | string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CreateIntersectionObserverOptions { + /** + * 所有阈值 + */ + thresholds?: any []; + /** + * 初始的相交比例 + */ + initialRatio?: number; + /** + * 是否同时观测多个参照节点(而非一个) + */ + selectAll?: boolean; +} + +interface NavigateBackOptions { + /** + * 返回的页面数,如果 delta 大于现有页面数,则返回到首页 + */ + delta?: number; + /** + * 窗口关闭的动画类型 + * - auto: 自动选择动画效果 + * - none: 无动画效果 + * - slide-out-right: 横向向右侧滑出屏幕动画 + * - slide-out-left: 横向向左侧滑出屏幕动画 + * - slide-out-top: 竖向向上侧滑出屏幕动画 + * - slide-out-bottom: 竖向向下侧滑出屏幕动画 + * - fade-out: 从不透明到透明逐渐隐藏动画 + * - zoom-in: 从大逐渐缩小关闭动画 + * - zoom-fade-in: 从大逐渐缩小并且从不透明到透明逐渐隐藏关闭动画 + * - pop-out: 从右侧平移出栈动画效果 + */ + animationType?: 'auto' | 'none' | 'slide-out-right' | 'slide-out-left' | 'slide-out-top' | 'slide-out-bottom' | 'fade-out' | 'zoom-in' | 'zoom-fade-in' | 'pop-out'; + /** + * 窗口关闭动画的持续时间,单位为 ms + */ + animationDuration?: number; +} + +interface CreateAnimationOptions { + /** + * 动画持续时间,单位ms + */ + duration?: number; + /** + * 定义动画的效果 + * - linear: 动画从头到尾的速度是相同的 + * - ease: 动画以低速开始,然后加快,在结束前变慢 + * - ease-in: 动画以低速开始 + * - ease-in-out: 动画以低速开始和结束 + * - ease-out: 动画以低速结束 + * - step-start: 动画第一帧就跳至结束状态直到结束 + * - step-end: 动画一直保持开始状态,最后一帧跳到结束状态 + */ + timingFunction?: 'linear' | 'ease' | 'ease-in' | 'ease-in-out' | 'ease-out' | 'step-start' | 'step-end'; + /** + * 动画延迟时间,单位 ms + */ + delay?: number; + /** + * 设置transform-origin + */ + transformOrigin?: string; +} + +interface PageScrollToOptions { + /** + * 滚动到页面的目标位置 + */ + scrollTop?: number; + /** + * 滚动动画的时长 + */ + duration?: number; +} + +interface StartPullDownRefreshOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SelectorQuery { + /** + * 将选择器的选取范围更改为自定义组件component内 + */ + in(component: any): void; + /** + * 在当前页面下选择第一个匹配选择器selector的节点 + */ + select(selector: string): NodesRef; + /** + * 在当前页面下选择匹配选择器selector的所有节点 + */ + selectAll(selector: string): NodesRef; + /** + * 选择显示区域 + */ + selectViewport(selector: string): NodesRef; + /** + * 执行所有的请求 + */ + exec(callback: () => void): void; +} + +interface NodesRef { + /** + * 添加节点的布局位置的查询请求,相对于显示区域,以像素为单位 + */ + boundingClientRect(callback: (result: NodeRect) => void): void; + /** + * 添加节点的滚动位置查询请求,以像素为单位 + */ + scrollOffset(callback: (result: NodeRect) => void): SelectorQuery; + /** + * 获取节点的相关信息,需要获取的字段在fields中指定 + */ + fields(fields: NodeField, callback: (result: NodeRect) => void): SelectorQuery; +} + +interface NodeRect { + /** + * 节点的ID + */ + id?: string; + /** + * 节点的dataset + */ + dataset?: any; + /** + * 节点的左边界坐标 + */ + left?: number; + /** + * 节点的右边界坐标 + */ + right?: number; + /** + * 节点的上边界坐标 + */ + top?: number; + /** + * 节点的下边界坐标 + */ + bottom?: number; + /** + * 节点的宽度 + */ + width?: number; + /** + * 节点的高度 + */ + height?: number; +} + +interface NodeField { + /** + * 节点的dataset + */ + dataset?: any; + /** + * 节点的宽度 + */ + width?: number; + /** + * 节点的高度 + */ + height?: number; + /** + * 节点的水平滚动位置 + */ + scrollLeft?: number; + /** + * 节点的竖直滚动位置 + */ + scrollTop?: number; + /** + * 节点 scroll-x 属性的当前值 + */ + scrollX?: number; + /** + * 节点 scroll-y 属性的当前值 + */ + scrollY?: number; +} + +interface IntersectionObserver { + /** + * 使用选择器指定一个节点,作为参照区域之一 + */ + relativeTo(selector: string, margins: any []): void; + /** + * 指定页面显示区域作为参照区域之一 + */ + relativeToViewport(margins: any []): void; + /** + * 指定目标节点并开始监听相交状态变化情况 + */ + observe(targetSelector: string, callback: (result: ObserveResult) => void): void; + /** + * 停止监听 + */ + disconnect(): void; +} + +interface ObserveResult { + /** + * 相交比例 + */ + intersectionRatio?: number; + /** + * 相交区域的边界 + */ + intersectionRect?: any; + /** + * 目标节点布局区域的边界 + */ + boundingClientRect?: ObserveNodeRect; + /** + * 参照区域的边界 + */ + relativeRect?: ObserveNodeRect; + /** + * 相交检测时的时间戳 + */ + time?: number; +} + +interface ObserveNodeRect { + /** + * left + */ + left?: number; + /** + * right + */ + right?: number; + /** + * top + */ + top?: number; + /** + * bottom + */ + bottom?: number; +} + +interface Animation { + /** + * 透明度 + */ + opacity(value: number): void; + /** + * 颜色值 + */ + backgroundColor(color: number): void; + /** + * 长度值 + */ + width(length: number): void; + /** + * 长度值 + */ + height(length: number): void; + /** + * 长度值 + */ + top(length: number): void; + /** + * 长度值 + */ + left(length: number): void; + /** + * 长度值 + */ + bottom(length: number): void; + /** + * 长度值 + */ + right(length: number): void; + /** + * 从原点顺时针旋转一个deg角度 + */ + rotate(deg: number): void; + /** + * 在X轴旋转一个deg角度 + */ + rotateX(deg: number): void; + /** + * 在Y轴旋转一个deg角度 + */ + rotateY(deg: number): void; + /** + * 在Z轴旋转一个deg角度 + */ + rotateZ(deg: number): void; + /** + * 同transform-function rotate3d + */ + rotate3d(x: number, y: number, z: number, deg: number): void; + /** + * 缩放 + */ + scale(sx: number, sy: number): void; + /** + * 在X轴缩放sx倍数 + */ + scaleX(sx: number): void; + /** + * 在Y轴缩放sy倍数 + */ + scaleY(sy: number): void; + /** + * 在Z轴缩放sz倍数 + */ + scaleZ(sz: number): void; + /** + * 在X轴缩放sx倍数,在Y轴缩放sy倍数,在Z轴缩放sz倍数 + */ + scale3d(sx: number, sy: number, sz: number): void; + /** + * 偏移 + */ + translate(tx: number, ty: number): void; + /** + * 在X轴偏移tx + */ + translateX(tx: number): void; + /** + * 在Y轴偏移ty + */ + translateY(ty: number): void; + /** + * 在Z轴偏移tx + */ + translateZ(tz: number): void; + /** + * 在X轴偏移tx,在Y轴偏移ty,在Z轴偏移tz + */ + translate3d(tx: number, ty: number, tz: number): void; + /** + * 倾斜 + */ + skew(ax: number, ay: number): void; + /** + * Y轴坐标不变,X轴坐标延顺时针倾斜ax度 + */ + skewX(ax: number): void; + /** + * X轴坐标不变,Y轴坐标延顺时针倾斜ay度 + */ + skewY(ay: number): void; + /** + * 矩阵变形 + */ + matrix(a: number, b: number, c: number, d: number, tx: number, ty: number): void; + /** + * 矩阵变形 + */ + matrix3d(): void; +} + +interface CanvasContext { + /** + * 填充色 + */ + fillStyle?: string; + /** + * 边框颜色 + */ + strokeStyle?: string; + /** + * 阴影的模糊级别 + */ + shadowBlur?: number; + /** + * 阴影的颜色 + */ + shadowColor?: string; + /** + * 阴影相对于形状在水平方向的偏移 + */ + shadowOffsetX?: number; + /** + * 阴影相对于形状在竖直方向的偏移 + */ + shadowOffsetY?: number; + /** + * 线条的宽度 + */ + lineWidth?: number; + /** + * 线条的端点样式 + * - butt: + * - round: + * - square: + */ + lineCap?: 'butt' | 'round' | 'square'; + /** + * 线条的结束交点样式 + * - bevel: + * - round: + * - miter: + */ + lineJoin?: 'bevel' | 'round' | 'miter'; + /** + * 最大斜接长度 + */ + miterLimit?: number; + /** + * 透明度 + */ + globalAlpha?: number; + /** + * 设置要在绘制新形状时应用的合成操作的类型 + */ + globalCompositeOperation?: string; + /** + * 偏移量 + */ + lineDashOffset?: number; + /** + * 字体样式 + */ + font?: string; + /** + * 设置填充色 + */ + setFillStyle(color: string): void; + /** + * 设置边框颜色 + */ + setStrokeStyle(color: string): void; + /** + * 设置阴影样式 + */ + setShadow(offsetX: number, offsetY: number, blur: number, color: string): void; + /** + * 创建一个线性的渐变颜色 + */ + createLinearGradient(x0: number, y0: number, x1: number, y1: string): CanvasContext; + /** + * 创建一个圆形的渐变颜色 + */ + createCircularGradient(x: number, y: number, r: number): CanvasContext; + /** + * 创建一个颜色的渐变点 + */ + addColorStop(stop: number, color: string): void; + /** + * 设置线条的宽度 + */ + setLineWidth(lineWidth: number): void; + /** + * 设置线条的端点样式 + */ + setLineCap(lineCap: string): void; + /** + * 设置线条的交点样式 + */ + setLineJoin(lineJoin: string): void; + /** + * 设置线条的宽度 + */ + setLineDash(pattern: any [], offset: number): void; + /** + * 设置最大斜接长度 + */ + setMiterLimit(miterLimit: number): void; + /** + * 创建一个矩形 + */ + rect(x: number, y: number, width: number, height: number): void; + /** + * 填充一个矩形 + */ + fillRect(x: number, y: number, width: number, height: number): void; + /** + * 画一个矩形(非填充) + */ + strokeRect(x: number, y: number, width: number, height: number): void; + /** + * 清除画布上在该矩形区域内的内容 + */ + clearRect(x: number, y: number, width: number, height: number): void; + /** + * 对当前路径中的内容进行填充 + */ + fill(): void; + /** + * 画出当前路径的边框 + */ + stroke(): void; + /** + * 开始创建一个路径 + */ + beginPath(): void; + /** + * 关闭一个路径 + */ + closePath(): void; + /** + * 把路径移动到画布中的指定点,不创建线条 + */ + moveTo(x: number, y: number): void; + /** + * 增加一个新点,然后创建一条从上次指定点到目标点的线 + */ + lineTo(x: number, y: number): void; + /** + * 画一条弧线 + */ + arc(x: number, y: number, r: number, sAngle: number, eAngle: number, counterclockwise: boolean): void; + /** + * 创建三次方贝塞尔曲线路径 + */ + bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, y: number): void; + /** + * 创建二次贝塞尔曲线路径 + */ + quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void; + /** + * 横纵坐标缩放 + */ + scale(scaleWidth: number, scaleHeight: number): void; + /** + * 顺时针旋转当前坐标轴 + */ + rotate(rotate: number): void; + /** + * 对当前坐标系的原点(0, 0)进行变换 + */ + translate(x: number, y: number): void; + /** + * 从原始画布中剪切任意形状和尺寸 + */ + clip(): void; + /** + * 设置字体的字号 + */ + setFontSize(fontSize: number): void; + /** + * 在画布上绘制被填充的文本 + */ + fillText(text: string, x: number, y: number, maxWidth: number): void; + /** + * 设置文字的对齐 + */ + setTextAlign(align: string): void; + /** + * 设置文字的水平对齐 + */ + setTextBaseline(textBaseline: string): void; + /** + * 绘制图像到画布 + */ + drawImage(imageResource: string, dx: number, dy: number, dWidth: number, dHeigt: number, sx: number, sy: number, sWidth: number, sHeight: number): void; + /** + * 设置全局画笔透明度 + */ + setGlobalAlpha(alpha: number): void; + /** + * 保存当前的绘图上下文 + */ + save(): void; + /** + * 恢复之前保存的绘图上下文 + */ + restore(): void; + /** + * 将之前在绘图上下文中的描述(路径、变形、样式)画到 canvas 中 + */ + draw(reserve: boolean, callback: () => void): void; + /** + * 测量文本尺寸信息,目前仅返回文本宽度 + */ + measureText(text: string): CanvasTextMetrics; + /** + * 根据控制点和半径绘制圆弧路径 + */ + arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void; + /** + * 给定的 (x, y) 位置绘制文本描边的方法 + */ + strokeText(text: string, x: number, y: number, maxWidth: number): void; + /** + * 对指定的图像创建模式的方法,可在指定的方向上重复元图像 + */ + createPattern(image: string, repetition: string): void; + /** + * 使用矩阵重新设置(覆盖)当前变换的方法 + */ + setTransform(scaleX: number, skewX: number, skewY: number, scaleY: number, translateX: number, translateY: number): void; +} + +interface CanvasTextMetrics { + /** + * 文本的宽度 + */ + width?: number; +} + +interface CanvasToTempFilePathOptions { + /** + * 画布x轴起点(默认0) + */ + x?: number; + /** + * 画布y轴起点(默认0) + */ + y?: number; + /** + * 画布宽度(默认为canvas宽度-x) + */ + width?: number; + /** + * 画布高度(默认为canvas高度-y) + */ + height?: number; + /** + * 输出图片宽度(默认为 width * 屏幕像素密度) + */ + destWidth?: boolean; + /** + * 输出图片高度(默认为 height * 屏幕像素密度) + */ + destHeight?: () => void; + /** + * 画布标识,传入 的 canvas-id + */ + canvasId?: string; + /** + * 目标文件的类型,默认为 'png' + */ + fileType?: string; + /** + * 图片的质量,取值范围为 (0, 1],不在范围内时当作1.0处理 + */ + quality?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: CanvasToTempFilePathRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CanvasToTempFilePathRes { + /** + * 导出生成的图片路径 + */ + tempFilePath?: string; +} + +interface CanvasGetImageDataOptions { + /** + * 画布标识,传入 的 canvas-id + */ + canvasId?: string; + /** + * 将要被提取的图像数据矩形区域的左上角 x 坐标 + */ + x?: number; + /** + * 将要被提取的图像数据矩形区域的左上角 y 坐标 + */ + y?: number; + /** + * 将要被提取的图像数据矩形区域的宽度 + */ + width?: number; + /** + * 将要被提取的图像数据矩形区域的高度 + */ + height?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: CanvasGetImageDataRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CanvasGetImageDataRes { + /** + * 回调信息 + */ + errMsg?: string; + /** + * 图像数据矩形的宽度 + */ + width?: number; + /** + * 图像数据矩形的高度 + */ + height?: number; + /** + * 图像像素点数据,一维数组,每四项表示一个像素点的rgba + */ + data?: any []; +} + +interface CanvasPutImageDataOptions { + /** + * 画布标识,传入 的 canvas-id + */ + canvasId?: string; + /** + * 图像像素点数据,一维数组,每四项表示一个像素点的rgba + */ + data?: any []; + /** + * 源图像数据在目标画布中的位置偏移量(x 轴方向的偏移量) + */ + x?: number; + /** + * 源图像数据在目标画布中的位置偏移量(y 轴方向的偏移量) + */ + y?: number; + /** + * 源图像数据矩形区域的宽度 + */ + width?: number; + /** + * 源图像数据矩形区域的高度 + */ + height?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetScreenBrightnessOptions { + /** + * 屏幕亮度值,范围 0~1,0 最暗,1 最亮 + */ + value?: number; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetScreenBrightnessOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetScreenBrightnessSuccessRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetScreenBrightnessSuccessRes { + /** + * 屏幕亮度值,范围 0~1,0 最暗,1 最亮。 + */ + value?: number; +} + +interface SetKeepScreenOnOptions { + /** + * 是否保持屏幕常亮 + */ + keepScreenOn?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface VibrateLongOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface VibrateShortOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface AddPhoneContactOptions { + /** + * 头像本地文件路径 + */ + photoFilePath?: string; + /** + * 昵称 + */ + nickName?: string; + /** + * 姓氏 + */ + lastName?: string; + /** + * 中间名 + */ + middleName?: string; + /** + * 名字 + */ + firstName?: string; + /** + * 备注 + */ + remark?: string; + /** + * 手机号 + */ + mobilePhoneNumber?: string; + /** + * 微信号 + */ + weChatNumber?: string; + /** + * 联系地址国家 + */ + addressCountry?: string; + /** + * 联系地址省份 + */ + addressState?: string; + /** + * 联系地址城市 + */ + addressCity?: string; + /** + * 联系地址街道 + */ + addressStreet?: string; + /** + * 联系地址邮政编码 + */ + addressPostalCode?: string; + /** + * 公司 + */ + organization?: string; + /** + * 职位 + */ + title?: string; + /** + * 工作传真 + */ + workFaxNumber?: string; + /** + * 工作电话 + */ + workPhoneNumber?: string; + /** + * 公司电话 + */ + hostNumber?: string; + /** + * 电子邮件 + */ + email?: string; + /** + * 网站 + */ + url?: string; + /** + * 工作地址国家 + */ + workAddressCountry?: string; + /** + * 工作地址省份 + */ + workAddressState?: string; + /** + * 工作地址城市 + */ + workAddressCity?: string; + /** + * 工作地址街道 + */ + workAddressStreet?: string; + /** + * 工作地址邮政编码 + */ + workAddressPostalCode?: string; + /** + * 住宅传真 + */ + homeFaxNumber?: string; + /** + * 住宅电话 + */ + homePhoneNumber?: string; + /** + * 住宅地址国家 + */ + homeAddressCountry?: string; + /** + * 住宅地址省份 + */ + homeAddressState?: string; + /** + * 住宅地址城市 + */ + homeAddressCity?: string; + /** + * 住宅地址街道 + */ + homeAddressStreet?: string; + /** + * 住宅地址邮政编码 + */ + homeAddressPostalCode?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetExtConfigOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetExtConfigRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetExtConfigRes { + /** + * 调用结果 + */ + errMsg?: string; + /** + * 第三方平台自定义的数据 + */ + extConfig?: any; +} + +interface GetExtConfigSyncRes { + /** + * 第三方平台自定义的数据 + */ + extConfig?: any; +} + +interface GetProviderOptions { + /** + * 服务类型,可取值“oauth”、“share”、“payment”、“push” + * - oauth: 授权登录 + * - share: 分享 + * - payment: 支付 + * - push: 推送 + */ + service?: 'oauth' | 'share' | 'payment' | 'push'; + /** + * 接口调用成功的回调 + */ + success?: (result: GetProviderRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetProviderRes { + /** + * 服务类型 + */ + service?: string; + /** + * 得到的服务供应商 + */ + provider?: any []; +} + +interface LoginOptions { + /** + * 分享服务提供商,通过uni.getProvider获取,如果不设置则弹出分享列表选择界面 + */ + provider?: string; + /** + * 超时时间,单位 ms + */ + timeout?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: LoginRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface LoginRes { + /** + * 描述信息 + */ + errMsg?: string; + /** + * 登录服务商提供的登录信息,服务商不同返回的结果不完全相同 + */ + authResult?: string; +} + +interface CheckSessionOptions { + /** + * 接口调用成功的回调函数,session_key未过期 + */ + success?: () => void; + /** + * 接口调用失败的回调函数,session_key已过期 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface AuthorizeOptions { + /** + * 需要获取权限的scope + */ + scope?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetUserInfoOptions { + /** + * 分享服务提供商,通过uni.getProvider获取 + */ + provider?: string; + /** + * 是否带上登录态信息,仅微信小程序生效。 + */ + withCredentials?: boolean; + /** + * 指定返回用户信息的语言,zh_CN 简体中文,zh_TW 繁体中文,en 英文。默认为en,仅微信小程序生效。 + */ + lang?: string; + /** + * 超时时间,单位 ms + */ + timeout?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetUserInfoRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetUserInfoRes { + /** + * 用户信息对象,不包含 openid 等敏感信息 + */ + userInfo?: UserInfo; + /** + * 不包括敏感信息的原始数据字符串,用于计算签名。 + */ + rawData?: string; + /** + * 使用 sha1( rawData + sessionkey ) 得到字符串,用于校验用户信息,仅微信小程序生效。 + */ + signature?: string; + /** + * 包括敏感数据在内的完整用户信息的加密数据,详细见加密数据解密算法,仅微信小程序生效。 + */ + encryptedData?: string; + /** + * 加密算法的初始向量,详细见加密数据解密算法,仅微信小程序生效。 + */ + iv?: string; + /** + * 描述信息 + */ + errMsg?: string; +} + +interface UserInfo { + /** + * 用户昵称 + */ + nickname?: string; + /** + * 该服务商唯一用户标识 + */ + openid?: string; + /** + * 用户头像 + */ + avatarUrl?: string; +} + +interface ShareOptions { + /** + * 分享服务提供商,通过uni.getProvider获取,如果不设置则弹出分享列表选择界面 + */ + provider?: string; + /** + * 分享类型。默认图文0,纯文字1,纯图片2,音乐3,视频4,小程序5。 + * - 0: 图文 + * - 1: 纯文字 + * - 2: 纯图片 + * - 3: 音乐 + * - 4: 视频 + * - 5: 小程序 + */ + type?: '0' | '1' | '2' | '3' | '4' | '5'; + /** + * 标题 + */ + title?: string; + /** + * 场景。可取值“WXSceneSession”分享到聊天界面,“WXSenceTimeline”分享到朋友圈,“WXSceneFavorite”分享到微信收藏 + */ + scene?: string; + /** + * 摘要 + */ + summary?: string; + /** + * 跳转链接 + */ + href?: string; + /** + * 图片地址 + */ + imageUrl?: string; + /** + * 音视频地址 + */ + mediaUrl?: string; + /** + * 分享小程序 + */ + miniProgram?: MiniProgramShareOptions; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface MiniProgramShareOptions { + /** + * 微信小程序原始id + */ + id?: string; + /** + * 点击链接进入的页面 + */ + path?: string; + /** + * 微信小程序版本类型,默认为0。 + * - 0: 正式版 + * - 1: 测试版 + * - 2: 体验版 + */ + type?: '0' | '1' | '2'; + /** + * 兼容低版本的网页链接 + */ + webUrl?: string; +} + +interface SubscribePushOptions { + /** + * 分享推送提供商,通过uni.getProvider获取 + */ + provider?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface UnscribePushOptions { + /** + * 分享推送提供商,通过uni.getProvider获取 + */ + provider?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OnPushOptions { + /** + * 分享推送提供商,通过uni.getProvider获取 + */ + provider?: string; + /** + * 接收到透传数据回调,回调参数(Object):messageId(消息id)、data(消息内容) + */ + callback?: () => void; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OffPushOptions { + /** + * 分享推送提供商,通过uni.getProvider获取 + */ + provider?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ShowShareMenuOptions { + /** + * 是否使用带 shareTicket 的转发 + */ + withShareTicket?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface HideShareMenuOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface UpdateShareMenuOptions { + /** + * 是否使用带 shareTicket 的转发 + */ + withShareTicket?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetShareInfoOptions { + /** + * shareTicket + */ + shareTicket?: string; + /** + * 超时时间,单位 ms + */ + timeout?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetShareInfoRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetShareInfoRes { + /** + * 错误信息 + */ + errMsg?: string; + /** + * 包括敏感数据在内的完整转发信息的加密数据 + */ + encryptedData?: string; + /** + * 加密算法的初始向量 + */ + iv?: string; +} + +interface ChooseAddressOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: ChooseAddressRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseAddressRes { + /** + * 调用结果 + */ + errMsg?: string; + /** + * 收货人姓名 + */ + userName?: string; + /** + * 邮编 + */ + postalCode?: string; + /** + * 国标收货地址第一级地址 + */ + provinceName?: string; + /** + * 国标收货地址第二级地址 + */ + cityName?: string; + /** + * 国标收货地址第三级地址 + */ + countyName?: string; + /** + * 详细收货地址信息 + */ + detailInfo?: string; + /** + * 收货地址国家码 + */ + nationalCode?: string; + /** + * 收货人手机号码 + */ + telNumber?: string; +} + +interface AddCardOptions { + /** + * 需要添加的卡券列表 + */ + cardList?: AddCardData []; + /** + * 接口调用成功的回调函数 + */ + success?: (result: AddCardRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface AddCardData { + /** + * 卡券 id + */ + cardId?: string; + /** + * 卡券的扩展参数 + */ + cardExt?: string; +} + +interface AddCardRes { + /** + * 卡券 id + */ + cardList?: CardData []; +} + +interface CardData { + /** + * 加密 code,为用户领取到卡券的code加密后的字符串 + */ + code?: string; + /** + * 用户领取到卡券的id + */ + cardId?: string; + /** + * 用户领取到卡券的扩展参数,与调用时传入的参数相同 + */ + cardExt?: string; + /** + * 是否成功 + */ + isSuccess?: boolean; +} + +interface OpenCardOptions { + /** + * 需要打开的卡券列表 + */ + cardList?: OpenCardData []; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OpenCardData { + /** + * 需要打开的卡券 Id + */ + cardId?: string; + /** + * 由 addCard 的返回对象中的加密 code 通过解密后得到 + */ + code?: string; +} + +interface OpenSettingOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetSettingOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetWeRunDataOptions { + /** + * 超时时间,单位 ms + */ + timeout?: number; + /** + * 接口调用成功的回调函数 + */ + success?: (result: GetWeRunDataRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface GetWeRunDataRes { + /** + * 调用结果 + */ + errMsg?: string; + /** + * 包括敏感数据在内的完整用户信息的加密数据 + */ + encryptedData?: string; + /** + * 加密算法的初始向量 + */ + iv?: string; +} + +interface NavigateToMiniProgramOptions { + /** + * 要打开的uni-app appId + */ + appId?: string; + /** + * 打开的页面路径,如果为空则打开首页 + */ + path?: string; + /** + * 需要传递给目标uni-app的数据 + */ + extraData?: any; + /** + * 要打开的uni-app版本 + */ + envVersion?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface NavigateBackMiniProgramOptions { + /** + * 需要返回给上一个uni-app的数据 + */ + extraData?: any; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseInvoiceTitleOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: ChooseInvoiceTitleRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface ChooseInvoiceTitleRes { + /** + * 抬头类型(0:单位,1:个人) + */ + type?: string; + /** + * 抬头名称 + */ + title?: string; + /** + * 抬头税号 + */ + taxNumber?: string; + /** + * 单位地址 + */ + companyAddress?: string; + /** + * 手机号码 + */ + telephone?: string; + /** + * 银行名称 + */ + bankName?: string; + /** + * 银行账号 + */ + bankAccount?: string; + /** + * 接口调用结果 + */ + errMsg?: string; +} + +interface CheckIsSupportSoterAuthenticationOptions { + /** + * 接口调用成功的回调函数 + */ + success?: (result: CheckIsSupportSoterAuthenticationRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface CheckIsSupportSoterAuthenticationRes { + /** + * 接口调用成功的回调函数 + */ + supportMode?: any []; + /** + * 接口调用结果 + */ + errMsg?: string; +} + +interface StartSoterAuthenticationOptions { + /** + * 请求使用的可接受的生物认证方式 + */ + requestAuthModes?: any []; + /** + * 挑战因子 + */ + challenge?: string; + /** + * 验证描述,即识别过程中显示在界面上的对话框提示内容 + */ + authContent?: string; + /** + * 接口调用成功的回调函数 + */ + success?: (result: StartSoterAuthenticationRes) => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StartSoterAuthenticationRes { + /** + * 错误码 + */ + errCode?: number; + /** + * 生物认证方式 + */ + authMode?: string; + /** + * 在设备安全区域(TEE)内获得的本机安全信息以及本次认证信息 + */ + resultJSON?: string; + /** + * 接口调用结果 + */ + errMsg?: string; +} + +interface CheckIsSoterEnrolledInDeviceOptions { + /** + * 认证方式 + * - fingerPrint: 指纹识别 + * - facial: 人脸识别(暂未支持) + * - speech: 声纹识别(暂未支持) + */ + checkAuthMode?: 'fingerPrint' | 'facial' | 'speech'; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface UpdateManager { + /** + * 当向应用后台请求完新版本信息,会进行回调 + */ + onCheckForUpdate(callback: () => void): void; + /** + * 当新版本下载完成,会进行回调 + */ + onUpdateReady(callback: () => void): void; + /** + * 当新版本下载失败,会进行回调 + */ + onUpdateFailed(callback: () => void): void; + /** + * 当新版本下载完成,调用该方法会强制当前uni-app应用上新版本并重启 + */ + applyUpdate(): void; +} + +interface Worker { + /** + * 向 Worker 线程发送的消息。 + */ + postMessage(message: any): void; + /** + * 监听 Worker 线程向当前线程发送的消息 + */ + onMessage(callback: () => void): void; + /** + * 结束当前 Worker 线程,仅限在主线程 Worker 实例上调用。 + */ + terminate(): void; +} + +interface SetEnableDebugOptions { + /** + * 是否打开调试 + */ + enableDebug?: boolean; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetBackgroundColorOptions { + /** + * 窗口的背景色,必须为十六进制颜色值 + */ + backgroundColor?: string; + /** + * 顶部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 + */ + backgroundColorTop?: string; + /** + * 底部窗口的背景色,必须为十六进制颜色值,仅 iOS 支持 + */ + backgroundColorBottom?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface SetBackgroundTextStyleOptions { + /** + * 下拉背景字体、loading 图的样式,值为:dark、light + */ + textStyle?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface OnGyroscopeChangeSuccess { + /** + * x 轴方向角速度 + */ + x?: number; + /** + * y 轴方向角速度 + */ + y?: number; + /** + * z 轴方向角速度 + */ + z?: number; +} + +interface StartGyroscopeOptions { + /** + * 监听陀螺仪数据回调函数的执行频率:game(20ms/次)、ui(60ms/次)、normal (200ms/次) + */ + interval?: string; + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} + +interface StopGyroscopeOptions { + /** + * 接口调用成功的回调函数 + */ + success?: () => void; + /** + * 接口调用失败的回调函数 + */ + fail?: () => void; + /** + * 接口调用结束的回调函数(调用成功、失败都会执行) + */ + complete?: () => void; +} diff --git a/types/uni-app/lib/app.d.ts b/types/uni-app/lib/app.d.ts new file mode 100644 index 0000000000..af29f99b17 --- /dev/null +++ b/types/uni-app/lib/app.d.ts @@ -0,0 +1,234 @@ +declare namespace App { + interface LaunchOptions { + query: number; + } + + interface ReferrerInfo { + /** + * 来源小程序或公众号或App的 appId + * + * 以下场景支持返回 referrerInfo.appId: + * - 1020(公众号 profile 页相关小程序列表): appId + * - 1035(公众号自定义菜单):来源公众号 appId + * - 1036(App 分享消息卡片):来源应用 appId + * - 1037(小程序打开小程序):来源小程序 appId + * - 1038(从另一个小程序返回):来源小程序 appId + * - 1043(公众号模板消息):来源公众号 appId + */ + appId: string; + /** 来源小程序传过来的数据,scene=1037或1038时支持 */ + extraData?: any; + } + + type SceneValues = 1001 + | 1005 + | 1006 + | 1007 + | 1008 + | 1011 + | 1012 + | 1013 + | 1014 + | 1017 + | 1019 + | 1020 + | 1022 + | 1023 + | 1024 + | 1025 + | 1026 + | 1027 + | 1028 + | 1029 + | 1030 + | 1031 + | 1032 + | 1034 + | 1035 + | 1036 + | 1037 + | 1038 + | 1039 + | 1042 + | 1043 + | 1044 + | 1045 + | 1046 + | 1047 + | 1048 + | 1049 + | 1052 + | 1053 + | 1054 + | 1056 + | 1057 + | 1058 + | 1059 + | 1064 + | 1067 + | 1068 + | 1069 + | 1071 + | 1072 + | 1073 + | 1074 + | 1077 + | 1078 + | 1079 + | 1081 + | 1082 + | 1084 + | 1089 + | 1090 + | 1091 + | 1092 + | 1095 + | 1096 + | 1097 + | 1099 + | 1102 + | 1103 + | 1104 + | number; + + interface LaunchShowOption { + /** 打开小程序的路径 */ + path: string; + /** 打开小程序的query */ + query: AnyObject; + /** + * 打开小程序的场景值 + * - 1001: 发现栏小程序主入口,「最近使用」列表(基础库2.2.4版本起包含「我的小程序」列表) + * - 1005: 顶部搜索框的搜索结果页 + * - 1006: 发现栏小程序主入口搜索框的搜索结果页 + * - 1007: 单人聊天会话中的小程序消息卡片 + * - 1008: 群聊会话中的小程序消息卡片 + * - 1011: 扫描二维码 + * - 1012: 长按图片识别二维码 + * - 1013: 手机相册选取二维码 + * - 1014: 小程序模板消息 + * - 1017: 前往体验版的入口页 + * - 1019: 微信钱包 + * - 1020: 公众号 profile 页相关小程序列表 + * - 1022: 聊天顶部置顶小程序入口 + * - 1023: 安卓系统桌面图标 + * - 1024: 小程序 profile 页 + * - 1025: 扫描一维码 + * - 1026: 附近小程序列表 + * - 1027: 顶部搜索框搜索结果页「使用过的小程序」列表 + * - 1028: 我的卡包 + * - 1029: 卡券详情页 + * - 1030: 自动化测试下打开小程序 + * - 1031: 长按图片识别一维码 + * - 1032: 手机相册选取一维码 + * - 1034: 微信支付完成页 + * - 1035: 公众号自定义菜单 + * - 1036: App 分享消息卡片 + * - 1037: 小程序打开小程序 + * - 1038: 从另一个小程序返回 + * - 1039: 摇电视 + * - 1042: 添加好友搜索框的搜索结果页 + * - 1043: 公众号模板消息 + * - 1044: 带 shareTicket 的小程序消息卡片 [详情]((转发#获取更多转发信息)) + * - 1045: 朋友圈广告 + * - 1046: 朋友圈广告详情页 + * - 1047: 扫描小程序码 + * - 1048: 长按图片识别小程序码 + * - 1049: 手机相册选取小程序码 + * - 1052: 卡券的适用门店列表 + * - 1053: 搜一搜的结果页 + * - 1054: 顶部搜索框小程序快捷入口 + * - 1056: 音乐播放器菜单 + * - 1057: 钱包中的银行卡详情页 + * - 1058: 公众号文章 + * - 1059: 体验版小程序绑定邀请页 + * - 1064: 微信连Wi-Fi状态栏 + * - 1067: 公众号文章广告 + * - 1068: 附近小程序列表广告 + * - 1069: 移动应用 + * - 1071: 钱包中的银行卡列表页 + * - 1072: 二维码收款页面 + * - 1073: 客服消息列表下发的小程序消息卡片 + * - 1074: 公众号会话下发的小程序消息卡片 + * - 1077: 摇周边 + * - 1078: 连Wi-Fi成功页 + * - 1079: 微信游戏中心 + * - 1081: 客服消息下发的文字链 + * - 1082: 公众号会话下发的文字链 + * - 1084: 朋友圈广告原生页 + * - 1089: 微信聊天主界面下拉,「最近使用」栏(基础库2.2.4版本起包含「我的小程序」栏) + * - 1090: 长按小程序右上角菜单唤出最近使用历史 + * - 1091: 公众号文章商品卡片 + * - 1092: 城市服务入口 + * - 1095: 小程序广告组件 + * - 1096: 聊天记录 + * - 1097: 微信支付签约页 + * - 1099: 页面内嵌插件 + * - 1102: 公众号 profile 页服务预览 + * - 1103: 发现栏小程序主入口,「我的小程序」列表(基础库2.2.4版本起废弃) + * - 1104: 微信聊天主界面下拉,「我的小程序」栏(基础库2.2.4版本起废弃) + */ + scene: SceneValues; + /** shareTicket,详见 [获取更多转发信息]((转发#获取更多转发信息)) */ + shareTicket: string; + /** 当场景为由从另一个小程序或公众号或App打开时,返回此字段 */ + referrerInfo?: ReferrerInfo; + } + + interface PageNotFoundOption { + /** 不存在页面的路径 */ + path: string; + /** 打开不存在页面的 query */ + query: AnyObject; + /** 是否本次启动的首个页面(例如从分享等入口进来,首个页面是开发者配置的分享页面) */ + isEntryPage: boolean; + } + + interface AppInstance { + /** + * 生命周期回调—监听应用初始化 + * 应用初始化完成时触发,全局只触发一次。 + */ + onLaunch?(options?: LaunchShowOption): void; + /** + * 生命周期回调—监听应用显示 + * 应用启动,或从后台进入前台显示时 + */ + onShow?(options?: LaunchShowOption): void; + /** + * 生命周期回调—监听应用隐藏 + * 应用从前台进入后台时 + */ + onHide?(): void; + /** + * 错误监听函数 + * 应用发生脚本错误,或者 api + */ + onError?(/** 错误信息,包含堆栈 */error?: string): void; + /** + * 页面不存在监听函数 + * 应用要打开的页面不存在时触发,会带上页面信息回调该函数 + * + * **注意:** + * 1. 如果开发者没有添加 `onPageNotFound` 监听,当跳转页面不存在时,将推入微信客户端原生的页面不存在提示页面。 + * 2. 如果 `onPageNotFound` 回调中又重定向到另一个不存在的页面,将推入微信客户端原生的页面不存在提示页面,并且不再回调 `onPageNotFound`。 + * + */ + onPageNotFound?(options?: PageNotFoundOption): void; + } + + type AppConstructor = ( + options: AppInstance & T, + ) => void; + + interface GetAppOption { + /** + * 在 `App` 未定义时返回默认实现。当App被调用时,默认实现中定义的属性会被覆盖合并到App中。一般用于独立分包 + */ + allowDefault: boolean; + } + + type GetApp = (opts?: GetAppOption) => AppInstance & T; + } + +declare const getApp: App.GetApp; diff --git a/types/uni-app/lib/common.d.ts b/types/uni-app/lib/common.d.ts new file mode 100644 index 0000000000..c8c1ed7c54 --- /dev/null +++ b/types/uni-app/lib/common.d.ts @@ -0,0 +1,5 @@ +type AnyObject = Record; + +type KVInfer = { [K in keyof T]: T[K] }; + +type Void = T | undefined | null; diff --git a/types/uni-app/lib/page.d.ts b/types/uni-app/lib/page.d.ts new file mode 100644 index 0000000000..6b2b22b083 --- /dev/null +++ b/types/uni-app/lib/page.d.ts @@ -0,0 +1,152 @@ +declare namespace Page { + interface CustomShareContent { + /** + * 转发标题。默认值:当前应用名称 + */ + title?: string; + /** + * 转发路径,必须是以 / 开头的完整路径。默认值:当前页面 path + */ + path?: string; + /** + * 自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4,默认值:使用默认截图 + */ + imageUrl?: string; + } + + interface PageScrollOption { + /** + * 页面在垂直方向已滚动的距离(单位px) + */ + scrollTop: number; + } + + interface ShareAppMessageOption { + /** + * 转发事件来源。 + * 可选值: + * - `button`:页面内转发按钮; + * - `menu`:右上角转发菜单。 + * + */ + from: "button" | "menu" | string; + /** + * 如果 `from` 值是 `button`,则 `target` 是触发这次转发事件的 `button`,否则为 `undefined` + */ + target: any; + /** + * 页面中包含``组件时,返回当前``的url + */ + webViewUrl?: string; + } + + interface TabItemTapOption { + /** + * 被点击tabItem的序号,从0开始 + */ + index: string; + /** + * 被点击tabItem的页面路径 + */ + pagePath: string; + /** + * 被点击tabItem的按钮文字 + */ + text: string; + } + + interface PageInstanceBaseProps { + /** + * 到当前页面的路径,类型为`String` + */ + route?: string; + } + + interface PageInstance extends PageInstanceBaseProps { + /** + * 生命周期回调—监听页面加载 + * 页面加载时触发。一个页面只会调用一次,可以在 onLoad 的参数中获取打开当前页面路径中的参数。 + */ + onLoad?( + /** + * 打开当前页面路径中的参数 + */ + query?: { [queryKey: string]: string }, + ): void; + /** + * 生命周期回调—监听页面显示 + * 页面显示/切入前台时触发。 + */ + onShow?(): void; + /** + * 生命周期回调—监听页面初次渲染完成 + * 页面初次渲染完成时触发。一个页面只会调用一次,代表页面已经准备妥当,可以和视图层进行交互。 + */ + onReady?(): void; + /** + * 生命周期回调—监听页面隐藏 + * 页面隐藏/切入后台时触发。 如 `navigateTo` 或底部 `tab` 切换到其他页面,应用切入后台等。 + */ + onHide?(): void; + /** + * 生命周期回调—监听页面卸载 + * 页面卸载时触发。如`redirectTo`或`navigateBack`到其他页面时。 + */ + onUnload?(): void; + /** + * 监听用户下拉动作 + * 监听用户下拉刷新事件。 + * - 需要在`pages.json`的页面配置中开启`enablePullDownRefresh`。 + * - 可以通过`uni.startPullDownRefresh`触发下拉刷新,调用后触发下拉刷新动画,效果与用户手动下拉刷新一致。 + * - 当处理完数据刷新后,`uni.stopPullDownRefresh`可以停止当前页面的下拉刷新。 + */ + onPullDownRefresh?(): void; + /** + * 页面上拉触底事件的处理函数 + * 监听用户上拉触底事件。 + * - 可以在`pages.json`的页面配置中设置触发距离`onReachBottomDistance`。 + * - 在触发距离内滑动期间,本事件只会被触发一次。 + */ + onReachBottom?(): void; + /** + * 用户点击右上角转发 + * 监听用户点击页面内转发按钮(`