From e841096f2aab1d8e5df489575e4ffa6bff66d7ab Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 6 Feb 2022 14:28:19 +1100 Subject: [PATCH 01/23] shift core.es5 into core defs --- definitions/{npm/core.es5_v5.1.0 => core/es5-1}/README.md | 0 .../core.es5_v5.1.0.js => core/es5-1/flow_v0.104.x-/es5-1.js} | 0 .../test_lib.js => core/es5-1/flow_v0.104.x-/test_es5-1.js} | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename definitions/{npm/core.es5_v5.1.0 => core/es5-1}/README.md (100%) rename definitions/{npm/core.es5_v5.1.0/flow_v0.104.x-/core.es5_v5.1.0.js => core/es5-1/flow_v0.104.x-/es5-1.js} (100%) rename definitions/{npm/core.es5_v5.1.0/flow_v0.104.x-/test_lib.js => core/es5-1/flow_v0.104.x-/test_es5-1.js} (100%) diff --git a/definitions/npm/core.es5_v5.1.0/README.md b/definitions/core/es5-1/README.md similarity index 100% rename from definitions/npm/core.es5_v5.1.0/README.md rename to definitions/core/es5-1/README.md diff --git a/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-/core.es5_v5.1.0.js b/definitions/core/es5-1/flow_v0.104.x-/es5-1.js similarity index 100% rename from definitions/npm/core.es5_v5.1.0/flow_v0.104.x-/core.es5_v5.1.0.js rename to definitions/core/es5-1/flow_v0.104.x-/es5-1.js diff --git a/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-/test_lib.js b/definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js similarity index 100% rename from definitions/npm/core.es5_v5.1.0/flow_v0.104.x-/test_lib.js rename to definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js From 68a820515e71ddaa0dd97937dcb9e467cda3cb80 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 6 Feb 2022 14:52:08 +1100 Subject: [PATCH 02/23] add block where installation will occur --- cli/src/commands/install.js | 42 ++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index bf3b0dc0b4..548c75c761 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -46,6 +46,10 @@ import {createStub, pkgHasFlowFiles} from '../lib/stubUtils'; import typeof Yargs from 'yargs'; +type FtConfig = { + env?: mixed, // Array, +}; + export const name = 'install [explicitLibDefs...]'; export const description = 'Installs libdefs into the ./flow-typed directory'; export type Args = { @@ -178,9 +182,18 @@ export async function run(args: Args): Promise { return dep; }); - const coreLibDefResult = await installCoreLibDefs(); - if (coreLibDefResult !== 0) { - return coreLibDefResult; + let ftConfig: void | FtConfig; + try { + ftConfig = JSON.parse( + fs.readFileSync(path.join(cwd, libdefDir, 'ft-config.json'), 'utf-8'), + ); + } catch (e) {} + + if (ftConfig) { + const coreLibDefResult = await installCoreLibDefs(ftConfig); + if (coreLibDefResult !== 0) { + return coreLibDefResult; + } } if (args.cacheDir) { @@ -218,8 +231,27 @@ export async function run(args: Args): Promise { return 0; } -async function installCoreLibDefs(): Promise { - // TODO... +async function installCoreLibDefs({env}: FtConfig): Promise { + if (env) { + if (!Array.isArray(env)) { + console.log( + colors.yellow( + 'Warning: `env` in `ft-config.json` must be of type Array', + ), + ); + return 0; + } + + // Go through each env and try to install a libdef of the same name + // for the given flow version, + // if none is found throw a warning and continue. We shouldn't block the user. + env.forEach(en => { + if (typeof en === 'string') { + // Try install + } + }); + } + return 0; } From e446169f7418b8eba1570688d2ce4d750c994bd9 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 6 Feb 2022 14:54:06 +1100 Subject: [PATCH 03/23] add jsx as one of the first cores --- definitions/core/jsx/flow_v0.83.x-/jsx.js | 3 +++ definitions/core/jsx/flow_v0.83.x-/test_jsx.js | 0 2 files changed, 3 insertions(+) create mode 100644 definitions/core/jsx/flow_v0.83.x-/jsx.js create mode 100644 definitions/core/jsx/flow_v0.83.x-/test_jsx.js diff --git a/definitions/core/jsx/flow_v0.83.x-/jsx.js b/definitions/core/jsx/flow_v0.83.x-/jsx.js new file mode 100644 index 0000000000..07e81b4842 --- /dev/null +++ b/definitions/core/jsx/flow_v0.83.x-/jsx.js @@ -0,0 +1,3 @@ +declare type jsx$HTMLElementProps = {| + +|}; diff --git a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js b/definitions/core/jsx/flow_v0.83.x-/test_jsx.js new file mode 100644 index 0000000000..e69de29bb2 From 78861b77b513392432375b55aa35d8568523a4cc Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Mon, 7 Feb 2022 09:17:26 +1100 Subject: [PATCH 04/23] can run core tests, though they all fail --- cli/src/commands/runTests.js | 53 +++++++----- cli/src/lib/libDefs.js | 21 ++++- definitions/core/jsx/flow_v0.83.x-/jsx.js | 83 +++++++++++++++++++ .../core/jsx/flow_v0.83.x-/test_jsx.js | 20 +++++ 4 files changed, 154 insertions(+), 23 deletions(-) diff --git a/cli/src/commands/runTests.js b/cli/src/commands/runTests.js index c4e4cc7b57..e71cc7a7ac 100644 --- a/cli/src/commands/runTests.js +++ b/cli/src/commands/runTests.js @@ -54,12 +54,14 @@ type TestGroup = { * structs. Each TestGroup represents a Package/PackageVersion/FlowVersion * directory. */ -const basePathRegex = new RegExp('definitions/npm/(@[^/]*/)?[^/]*/?'); +const basePathRegex = new RegExp('definitions/(npm|core)/(@[^/]*/)?[^/]*/?'); async function getTestGroups( repoDirPath, + coreDirPath, onlyChanged: boolean = false, ): Promise> { let libDefs = await getLibDefs(repoDirPath); + let coreDefs = await getLibDefs(coreDirPath); if (onlyChanged) { const diff = await getDefinitionsDiff(); const baseDiff: string[] = diff @@ -80,10 +82,13 @@ async function getTestGroups( version: `v${major}.${minor}.${patch}`, }; }); - libDefs = libDefs.filter(def => - changedDefs.some( - d => d.name === def.pkgName && d.version === def.pkgVersionStr, - ), + libDefs = [...libDefs, ...coreDefs].filter(def => + changedDefs.some(d => { + if (d.version === 'vx.x.x') { + return d.name === def.pkgName; + } + return d.name === def.pkgName && d.version === def.pkgVersionStr; + }), ); } return libDefs.map(libDef => { @@ -611,27 +616,28 @@ async function runTestGroup( async function runTests( repoDirPath: string, + coreDirPath: string, testPatterns: Array, onlyChanged?: boolean, numberOfFlowVersions?: number, ): Promise>> { const testPatternRes = testPatterns.map(patt => new RegExp(patt, 'g')); - const testGroups = (await getTestGroups(repoDirPath, onlyChanged)).filter( - testGroup => { - if (testPatternRes.length === 0) { - return true; - } + const testGroups = ( + await getTestGroups(repoDirPath, coreDirPath, onlyChanged) + ).filter(testGroup => { + if (testPatternRes.length === 0) { + return true; + } - for (var i = 0; i < testPatternRes.length; i++) { - const pattern = testPatternRes[i]; - if (testGroup.id.match(pattern) != null) { - return true; - } + for (var i = 0; i < testPatternRes.length; i++) { + const pattern = testPatternRes[i]; + if (testGroup.id.match(pattern) != null) { + return true; } + } - return false; - }, - ); + return false; + }); try { // Create a temp dir to copy files into to run the tests @@ -727,21 +733,25 @@ export async function run(argv: Args): Promise { const cwd = process.cwd(); const basePath = argv.path ? String(argv.path) : cwd; const cwdDefsNPMPath = path.join(basePath, 'definitions', 'npm'); - let repoDirPath = (await fs.exists(cwdDefsNPMPath)) + const repoDirPath = (await fs.exists(cwdDefsNPMPath)) ? cwdDefsNPMPath : path.join(__dirname, '..', '..', '..', 'definitions', 'npm'); + const cwdDefsCorePath = path.join(basePath, 'definitions', 'core'); + const coreDirPath = (await fs.exists(cwdDefsCorePath)) + ? cwdDefsCorePath + : path.join(__dirname, '..', '..', '..', 'definitions', 'npm'); if (onlyChanged) { console.log( 'Running changed definition tests against latest %s flow versions in %s...\n', numberOfFlowVersions, - repoDirPath, + path.join(repoDirPath, '..'), ); } else { console.log( 'Running definition tests against latest %s flow versions in %s...\n', numberOfFlowVersions, - repoDirPath, + path.join(repoDirPath, '..'), ); } @@ -749,6 +759,7 @@ export async function run(argv: Args): Promise { try { results = await runTests( repoDirPath, + coreDirPath, testPatterns, onlyChanged, numberOfFlowVersions, diff --git a/cli/src/lib/libDefs.js b/cli/src/lib/libDefs.js index 0883d3082f..e545104924 100644 --- a/cli/src/lib/libDefs.js +++ b/cli/src/lib/libDefs.js @@ -161,7 +161,7 @@ async function addLibDefs(pkgDirPath, libDefs: Array) { } /** - * Given a 'definitions/npm' dir, return a list of LibDefs that it contains. + * Given a 'definitions/...' dir, return a list of LibDefs that it contains. */ export async function getLibDefs(defsDir: string): Promise> { const libDefs: Array = []; @@ -261,7 +261,10 @@ async function parseLibDefsFromPkgDir( const testFilePaths = [].concat(commonTestFiles); const basePkgName = pkgName.charAt(0) === '@' ? pkgName.split(path.sep).pop() : pkgName; - const libDefFileName = `${basePkgName}_${pkgVersionStr}.js`; + const libDefFileName = + pkgVersionStr === 'vx.x.x' + ? `${basePkgName}.js` + : `${basePkgName}_${pkgVersionStr}.js`; let libDefFilePath; (await fs.readdir(flowDirPath)).forEach(flowDirItem => { const flowDirItemPath = path.join(flowDirPath, flowDirItem); @@ -327,6 +330,20 @@ export function parseRepoDirItem( pkgVersion: Version, |} { const dirItem = path.basename(dirItemPath); + + // Core definitions don't have versions nor need any sort of name validation + if (dirItemPath.includes('definitions/core')) { + return { + pkgName: dirItem, + pkgVersion: { + major: 'x', + minor: 'x', + patch: 'x', + prerel: null, + }, + }; + } + const itemMatches = dirItem.match(REPO_DIR_ITEM_NAME_RE); if (itemMatches == null) { const error = diff --git a/definitions/core/jsx/flow_v0.83.x-/jsx.js b/definitions/core/jsx/flow_v0.83.x-/jsx.js index 07e81b4842..2dce3117ba 100644 --- a/definitions/core/jsx/flow_v0.83.x-/jsx.js +++ b/definitions/core/jsx/flow_v0.83.x-/jsx.js @@ -1,3 +1,86 @@ +// @flow + declare type jsx$HTMLElementProps = {| + /** + * Specifies a shortcut key to activate/focus an element + */ + accessKey?: string, + /** + * Specifies one or more classnames for an element (refers to a class in a style sheet) + */ + className?: string, + /** + * Specifies whether the content of an element is editable or not + */ + contentEditable?: string, + /** + * Specifies meta tag for application testing or querying + */ + 'data-testid'?: string, + /** + * Specifies the text direction for the content in an element + */ + dir?: string, + /** + * Specifies whether an element is draggable or not + */ + draggable?: string, + /** + * Specifies that an element is not yet, or is no longer, relevant + */ + hidden?: string, + /** + * Specifies a unique id for an element + */ + id?: string, + /** + * Specifies the language of the element's content + */ + lang?: string, + /** + * Specifies whether the element is to have its spelling and grammar checked or not + */ + spellCheck?: string, + /** + * Specifies the tabbing order of an element + */ + tabIndex?: string, + /** + * Specifies extra information about an element + */ + title?: string, + /** + * Specifies whether the content of an element should be translated or not + */ + translate?: string, +|}; + +declare type jsx$HTMLInputElementProps$Type = + | 'button' + | 'checkbox' + | 'color' + | 'date' + | 'datetime-local' + | 'email' + | 'file' + | 'hidden' + | 'image' + | 'month' + | 'number' + | 'password' + | 'radio' + | 'range' + | 'reset' + | 'search' + | 'submit' + | 'tel' + | 'text' + | 'time' + | 'url' + | 'week'; +declare type jsx$HTMLInputElementProps = {| + ...jsx$HTMLElementProps, + value?: string, + type?: jsx$HTMLInputElementProps$Type, |}; diff --git a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js b/definitions/core/jsx/flow_v0.83.x-/test_jsx.js index e69de29bb2..73e7f7b178 100644 --- a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js +++ b/definitions/core/jsx/flow_v0.83.x-/test_jsx.js @@ -0,0 +1,20 @@ +// @flow +import * as React from 'react'; + +describe('jsx', () => { + it('has input props', () => { + type Props = {| + ...jsx$HTMLElementProps, + foo: string, + |} + + const Input = ({ + foo, + + }: Props) => { + return ( + + ) + } + }); +}); From 41610c882f8bcdf3d1ac892e0b4eb375bc166747 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 9 Feb 2022 05:57:53 +1100 Subject: [PATCH 05/23] fix tests --- definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js | 12 ------------ .../es5-1.js | 0 .../core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js | 12 ++++++++++++ definitions/core/jsx/flow_v0.83.x-/test_jsx.js | 1 + 4 files changed, 13 insertions(+), 12 deletions(-) delete mode 100644 definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js rename definitions/core/es5-1/{flow_v0.104.x- => flow_v0.104.x-v0.150.x}/es5-1.js (100%) create mode 100644 definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js diff --git a/definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js b/definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js deleted file mode 100644 index fe3c4e10f7..0000000000 --- a/definitions/core/es5-1/flow_v0.104.x-/test_es5-1.js +++ /dev/null @@ -1,12 +0,0 @@ -// @flow strict - -// $FlowExpectedError -var x:string = NaN -// $FlowExpectedError -var y:string = Number.MAX_VALUE; -// $FlowExpectedError -var z:number = new TypeError().name; -// $FlowExpectedError -var w:string = parseInt("..."); -// $FlowExpectedError -const ra: $ReadOnlyArray = Object.freeze({q:2}); diff --git a/definitions/core/es5-1/flow_v0.104.x-/es5-1.js b/definitions/core/es5-1/flow_v0.104.x-v0.150.x/es5-1.js similarity index 100% rename from definitions/core/es5-1/flow_v0.104.x-/es5-1.js rename to definitions/core/es5-1/flow_v0.104.x-v0.150.x/es5-1.js diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js b/definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js new file mode 100644 index 0000000000..21a45c8e5d --- /dev/null +++ b/definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js @@ -0,0 +1,12 @@ +// @flow strict + +// $FlowExpectedError[incompatible-type] +var x:string = NaN +// $FlowExpectedError[incompatible-type] +var y:string = Number.MAX_VALUE; +// $FlowExpectedError[incompatible-type] +var z:number = new TypeError().name; +// $FlowExpectedError[incompatible-type] +var w:string = parseInt("..."); +// $FlowExpectedError[incompatible-type] +const ra: $ReadOnlyArray = Object.freeze({q:2}); diff --git a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js b/definitions/core/jsx/flow_v0.83.x-/test_jsx.js index 73e7f7b178..6f312f5642 100644 --- a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js +++ b/definitions/core/jsx/flow_v0.83.x-/test_jsx.js @@ -1,4 +1,5 @@ // @flow +import { describe, it } from 'flow-typed-test'; import * as React from 'react'; describe('jsx', () => { From aaa3116754fb6e94e9faeba117b25428553f386f Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 9 Feb 2022 07:12:44 +1100 Subject: [PATCH 06/23] update flow version compat for es5-1 --- .../{flow_v0.104.x-v0.150.x => flow_v0.104.x-v0.142.x}/es5-1.js | 0 .../test_es5-1.js | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename definitions/core/es5-1/{flow_v0.104.x-v0.150.x => flow_v0.104.x-v0.142.x}/es5-1.js (100%) rename definitions/core/es5-1/{flow_v0.104.x-v0.150.x => flow_v0.104.x-v0.142.x}/test_es5-1.js (100%) diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.150.x/es5-1.js b/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js similarity index 100% rename from definitions/core/es5-1/flow_v0.104.x-v0.150.x/es5-1.js rename to definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js b/definitions/core/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js similarity index 100% rename from definitions/core/es5-1/flow_v0.104.x-v0.150.x/test_es5-1.js rename to definitions/core/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js From 2c3ea1eef6eec70ff62a81e19b76258513565e4e Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 9 Feb 2022 07:38:30 +1100 Subject: [PATCH 07/23] shift install order --- cli/src/commands/install.js | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 548c75c761..1b5aabc53f 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -189,13 +189,6 @@ export async function run(args: Args): Promise { ); } catch (e) {} - if (ftConfig) { - const coreLibDefResult = await installCoreLibDefs(ftConfig); - if (coreLibDefResult !== 0) { - return coreLibDefResult; - } - } - if (args.cacheDir) { const cacheDir = path.resolve(String(args.cacheDir)); console.log('• Setting cache dir', cacheDir); @@ -218,6 +211,14 @@ export async function run(args: Args): Promise { return npmLibDefResult; } + // Must be after `installNpmLibDefs` to ensure cache is updated first + if (ftConfig) { + const coreLibDefResult = await installCoreLibDefs(ftConfig); + if (coreLibDefResult !== 0) { + return coreLibDefResult; + } + } + // Once complete restart flow to solve flow issues when scanning large diffs if (!args.skipFlowRestart) { try { From 83198ede3b85581277a37d68258f142a3dc59a87 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sat, 12 Feb 2022 10:40:20 +1100 Subject: [PATCH 08/23] add prep comments --- cli/src/commands/install.js | 8 ++++++++ cli/src/lib/coreDefs.js | 0 2 files changed, 8 insertions(+) create mode 100644 cli/src/lib/coreDefs.js diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 1b5aabc53f..c764e40c85 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -243,12 +243,20 @@ async function installCoreLibDefs({env}: FtConfig): Promise { return 0; } + // Get a list of all core defs + // getNpmLibDefs(path.join(getCacheRepoDir(), 'definitions')); + // Go through each env and try to install a libdef of the same name // for the given flow version, // if none is found throw a warning and continue. We shouldn't block the user. env.forEach(en => { if (typeof en === 'string') { // Try install + // 1. Check if it's already installed + // 2. Check if it's been overriden + // 3. Uninstall prev installed + // 4. With cached def, code sign it + // 5. Write it to dir } }); } diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/coreDefs.js new file mode 100644 index 0000000000..e69de29bb2 From 7617f10b1252a29c53c70b438a7ad0a4ec917fd3 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 13 Feb 2022 11:16:49 +1100 Subject: [PATCH 09/23] get list of all core defs into install --- cli/src/commands/install.js | 45 ++++++----- cli/src/lib/coreDefs.js | 147 ++++++++++++++++++++++++++++++++++++ 2 files changed, 169 insertions(+), 23 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index c764e40c85..6350263a53 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -1,18 +1,23 @@ // @flow +import colors from 'colors/safe'; +import semver from 'semver'; +import typeof Yargs from 'yargs'; + +import { + getCacheRepoDir, + _setCustomCacheDir as setCustomCacheDir, + CACHE_REPO_EXPIRY, +} from '../lib/cacheRepoUtils'; import {signCodeStream} from '../lib/codeSign'; +import {getCoreDefs} from '../lib/coreDefs'; import {copyFile, mkdirp} from '../lib/fileUtils'; -import {child_process} from '../lib/node'; - import {findFlowRoot} from '../lib/flowProjectUtils'; - import { toSemverString as flowVersionToSemver, determineFlowSpecificVersion, + type FlowVersion, } from '../lib/flowVersion'; -import type {FlowVersion} from '../lib/flowVersion'; - -import {fs, path} from '../lib/node'; - +import {fs, path, child_process} from '../lib/node'; import { findNpmLibDef, getCacheNpmLibDefs, @@ -21,7 +26,6 @@ import { getScopedPackageName, type NpmLibDef, } from '../lib/npm/npmLibDefs'; - import { findWorkspacesPackages, getPackageJsonData, @@ -29,23 +33,9 @@ import { loadPnpResolver, mergePackageJsonDependencies, } from '../lib/npm/npmProjectUtils'; - -import { - getCacheRepoDir, - _setCustomCacheDir as setCustomCacheDir, - CACHE_REPO_EXPIRY, -} from '../lib/cacheRepoUtils'; - import {getRangeLowerBound} from '../lib/semver'; - -import colors from 'colors/safe'; - -import semver from 'semver'; - import {createStub, pkgHasFlowFiles} from '../lib/stubUtils'; -import typeof Yargs from 'yargs'; - type FtConfig = { env?: mixed, // Array, }; @@ -244,15 +234,23 @@ async function installCoreLibDefs({env}: FtConfig): Promise { } // Get a list of all core defs - // getNpmLibDefs(path.join(getCacheRepoDir(), 'definitions')); + const coreDefs = await getCoreDefs(); + + console.log(coreDefs); // Go through each env and try to install a libdef of the same name // for the given flow version, // if none is found throw a warning and continue. We shouldn't block the user. env.forEach(en => { if (typeof en === 'string') { + const def = coreDefs.find(def => def === en); + + if (def) { + // install it here + } // Try install // 1. Check if it's already installed + // - if not install it immediately // 2. Check if it's been overriden // 3. Uninstall prev installed // 4. With cached def, code sign it @@ -388,6 +386,7 @@ async function installNpmLibDefs({ ][] = []; const unavailableLibDefs = []; + // This updates the cache for all definition types, npm/core/etc const libDefs = await getCacheNpmLibDefs(useCacheUntil, skipCache); const getLibDefsToInstall = async (entries: Array<[string, string]>) => { diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/coreDefs.js index e69de29bb2..5fe42bf530 100644 --- a/cli/src/lib/coreDefs.js +++ b/cli/src/lib/coreDefs.js @@ -0,0 +1,147 @@ +// @flow +import path from 'path'; + +import {getCacheRepoDir} from './cacheRepoUtils'; +import {fs} from './node'; +import {ValidationError} from './ValidationError'; +import { + disjointVersionsAll as disjointFlowVersionsAll, + parseDirString as parseFlowDirString, + type FlowVersion, +} from './flowVersion'; +import {TEST_FILE_NAME_RE} from './libDefs'; + +type CoreLibDef = { + name: string, + flowVersion: FlowVersion, + path: string, + testFilePaths: Array, +}; + +export const getCoreDefs = async (): Promise> => { + const definitionsDir = path.join(getCacheRepoDir(), 'definitions'); + const coreDefsDirPath = path.join(definitionsDir, 'core'); + + const dirItems = await fs.readdir(coreDefsDirPath); + const errors = []; + const proms = dirItems.map(async itemName => { + // If a user opens definitions dir in finder it will create `.DS_Store` + // which will need to be excluded while parsing + if (itemName === '.DS_Store') return; + + try { + return await getSingleCoreDef(itemName, coreDefsDirPath); + } catch (e) { + errors.push(e); + } + }); + + const settled = await Promise.all(proms); + if (errors.length) { + throw errors; + } + return [...settled].filter(Boolean); +}; + +const getSingleCoreDef = async (defName, coreDefPath) => { + const itemPath = path.join(coreDefPath, defName); + const itemStat = await fs.stat(itemPath); + if (itemStat.isDirectory()) { + // itemPath must be an env dir + return await extractLibDefsFromNpmPkgDir(itemPath, defName); + } else { + throw new ValidationError( + `Expected only directories to be present in this directory.`, + ); + } +}; + +async function extractLibDefsFromNpmPkgDir( + envDirPath: string, + defName: string, +): Promise> { + const coreDefFileName = `${defName}.js`; + const envDirItems = await fs.readdir(envDirPath); + + const commonTestFiles = []; + const parsedFlowDirs: Array<[string, FlowVersion]> = []; + envDirItems.forEach(envDirItem => { + const envDirItemPath = path.join(envDirPath, envDirItem); + + const envDirItemStat = fs.statSync(envDirItemPath); + if (envDirItemStat.isFile()) { + const isValidTestFile = TEST_FILE_NAME_RE.test(envDirItem); + if (isValidTestFile) commonTestFiles.push(envDirItemPath); + } else if (envDirItemStat.isDirectory()) { + const parsedFlowDir = parseFlowDirString(envDirItem); + parsedFlowDirs.push([envDirItemPath, parsedFlowDir]); + } else { + throw new ValidationError('Unexpected directory item'); + } + }); + + if (!disjointFlowVersionsAll(parsedFlowDirs.map(([_, ver]) => ver))) { + throw new ValidationError('Flow versions not disjoint!'); + } + + if (parsedFlowDirs.length === 0) { + throw new ValidationError('No libdef files found!'); + } + + const coreDefs = []; + await Promise.all( + parsedFlowDirs.map(async ([flowDirPath, flowVersion]) => { + const testFilePaths = [...commonTestFiles]; + let libDefFilePath: null | string = null; + (await fs.readdir(flowDirPath)).forEach(flowDirItem => { + const flowDirItemPath = path.join(flowDirPath, flowDirItem); + const flowDirItemStat = fs.statSync(flowDirItemPath); + if (flowDirItemStat.isFile()) { + if (path.extname(flowDirItem) === '.swp') { + return; + } + + // Is this the libdef file? + if (flowDirItem === coreDefFileName) { + libDefFilePath = path.join(flowDirPath, flowDirItem); + return; + } + + // Is this a test file? + const isValidTestFile = TEST_FILE_NAME_RE.test(flowDirItem); + + if (isValidTestFile) { + testFilePaths.push(flowDirItemPath); + return; + } + + throw new ValidationError( + `Unexpected file: ${coreDefFileName}. This directory can only contain test files ` + + `or a libdef file named \`${coreDefFileName}\`.`, + ); + } else { + throw new ValidationError( + `Unexpected sub-directory. This directory can only contain test ` + + `files or a libdef file named \`${coreDefFileName}\`.`, + ); + } + }); + + if (libDefFilePath === null) { + libDefFilePath = path.join(flowDirPath, coreDefFileName); + throw new ValidationError( + `No libdef file found. Looking for a file named ${coreDefFileName}`, + ); + } + + coreDefs.push({ + name: defName, + flowVersion, + path: libDefFilePath, + testFilePaths, + }); + }), + ); + + return coreDefs; +} From 02412df5f632f74566d504aafffe56646253476a Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 13 Feb 2022 15:16:01 +1100 Subject: [PATCH 10/23] able to find matching core defs --- cli/src/commands/install.js | 67 ++++++++++++++++++++++++++----------- cli/src/lib/coreDefs.js | 30 +++++++++++++++++ 2 files changed, 77 insertions(+), 20 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 6350263a53..6774b313dd 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -9,7 +9,7 @@ import { CACHE_REPO_EXPIRY, } from '../lib/cacheRepoUtils'; import {signCodeStream} from '../lib/codeSign'; -import {getCoreDefs} from '../lib/coreDefs'; +import {getCoreDefs, findCoreDef} from '../lib/coreDefs'; import {copyFile, mkdirp} from '../lib/fileUtils'; import {findFlowRoot} from '../lib/flowProjectUtils'; import { @@ -185,6 +185,8 @@ export async function run(args: Args): Promise { setCustomCacheDir(cacheDir); } + const useCacheUntil = Number(args.useCacheUntil) || CACHE_REPO_EXPIRY; + const npmLibDefResult = await installNpmLibDefs({ cwd, flowVersion, @@ -203,7 +205,11 @@ export async function run(args: Args): Promise { // Must be after `installNpmLibDefs` to ensure cache is updated first if (ftConfig) { - const coreLibDefResult = await installCoreLibDefs(ftConfig); + const coreLibDefResult = await installCoreLibDefs( + ftConfig, + flowVersion, + useCacheUntil, + ); if (coreLibDefResult !== 0) { return coreLibDefResult; } @@ -222,8 +228,18 @@ export async function run(args: Args): Promise { return 0; } -async function installCoreLibDefs({env}: FtConfig): Promise { +async function installCoreLibDefs( + {env}: FtConfig, + flowVersion: FlowVersion, + useCacheUntil: number, +): Promise { if (env) { + console.log( + colors.green( + '`env` key found in `ft-config`, attempting to install core definitions...', + ), + ); + if (!Array.isArray(env)) { console.log( colors.yellow( @@ -234,29 +250,40 @@ async function installCoreLibDefs({env}: FtConfig): Promise { } // Get a list of all core defs - const coreDefs = await getCoreDefs(); - - console.log(coreDefs); + const coreDefs = (await getCoreDefs()).flat(); // Go through each env and try to install a libdef of the same name // for the given flow version, // if none is found throw a warning and continue. We shouldn't block the user. - env.forEach(en => { - if (typeof en === 'string') { - const def = coreDefs.find(def => def === en); + await Promise.all( + env.map(async en => { + if (typeof en === 'string') { + const def = await findCoreDef( + en, + flowVersion, + useCacheUntil, + coreDefs, + ); - if (def) { - // install it here + if (def) { + // install it here + } else { + console.log( + colors.yellow( + `Was unable to install ${en}. The env might not exist or there is not a version compatible with your version of flow`, + ), + ); + } + // Try install + // 1. Check if it's already installed + // - if not install it immediately + // 2. Check if it's been overriden + // 3. Uninstall prev installed + // 4. With cached def, code sign it + // 5. Write it to dir } - // Try install - // 1. Check if it's already installed - // - if not install it immediately - // 2. Check if it's been overriden - // 3. Uninstall prev installed - // 4. With cached def, code sign it - // 5. Write it to dir - } - }); + }), + ); } return 0; diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/coreDefs.js index 5fe42bf530..9cc34d6070 100644 --- a/cli/src/lib/coreDefs.js +++ b/cli/src/lib/coreDefs.js @@ -1,5 +1,6 @@ // @flow import path from 'path'; +import semver from 'semver'; import {getCacheRepoDir} from './cacheRepoUtils'; import {fs} from './node'; @@ -7,6 +8,7 @@ import {ValidationError} from './ValidationError'; import { disjointVersionsAll as disjointFlowVersionsAll, parseDirString as parseFlowDirString, + toSemverString as flowVersionToSemver, type FlowVersion, } from './flowVersion'; import {TEST_FILE_NAME_RE} from './libDefs'; @@ -145,3 +147,31 @@ async function extractLibDefsFromNpmPkgDir( return coreDefs; } + +export const findCoreDef = ( + defName: string, + flowVersion: FlowVersion, + useCacheUntil: number, + coreDefs: Array, +): CoreLibDef | void => { + return coreDefs.filter(def => { + let filterMatch = def.name === defName; + + if (!filterMatch) { + return false; + } + + switch (def.flowVersion.kind) { + case 'all': + return true; + case 'ranged': + case 'specific': + return semver.satisfies( + flowVersionToSemver(flowVersion), + flowVersionToSemver(def.flowVersion), + ); + default: + return true; + } + })[0]; +}; From ab01aa9a77c0cf51e36be9d864f6383dd84c2661 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 13 Feb 2022 15:34:15 +1100 Subject: [PATCH 11/23] update comments for next steps --- cli/src/commands/install.js | 31 +++++++++++++++++++++---------- 1 file changed, 21 insertions(+), 10 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 6774b313dd..d6ad50256d 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -208,6 +208,8 @@ export async function run(args: Args): Promise { const coreLibDefResult = await installCoreLibDefs( ftConfig, flowVersion, + cwd, + libdefDir, useCacheUntil, ); if (coreLibDefResult !== 0) { @@ -231,19 +233,21 @@ export async function run(args: Args): Promise { async function installCoreLibDefs( {env}: FtConfig, flowVersion: FlowVersion, + flowProjectRoot, + libdefDir, useCacheUntil: number, ): Promise { if (env) { console.log( colors.green( - '`env` key found in `ft-config`, attempting to install core definitions...', + '• `env` key found in `ft-config`, attempting to install core definitions...', ), ); if (!Array.isArray(env)) { console.log( colors.yellow( - 'Warning: `env` in `ft-config.json` must be of type Array', + 'Warning: `env` in `ft-config.json` must be of type Array - skipping', ), ); return 0; @@ -252,6 +256,9 @@ async function installCoreLibDefs( // Get a list of all core defs const coreDefs = (await getCoreDefs()).flat(); + const flowTypedDirPath = path.join(flowProjectRoot, libdefDir, 'core'); + await mkdirp(flowTypedDirPath); + // Go through each env and try to install a libdef of the same name // for the given flow version, // if none is found throw a warning and continue. We shouldn't block the user. @@ -266,7 +273,18 @@ async function installCoreLibDefs( ); if (def) { - // install it here + // check it needs to be deleted first + // const toUninstall = libDefsToUninstall.get( + // getScopedPackageName(libDef), + // ); + // delete it + // if (toUninstall != null) { + // await fs.unlink(toUninstall); + // } + // try to install it now, which if it still exists we know + // it's been modified and we will flag it unless `overwrite` + // is passed + // installNpmLibDef(libDef, flowTypedDirPath, overwrite); } else { console.log( colors.yellow( @@ -274,13 +292,6 @@ async function installCoreLibDefs( ), ); } - // Try install - // 1. Check if it's already installed - // - if not install it immediately - // 2. Check if it's been overriden - // 3. Uninstall prev installed - // 4. With cached def, code sign it - // 5. Write it to dir } }), ); From 458fc6d52cade8c05cffddb54dc0718d8a02615b Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 13:40:08 +1100 Subject: [PATCH 12/23] can install core defs --- cli/src/commands/install.js | 34 ++++++++++++++++++++++++++++++++-- cli/src/lib/coreDefs.js | 14 ++++++++++++++ 2 files changed, 46 insertions(+), 2 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index d6ad50256d..7a6c2bb0ed 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -9,7 +9,7 @@ import { CACHE_REPO_EXPIRY, } from '../lib/cacheRepoUtils'; import {signCodeStream} from '../lib/codeSign'; -import {getCoreDefs, findCoreDef} from '../lib/coreDefs'; +import {getCoreDefs, findCoreDef, getCoreDefVersionHash} from '../lib/coreDefs'; import {copyFile, mkdirp} from '../lib/fileUtils'; import {findFlowRoot} from '../lib/flowProjectUtils'; import { @@ -240,7 +240,7 @@ async function installCoreLibDefs( if (env) { console.log( colors.green( - '• `env` key found in `ft-config`, attempting to install core definitions...', + '• `env` key found in `ft-config`, attempting to install core definitions...\n', ), ); @@ -273,6 +273,34 @@ async function installCoreLibDefs( ); if (def) { + const fileName = `${en}.js`; + const defLocalPath = path.join(flowTypedDirPath, fileName); + const envAlreadyInstalled = await fs.exists(defLocalPath); + if (envAlreadyInstalled) { + // try generate signature and compare with def + // only if not overwrite mode enabled + // if they are not the same then it's been overwritten + // and log a message and then return + // otherwise delete it so that later steps can install it + // return; + } + + const repoVersion = await getCoreDefVersionHash( + getCacheRepoDir(), + def, + ); + const codeSignPreprocessor = signCodeStream(repoVersion); + await copyFile(def.path, defLocalPath, codeSignPreprocessor); + + console.log( + colors.bold(' • %s\n' + ' └> %s'), + en, + colors.green(`.${defLocalPath}`), + ); + // if def does not exist install it + // otherwise read the file and compare the signature + // if + // check it needs to be deleted first // const toUninstall = libDefsToUninstall.get( // getScopedPackageName(libDef), @@ -287,6 +315,8 @@ async function installCoreLibDefs( // installNpmLibDef(libDef, flowTypedDirPath, overwrite); } else { console.log( + colors.bold(' • %s\n' + ' └> %s'), + en, colors.yellow( `Was unable to install ${en}. The env might not exist or there is not a version compatible with your version of flow`, ), diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/coreDefs.js index 9cc34d6070..2bf5e12776 100644 --- a/cli/src/lib/coreDefs.js +++ b/cli/src/lib/coreDefs.js @@ -12,6 +12,7 @@ import { type FlowVersion, } from './flowVersion'; import {TEST_FILE_NAME_RE} from './libDefs'; +import {findLatestFileCommitHash} from './git'; type CoreLibDef = { name: string, @@ -175,3 +176,16 @@ export const findCoreDef = ( } })[0]; }; + +export async function getCoreDefVersionHash( + repoDirPath: string, + libDef: CoreLibDef, +): Promise { + const latestCommitHash = await findLatestFileCommitHash( + repoDirPath, + path.relative(repoDirPath, libDef.path), + ); + return `${latestCommitHash.substr(0, 10)}/${ + libDef.name + }/flow_${flowVersionToSemver(libDef.flowVersion)}`; +} From ad387838136469b416bf80b43733185fd898a2bc Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 13:59:31 +1100 Subject: [PATCH 13/23] detects if def has been overwritten --- cli/src/commands/install.js | 65 ++++++++++++------- .../es5-1/flow_v0.104.x-v0.142.x/es5-1.js | 1 - definitions/core/jsx/flow_v0.83.x-/jsx.js | 2 - 3 files changed, 40 insertions(+), 28 deletions(-) diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 7a6c2bb0ed..94aaa84395 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -8,7 +8,7 @@ import { _setCustomCacheDir as setCustomCacheDir, CACHE_REPO_EXPIRY, } from '../lib/cacheRepoUtils'; -import {signCodeStream} from '../lib/codeSign'; +import {signCodeStream, verifySignedCode} from '../lib/codeSign'; import {getCoreDefs, findCoreDef, getCoreDefVersionHash} from '../lib/coreDefs'; import {copyFile, mkdirp} from '../lib/fileUtils'; import {findFlowRoot} from '../lib/flowProjectUtils'; @@ -211,6 +211,7 @@ export async function run(args: Args): Promise { cwd, libdefDir, useCacheUntil, + Boolean(args.overwrite), ); if (coreLibDefResult !== 0) { return coreLibDefResult; @@ -236,6 +237,7 @@ async function installCoreLibDefs( flowProjectRoot, libdefDir, useCacheUntil: number, + overwrite: boolean, ): Promise { if (env) { console.log( @@ -277,12 +279,39 @@ async function installCoreLibDefs( const defLocalPath = path.join(flowTypedDirPath, fileName); const envAlreadyInstalled = await fs.exists(defLocalPath); if (envAlreadyInstalled) { - // try generate signature and compare with def - // only if not overwrite mode enabled - // if they are not the same then it's been overwritten - // and log a message and then return - // otherwise delete it so that later steps can install it - // return; + const localFile = fs.readFileSync(defLocalPath, 'utf-8'); + + if (!verifySignedCode(localFile) && !overwrite) { + console.log( + colors.bold( + ' • %s\n' + + ' └> %s\n' + + ' %s\n' + + ' %s\n' + + ' %s\n' + + ' %s', + ), + en, + colors.red( + `${en} already exists and appears to have been manually written or changed!`, + ), + colors.yellow( + `Consider contributing your changes back to flow-typed repository :)`, + ), + colors.yellow( + `${en} already exists and appears to have been manually written or changed!`, + ), + colors.yellow( + `Read more at https://github.com/flow-typed/flow-typed/blob/master/CONTRIBUTING.md`, + ), + colors.yellow( + `Use --overwrite to overwrite the existing core defs.`, + ), + ); + return; + } + + fs.unlink(defLocalPath); } const repoVersion = await getCoreDefVersionHash( @@ -295,24 +324,10 @@ async function installCoreLibDefs( console.log( colors.bold(' • %s\n' + ' └> %s'), en, - colors.green(`.${defLocalPath}`), + colors.green( + `.${path.sep}${path.relative(flowProjectRoot, defLocalPath)}`, + ), ); - // if def does not exist install it - // otherwise read the file and compare the signature - // if - - // check it needs to be deleted first - // const toUninstall = libDefsToUninstall.get( - // getScopedPackageName(libDef), - // ); - // delete it - // if (toUninstall != null) { - // await fs.unlink(toUninstall); - // } - // try to install it now, which if it still exists we know - // it's been modified and we will flag it unless `overwrite` - // is passed - // installNpmLibDef(libDef, flowTypedDirPath, overwrite); } else { console.log( colors.bold(' • %s\n' + ' └> %s'), @@ -708,7 +723,7 @@ async function installNpmLibDef( colors.green( `Consider contributing your changes back to flow-typed repository :)`, ), - `Read more at https://github.com/flowtype/flow-typed/wiki/Contributing-Library-Definitions`, + `Read more at https://github.com/flow-typed/flow-typed/blob/master/CONTRIBUTING.md`, 'Use --overwrite to overwrite the existing libdef.', ); return true; diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js b/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js index 5a09f91b5e..a37aaff608 100644 --- a/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js +++ b/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js @@ -4,7 +4,6 @@ * cf. https://github.com/microsoft/TypeScript/blob/master/lib/lib.es5.d.ts * Flowgen v1.10.0 * and somewhat updated by comparison with the core lib built into Flow - * @flow */ declare var NaN: number; diff --git a/definitions/core/jsx/flow_v0.83.x-/jsx.js b/definitions/core/jsx/flow_v0.83.x-/jsx.js index 2dce3117ba..4739ab4da5 100644 --- a/definitions/core/jsx/flow_v0.83.x-/jsx.js +++ b/definitions/core/jsx/flow_v0.83.x-/jsx.js @@ -1,5 +1,3 @@ -// @flow - declare type jsx$HTMLElementProps = {| /** * Specifies a shortcut key to activate/focus an element From 2658ecc528d9acb51bbe275238326fd6d6c6fdd8 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 14:53:55 +1100 Subject: [PATCH 14/23] outdated handled --- cli/src/commands/install.js | 14 ++----- cli/src/commands/outdated.js | 79 ++++++++++++++++++++++++++++++++---- cli/src/lib/coreDefs.js | 6 +-- cli/src/lib/ftConfig.js | 17 ++++++++ 4 files changed, 94 insertions(+), 22 deletions(-) create mode 100644 cli/src/lib/ftConfig.js diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index 94aaa84395..dade44f223 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -17,6 +17,7 @@ import { determineFlowSpecificVersion, type FlowVersion, } from '../lib/flowVersion'; +import {getFtConfig, type FtConfig} from '../lib/ftConfig'; import {fs, path, child_process} from '../lib/node'; import { findNpmLibDef, @@ -36,10 +37,6 @@ import { import {getRangeLowerBound} from '../lib/semver'; import {createStub, pkgHasFlowFiles} from '../lib/stubUtils'; -type FtConfig = { - env?: mixed, // Array, -}; - export const name = 'install [explicitLibDefs...]'; export const description = 'Installs libdefs into the ./flow-typed directory'; export type Args = { @@ -172,12 +169,7 @@ export async function run(args: Args): Promise { return dep; }); - let ftConfig: void | FtConfig; - try { - ftConfig = JSON.parse( - fs.readFileSync(path.join(cwd, libdefDir, 'ft-config.json'), 'utf-8'), - ); - } catch (e) {} + const ftConfig = getFtConfig(cwd, libdefDir); if (args.cacheDir) { const cacheDir = path.resolve(String(args.cacheDir)); @@ -256,7 +248,7 @@ async function installCoreLibDefs( } // Get a list of all core defs - const coreDefs = (await getCoreDefs()).flat(); + const coreDefs = await getCoreDefs(); const flowTypedDirPath = path.join(flowProjectRoot, libdefDir, 'core'); await mkdirp(flowTypedDirPath); diff --git a/cli/src/commands/outdated.js b/cli/src/commands/outdated.js index 05835622e0..fb32d25e40 100644 --- a/cli/src/commands/outdated.js +++ b/cli/src/commands/outdated.js @@ -14,6 +14,10 @@ import {fs} from '../lib/node'; import {determineFlowSpecificVersion} from '../lib/flowVersion'; import {signCodeStream} from '../lib/codeSign'; import {CACHE_REPO_EXPIRY, getCacheRepoDir} from '../lib/cacheRepoUtils'; +import {getFtConfig} from '../lib/ftConfig'; +import {findCoreDef, getCoreDefVersionHash, getCoreDefs} from '../lib/coreDefs'; + +const pullSignature = v => v.split('\n').slice(0, 2); export const name = 'outdated'; export const description = @@ -77,12 +81,15 @@ export async function run(args: Args): Promise { ? path.resolve(args.rootDir) : process.cwd(); const flowProjectRoot = await findFlowRoot(cwd); + const libdefDir = + typeof args.libdefDir === 'string' ? args.libdefDir : 'flow-typed'; const packageDir = typeof args.packageDir === 'string' ? path.resolve(args.packageDir) : cwd; const flowVersion = await determineFlowSpecificVersion( packageDir, args.flowVersion, ); + const useCacheUntil = Number(args.useCacheUntil) || CACHE_REPO_EXPIRY; if (flowProjectRoot === null) { console.error( 'Error: Unable to find a flow project in the current dir or any of ' + @@ -92,13 +99,10 @@ export async function run(args: Args): Promise { return 1; } - const cachedLibDefs = await getCacheNpmLibDefs( - Number(args.useCacheUntil) || CACHE_REPO_EXPIRY, - true, - ); + const cachedLibDefs = await getCacheNpmLibDefs(useCacheUntil, true); const installedLibDefs = await getInstalledNpmLibDefs( flowProjectRoot, - args.libdefDir ? String(args.libdefDir) : undefined, + libdefDir, ); let outdatedList: Array<{ @@ -146,11 +150,9 @@ export async function run(args: Args): Promise { ); if (npmLibDef) { - const pullSignature = v => v.split('\n').slice(0, 2); - const file = await fs.readFile( path.join(cwd, installedDef.libDef.path), - 'utf8', + 'utf-8', ); const installedSignatureArray = pullSignature(file); @@ -181,6 +183,67 @@ export async function run(args: Args): Promise { }), ); + const ftConfig = getFtConfig(cwd, libdefDir); + const {env} = ftConfig ?? {}; + + if (Array.isArray(env)) { + const coreDefs = await getCoreDefs(); + await Promise.all( + env.map(async en => { + if (typeof en !== 'string') return; + + const def = await findCoreDef(en, flowVersion, useCacheUntil, coreDefs); + + if (def) { + const localDefPath = path.join( + flowProjectRoot, + libdefDir, + 'core', + `${en}.js`, + ); + if (!fs.exists(localDefPath)) { + outdatedList.push({ + name: en, + message: + 'This core def has not yet been installed try running `flow-typed install`', + }); + return; + } else { + const installedDef = fs.readFileSync(localDefPath, 'utf-8'); + const installedSignatureArray = pullSignature(installedDef); + + const repoVersion = await getCoreDefVersionHash( + getCacheRepoDir(), + def, + ); + const codeSignPreprocessor = signCodeStream(repoVersion); + const content = fs.readFileSync(def.path, 'utf-8'); + const cacheSignatureArray = pullSignature( + codeSignPreprocessor(content), + ); + + if ( + installedSignatureArray[0] !== cacheSignatureArray[0] || + installedSignatureArray[1] !== cacheSignatureArray[1] + ) { + outdatedList.push({ + name: en, + message: + 'This core definition does not match what we found in the registry, update it with `flow-typed update`', + }); + } + } + } else { + outdatedList.push({ + name: en, + message: + 'This core definition does not exist in the registry or there is no compatible definition for your version of flow', + }); + } + }), + ); + } + if (outdatedList.length > 0) { // Cleanup duplicated dependencies which come from nested libraries that ship flow outdatedList = outdatedList.reduce((acc, cur) => { diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/coreDefs.js index 2bf5e12776..426f9f24cb 100644 --- a/cli/src/lib/coreDefs.js +++ b/cli/src/lib/coreDefs.js @@ -43,7 +43,7 @@ export const getCoreDefs = async (): Promise> => { if (errors.length) { throw errors; } - return [...settled].filter(Boolean); + return [...settled].filter(Boolean).flat(); }; const getSingleCoreDef = async (defName, coreDefPath) => { @@ -51,7 +51,7 @@ const getSingleCoreDef = async (defName, coreDefPath) => { const itemStat = await fs.stat(itemPath); if (itemStat.isDirectory()) { // itemPath must be an env dir - return await extractLibDefsFromNpmPkgDir(itemPath, defName); + return await extractCoreDefs(itemPath, defName); } else { throw new ValidationError( `Expected only directories to be present in this directory.`, @@ -59,7 +59,7 @@ const getSingleCoreDef = async (defName, coreDefPath) => { } }; -async function extractLibDefsFromNpmPkgDir( +async function extractCoreDefs( envDirPath: string, defName: string, ): Promise> { diff --git a/cli/src/lib/ftConfig.js b/cli/src/lib/ftConfig.js new file mode 100644 index 0000000000..b8bfaedcc1 --- /dev/null +++ b/cli/src/lib/ftConfig.js @@ -0,0 +1,17 @@ +// @flow +import {fs, path} from './node'; + +export type FtConfig = { + env?: mixed, // Array, +}; + +export const getFtConfig = ( + cwd: string, + libdefDir: string, +): FtConfig | void => { + try { + return JSON.parse( + fs.readFileSync(path.join(cwd, libdefDir, 'ft-config.json'), 'utf-8'), + ); + } catch (e) {} +}; From 98f9ddda26aa2820498a1fdb00209688866d6ff7 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 15:40:45 +1100 Subject: [PATCH 15/23] add outdated tests for core defs --- .../definitions/core/jsx/flow_v0.83.x-/jsx.js | 1 + cli/src/commands/__tests__/outdated-test.js | 129 +++++++++++++++++- cli/src/commands/outdated.js | 2 +- 3 files changed, 126 insertions(+), 6 deletions(-) create mode 100644 cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js diff --git a/cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js b/cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js new file mode 100644 index 0000000000..db59104874 --- /dev/null +++ b/cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js @@ -0,0 +1 @@ +declare type jsx$HTMLElementProps = {||}; diff --git a/cli/src/commands/__tests__/outdated-test.js b/cli/src/commands/__tests__/outdated-test.js index b426772d2b..f592f8a839 100644 --- a/cli/src/commands/__tests__/outdated-test.js +++ b/cli/src/commands/__tests__/outdated-test.js @@ -61,8 +61,17 @@ describe('outdated (command)', () => { const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); + const FLOWTYPED_CORE_DIR = path.join( + FLOWPROJ_DIR, + 'flow-typed', + 'core', + ); - await Promise.all([mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR)]); + await Promise.all([ + mkdirp(FAKE_CACHE_REPO_DIR), + mkdirp(FLOWTYPED_DIR), + mkdirp(FLOWTYPED_CORE_DIR), + ]); await copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR); @@ -124,8 +133,6 @@ declare module 'foo' { }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), - mkdirp(path.join(FLOWPROJ_DIR, 'flow-typed')), - mkdirp(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')), touchFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_vx.x.x.js'), ), @@ -178,8 +185,6 @@ declare module 'foo' {}`; }), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), - mkdirp(path.join(FLOWPROJ_DIR, 'flow-typed')), - mkdirp(path.join(FLOWPROJ_DIR, 'flow-typed', 'npm')), touchFile( path.join(FLOWPROJ_DIR, 'flow-typed', 'npm', 'foo_v1.x.x.js'), ), @@ -254,5 +259,119 @@ declare module 'foo' {}`; ); }); }); + + it('reports outdated core definitions as needing updates', () => { + const fooLibdef = `// flow-typed signature: fa26c13e83581eea415de59d5f03e416 +// flow-typed version: /jsx/flow_>=v0.83.x + +declare module 'foo' {}`; + + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.162.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + fs.writeFile( + path.join(FLOWPROJ_DIR, 'flow-typed', 'core', 'jsx.js'), + fooLibdef, + ), + fs.writeFile( + path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + '{ "env": ["jsx"] }', + ), + ]); + + await run({}); + + expect( + await Promise.all([ + fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'core', 'jsx.js')), + ]), + ).toEqual([true]); + + expect(console.log).toHaveBeenCalledWith( + table([ + ['Name', 'Details'], + [ + 'jsx', + 'This core definition does not match what we found in the registry, update it with `flow-typed update`', + ], + ]), + ); + }); + }); + + it('reports outdated core definitions which do not exist in the registry', () => { + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.162.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + fs.writeFile( + path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + '{ "env": ["random"] }', + ), + ]); + + await run({}); + + expect(console.log).toHaveBeenCalledWith( + table([ + ['Name', 'Details'], + [ + 'random', + 'This core definition does not exist in the registry or there is no compatible definition for your version of flow', + ], + ]), + ); + }); + }); + + it('reports outdated core definition when it exists ft-config and registry but has not been installed', () => { + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + touchFile(path.join(FLOWPROJ_DIR, '.flowconfig')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.162.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + fs.writeFile( + path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + '{ "env": ["jsx"] }', + ), + ]); + + await run({}); + + expect(console.log).toHaveBeenCalledWith( + table([ + ['Name', 'Details'], + [ + 'jsx', + 'This core def has not yet been installed try running `flow-typed install`', + ], + ]), + ); + }); + }); }); }); diff --git a/cli/src/commands/outdated.js b/cli/src/commands/outdated.js index fb32d25e40..450e574f91 100644 --- a/cli/src/commands/outdated.js +++ b/cli/src/commands/outdated.js @@ -201,7 +201,7 @@ export async function run(args: Args): Promise { 'core', `${en}.js`, ); - if (!fs.exists(localDefPath)) { + if (!(await fs.exists(localDefPath))) { outdatedList.push({ name: en, message: From 411a293bb71eb655ce838d46e2531e7bd04b350e Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 16:05:59 +1100 Subject: [PATCH 16/23] add install tests --- .../definitions/core/jsx/flow_v0.83.x-/jsx.js | 3 + cli/src/commands/__tests__/install-test.js | 148 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js diff --git a/cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js b/cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js new file mode 100644 index 0000000000..3d08009f37 --- /dev/null +++ b/cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js @@ -0,0 +1,3 @@ +declare type jsx$HTMLElementProps = {| + test: boolean, +|}; diff --git a/cli/src/commands/__tests__/install-test.js b/cli/src/commands/__tests__/install-test.js index 99647ae811..cb18bcd7c6 100644 --- a/cli/src/commands/__tests__/install-test.js +++ b/cli/src/commands/__tests__/install-test.js @@ -1232,6 +1232,154 @@ describe('install (command)', () => { ).toEqual(true); }); }); + + describe('core defs', () => { + it('installs core definitions if it exists in ft-config', () => { + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + mkdirp(path.join(FLOWPROJ_DIR, 'src')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.140.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + ]); + + await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); + await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); + await touchFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + ); + await fs.writeJson( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + {env: ['jsx']}, + ); + + // Run the install command + await run({ + ...defaultRunProps, + rootDir: path.join(FLOWPROJ_DIR, 'src'), + }); + + // Installs core definitions + expect( + await fs.exists( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + ), + ).toEqual(true); + }); + }); + + it('does not install new version of definition if it has been overridden', () => { + const installedDef = `// flow-typed signature: fa26c13e83581eea415de59d5f03e123 +// flow-typed version: /jsx/flow_>=v0.83.x + +declare type jsx$HTMLElementProps = {||}`; + + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + mkdirp(path.join(FLOWPROJ_DIR, 'src')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.140.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + ]); + + await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); + await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); + await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core')); + await touchFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + ); + await fs.writeFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + installedDef, + ); + await touchFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + ); + await fs.writeJson( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + {env: ['jsx']}, + ); + + // Run the install command + await run({ + ...defaultRunProps, + rootDir: path.join(FLOWPROJ_DIR, 'src'), + }); + + // Installs core definitions + expect( + await fs.readFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + 'utf-8', + ), + ).toEqual(installedDef); + }); + }); + + it('overrides the core definition if overwrite arg is passed in', () => { + const installedDef = `// flow-typed signature: fa26c13e83581eea415de59d5f03e123 +// flow-typed version: /jsx/flow_>=v0.83.x + +declare type jsx$HTMLElementProps = {||}`; + + return fakeProjectEnv(async FLOWPROJ_DIR => { + // Create some dependencies + await Promise.all([ + mkdirp(path.join(FLOWPROJ_DIR, 'src')), + writePkgJson(path.join(FLOWPROJ_DIR, 'package.json'), { + name: 'test', + devDependencies: { + 'flow-bin': '^0.140.0', + }, + }), + mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), + ]); + + await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); + await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); + await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core')); + await touchFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + ); + await fs.writeFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + installedDef, + ); + await touchFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + ); + await fs.writeJson( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + {env: ['jsx']}, + ); + + // Run the install command + await run({ + ...defaultRunProps, + rootDir: path.join(FLOWPROJ_DIR, 'src'), + overwrite: true, + }); + + // Installs core definitions + expect( + await fs.readFile( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + 'utf-8', + ), + ).not.toEqual(installedDef); + }); + }); + }); }); describe('workspace tests', () => { From 13bb7dae528f9b167961d66a7e69246f89e452c0 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 16:10:10 +1100 Subject: [PATCH 17/23] add back es5_ from npm --- definitions/npm/core.es5_v5.1.0/README.md | 9 + .../flow_v0.104.x-v0.142.x/core.es5_v5.1.0.js | 1490 +++++++++++++++++ .../flow_v0.104.x-v0.142.x/test_lib.js | 12 + 3 files changed, 1511 insertions(+) create mode 100644 definitions/npm/core.es5_v5.1.0/README.md create mode 100644 definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/core.es5_v5.1.0.js create mode 100644 definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/test_lib.js diff --git a/definitions/npm/core.es5_v5.1.0/README.md b/definitions/npm/core.es5_v5.1.0/README.md new file mode 100644 index 0000000000..f1daa44727 --- /dev/null +++ b/definitions/npm/core.es5_v5.1.0/README.md @@ -0,0 +1,9 @@ +An alternative JS core library definition for ES5.1 + +The Flow core library definitions cover the latest ES versions. That has a lot of additional methods and classes compared to ES5 and so code-completion and type checking do not give errors about using those new methods and classes. Use this core library definition to write pure ES5.1 Javascript without having to add pollyfills or compile down to ES5 via Babel. + +Requires the `no_flowlib` option. + +Based off Typescript's es5 definition and adjusted towards Flow's core libdef. + +If Flow provided a way to specify which ES the code was targeting then this should be part of Flow core. diff --git a/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/core.es5_v5.1.0.js b/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/core.es5_v5.1.0.js new file mode 100644 index 0000000000..a3030be5df --- /dev/null +++ b/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/core.es5_v5.1.0.js @@ -0,0 +1,1490 @@ +/** + * TODO: This lib will be delete and replaced by core/es5-1 once core definition + * changes are released + * + * Flowtype definitions for core.es5 + * Generated by Flowgen from a Typescript Definition + * cf. https://github.com/microsoft/TypeScript/blob/master/lib/lib.es5.d.ts + * Flowgen v1.10.0 + * and somewhat updated by comparison with the core lib built into Flow + */ + + declare var NaN: number; + declare var Infinity: number; + declare var undefined: void; + + /** + * Evaluates JavaScript code and executes it. + * @param x A String value that contains valid JavaScript code. + */ + declare function eval(x: string): any; + + /** + * Converts a string to an integer. + * @param string A string to convert into a number. + * @param radix A value between 2 and 36 that specifies the base of the number in numString. + * If this argument is not supplied, strings with a prefix of '0x' are considered hexadecimal. + * All other strings are considered decimal. + */ + declare function parseInt(string: mixed, radix?: number): number; + + /** + * Converts a string to a floating-point number. + * @param string A string that contains a floating-point number. + */ + declare function parseFloat(string: mixed): number; + + /** + * Returns a Boolean value that indicates whether a value is the reserved value NaN (not a number). + * @param number A numeric value. + */ + declare function isNaN(number: mixed): boolean; + + /** + * Determines whether a supplied number is finite. + * @param number Any numeric value. + */ + declare function isFinite(number: mixed): boolean; + + /** + * Gets the unencoded version of an encoded Uniform Resource Identifier (URI). + * @param encodedURI A value representing an encoded URI. + */ + declare function decodeURI(encodedURI: string): string; + + /** + * Gets the unencoded version of an encoded component of a Uniform Resource Identifier (URI). + * @param encodedURIComponent A value representing an encoded URI component. + */ + declare function decodeURIComponent(encodedURIComponent: string): string; + + /** + * Encodes a text string as a valid Uniform Resource Identifier (URI) + * @param uri A value representing an encoded URI. + */ + declare function encodeURI(uri: string): string; + + /** + * Encodes a text string as a valid component of a Uniform Resource Identifier (URI). + * @param uriComponent A value representing an encoded URI component. + */ + declare function encodeURIComponent(uriComponent: mixed): string; + + type PropertyDescriptor = { + enumerable?: boolean, + configurable?: boolean, + writable?: boolean, + value?: T, + get?: () => T, + set?: (value: T) => void, + ... + }; + + type PropertyDescriptorMap = { + [s: string]: PropertyDescriptor, + ... + }; + + type $NotNullOrVoid = + | number + | string + | boolean + | {...} + | $ReadOnlyArray; + + declare type PropertyKey = string | number | symbol; + + /** + * Provides functionality common to all JavaScript objects. + */ + declare class Object { + constructor(value?: any): Object; + static (o: ?void): { ... }; + static (o: boolean): Boolean; + static (o: number): Number; + static (o: string): String; + static (o: T): T; + + /** + * Creates an object that has the specified prototype, and that optionally contains specified properties. + * @param o Object to use as a prototype. May be null + * @param properties JavaScript object that contains one or more property descriptors. + */ + // compiler magic + static create( + o: { ... } | null, + properties?: PropertyDescriptorMap + ): any; + + /** + * Adds one or more properties to an object, and/or modifies attributes of existing properties. + * @param o Object on which to add or modify the properties. This can be a native JavaScript object or a DOM object. + * @param properties JavaScript object that contains one or more descriptor objects. Each descriptor object describes a data property or an accessor property. + */ + static defineProperties( + o: { ... }, + properties: PropertyDescriptorMap + ): any; + + /** + * Adds a property to an object, or modifies attributes of an existing property. + * @param o Object on which to add or modify the property. This can be a native JavaScript object (that is, a user-defined object or a built in object) or a DOM object. + * @param p The property name. + * @param attributes Descriptor for the property. It can be for a data property or an accessor property. + */ + static defineProperty( + o: { ... }, + p: PropertyKey, + attributes: PropertyDescriptor + ): any; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + static freeze(a: T[]): $ReadOnlyArray; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + static freeze(f: T): T; + + /** + * Prevents the modification of existing property attributes and values, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + static freeze(o: T): $ReadOnly; + + /** + * Gets the own property descriptor of the specified object. + * An own property descriptor is one that is defined directly on the object and is not inherited from the object's prototype. + * @param o Object that contains the property. + * @param p Name of the property. + */ + static getOwnPropertyDescriptor>( + o: O, + p: K + ): PropertyDescriptor<$ElementType> | void; + + /** + * Returns the names of the own properties of an object. The own properties of an object are those that are defined directly + * on that object, and are not inherited from the object's prototype. The properties of an object include both fields (objects) and functions. + * @param o Object that contains the own properties. + */ + // This is documentation only. Object.getOwnPropertyNames is implemented in OCaml code + // https://github.com/facebook/flow/blob/8ac01bc604a6827e6ee9a71b197bb974f8080049/src/typing/statement.ml#L6308 + static getOwnPropertyNames(o: $NotNullOrVoid): Array; + + /** + * Returns the prototype of an object. + * @param o The object that references the prototype. + */ + // magic + static getPrototypeOf: Object$GetPrototypeOf; + + /** + * Returns a value that indicates whether new properties can be added to an object. + * @param o Object to test. + */ + static isExtensible(o: $NotNullOrVoid): boolean; + + /** + * Returns true if existing property attributes and values cannot be modified in an object, and new properties cannot be added to the object. + * @param o Object to test. + */ + static isFrozen(o: $NotNullOrVoid): boolean; + + /** + * Returns true if existing property attributes cannot be modified in an object and new properties cannot be added to the object. + * @param o Object to test. + */ + static isSealed(o: $NotNullOrVoid): boolean; + + /** + * Returns the names of the enumerable string properties and methods of an object. + * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. + */ + // This is documentation only. Object.keys is implemented in OCaml code. + // https://github.com/facebook/flow/blob/8ac01bc604a6827e6ee9a71b197bb974f8080049/src/typing/statement.ml#L6308 + static keys(o: { ... }): Array; + + /** + * Prevents the modification of attributes of existing properties, and prevents the addition of new properties. + * @param o Object on which to lock the attributes. + */ + static seal(o: T): T; + + /** + * Prevents the addition of new properties to an object. + * @param o Object to make non-extensible. + */ + static preventExtensions(o: T): T; + + /** + * Determines whether an object has a property with the specified name. + * @param v A property name. + */ + hasOwnProperty(v: PropertyKey): boolean; + + /** + * Determines whether an object exists in another object's prototype chain. + * @param v Another object whose prototype chain is to be checked. + */ + isPrototypeOf(v: $NotNullOrVoid): boolean; + + /** + * Determines whether a specified property is enumerable. + * @param v A property name. + */ + propertyIsEnumerable(v: PropertyKey): boolean; + + /** + * Returns a date converted to a string using the current locale. + */ + toLocaleString(): string; + + /** + * Returns a string representation of an object. + */ + toString(): string; + + /** + * Returns the primitive value of the specified object. + */ + valueOf(): mixed; + } + + declare interface Symbol { + /** + * Returns a string representation of an object. + */ + toString(): string; + + /** + * Returns the primitive value of the specified object. + */ + valueOf(): ?symbol; + } + + // TODO: instance, static + declare class Function { + proto apply: Function$Prototype$Apply; // (thisArg: any, argArray?: any) => any + proto bind: Function$Prototype$Bind; // (thisArg: any, ...argArray: Array) => any; + proto call: Function$Prototype$Call; // (thisArg: any, ...argArray: Array) => any + toString(): string; + arguments: any; + caller: any | null; + length: number; + name: string; + } + + declare class Boolean { + constructor(value?: mixed): Boolean; + static (value?: mixed): boolean; + + /** + * Returns the primitive value of the specified object. + */ + valueOf(): boolean; + toString(): string; + } + + /** + * An object that represents a number of any kind. All JavaScript numbers are 64-bit floating-point numbers. + */ + declare class Number { + /** + * The largest number that can be represented in JavaScript. Equal to approximately 1.79E+308. + */ + static +MAX_VALUE: number; + + /** + * The closest number to zero that can be represented in JavaScript. Equal to approximately 5.00E-324. + */ + static +MIN_VALUE: number; + + /** + * A value that is not a number. + * In equality comparisons, NaN does not equal any value, including itself. To test whether a value is equivalent to NaN, use the isNaN function. + */ + static +NaN: number; + + /** + * A value that is less than the largest negative number that can be represented in JavaScript. + * JavaScript displays NEGATIVE_INFINITY values as -infinity. + */ + static +NEGATIVE_INFINITY: number; + + /** + * A value greater than the largest number that can be represented in JavaScript. + * JavaScript displays POSITIVE_INFINITY values as infinity. + */ + static +POSITIVE_INFINITY: number; + + static (value?: mixed): number; + constructor(value?: mixed): Number; + + /** + * Returns a string containing a number represented in exponential notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toExponential(fractionDigits?: number): string; + + /** + * Returns a string representing a number in fixed-point notation. + * @param fractionDigits Number of digits after the decimal point. Must be in the range 0 - 20, inclusive. + */ + toFixed(fractionDigits?: number): string; + + /** + * Converts a number to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString( + locales?: string | Array, + options?: Intl$NumberFormatOptions + ): string; + + /** + * Returns a string containing a number represented either in exponential or fixed-point notation with a specified number of digits. + * @param precision Number of significant digits. Must be in the range 1 - 21, inclusive. + */ + toPrecision(precision?: number): string; + + /** + * Returns a string representation of an object. + * @param radix Specifies a radix for converting numeric values to strings. This value is only used for numbers. + */ + toString(radix?: number): string; + + /** + * Returns the primitive value of the specified object. + */ + valueOf(): number; + } + + /** + * An intrinsic object that provides basic mathematics functionality and constants. + */ + declare var Math: { + /** + * The mathematical constant e. This is Euler's number, the base of natural logarithms. + */ + +E: number; + + /** + * The natural logarithm of 10. + */ + +LN10: number; + + /** + * The natural logarithm of 2. + */ + +LN2: number; + + /** + * The base-2 logarithm of e. + */ + +LOG2E: number; + + /** + * The base-10 logarithm of e. + */ + +LOG10E: number; + + /** + * Pi. This is the ratio of the circumference of a circle to its diameter. + */ + +PI: number; + + /** + * The square root of 0.5, or, equivalently, one divided by the square root of 2. + */ + +SQRT1_2: number; + + /** + * The square root of 2. + */ + +SQRT2: number; + + /** + * Returns the absolute value of a number (the value without regard to whether it is positive or negative). + * For example, the absolute value of -5 is the same as the absolute value of 5. + * @param x A numeric expression for which the absolute value is needed. + */ + abs(x: number): number; + + /** + * Returns the arc cosine (or inverse cosine) of a number. + * @param x A numeric expression. + */ + acos(x: number): number; + + /** + * Returns the arcsine of a number. + * @param x A numeric expression. + */ + asin(x: number): number; + + /** + * Returns the arctangent of a number. + * @param x A numeric expression for which the arctangent is needed. + */ + atan(x: number): number; + + /** + * Returns the angle (in radians) from the X axis to a point. + * @param y A numeric expression representing the cartesian y-coordinate. + * @param x A numeric expression representing the cartesian x-coordinate. + */ + atan2(y: number, x: number): number; + + /** + * Returns the smallest integer greater than or equal to its numeric argument. + * @param x A numeric expression. + */ + ceil(x: number): number; + + /** + * Returns the cosine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + cos(x: number): number; + + /** + * Returns e (the base of natural logarithms) raised to a power. + * @param x A numeric expression representing the power of e. + */ + exp(x: number): number; + + /** + * Returns the greatest integer less than or equal to its numeric argument. + * @param x A numeric expression. + */ + floor(x: number): number; + + /** + * Returns the natural logarithm (base e) of a number. + * @param x A numeric expression. + */ + log(x: number): number; + + /** + * Returns the larger of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + max(...values: number[]): number; + + /** + * Returns the smaller of a set of supplied numeric expressions. + * @param values Numeric expressions to be evaluated. + */ + min(...values: number[]): number; + + /** + * Returns the value of a base expression taken to a specified power. + * @param x The base value of the expression. + * @param y The exponent value of the expression. + */ + pow(x: number, y: number): number; + + /** + * Returns a pseudorandom number between 0 and 1. + */ + random(): number; + + /** + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. + */ + round(x: number): number; + + /** + * Returns the sine of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + sin(x: number): number; + + /** + * Returns the square root of a number. + * @param x A numeric expression. + */ + sqrt(x: number): number; + + /** + * Returns the tangent of a number. + * @param x A numeric expression that contains an angle measured in radians. + */ + tan(x: number): number; + ... + }; + + /** + * All the Array.prototype methods and properties that don't mutate the array. + */ + declare class $ReadOnlyArray<+T> { + /** + * Returns a string representation of an array. The elements are converted to string using their toLocalString methods. + */ + toLocaleString(): string; + + /** + * Combines two or more arrays. + * @param items Additional items to add to the end of array1. + */ + concat | S>(...items: Array): Array; + + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every( + callbackfn: (value: T, index: number, array: $ReadOnlyArray) => boolean, + thisArg?: any + ): boolean; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter(callbackfn: typeof Boolean): Array<$NonMaybeType>; // special case for the function "Boolean" + filter( + callbackfn: (value: T, index: number, array: $ReadOnlyArray) => boolean, + thisArg?: any + ): Array; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach( + callbackfn: (value: T, index: number, array: $ReadOnlyArray) => void, + thisArg?: any + ): void; + + /** + * Returns the index of the first occurrence of a value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at index 0. + */ + indexOf(searchElement: T, fromIndex?: number): number; + + /** + * Adds all the elements of an array separated by the specified separator string. + * @param separator A string used to separate one element of an array from the next in the resulting String. If omitted, the array elements are separated with a comma. + */ + join(separator?: string): string; + + /** + * Returns the index of the last occurrence of a specified value in an array. + * @param searchElement The value to locate in the array. + * @param fromIndex The array index at which to begin the search. If fromIndex is omitted, the search starts at the last index in the array. + */ + lastIndexOf(searchElement: T, fromIndex?: number): number; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map( + callbackfn: (value: T, index: number, array: $ReadOnlyArray) => U, + thisArg?: any + ): Array; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + */ + reduce( + callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: $ReadOnlyArray) => T, + ): T; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce( + callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: $ReadOnlyArray) => U, + initialValue: U + ): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + */ + reduceRight( + callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: $ReadOnlyArray) => T, + ): T; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight( + callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: $ReadOnlyArray) => U, + initialValue: U + ): U; + + /** + * Returns a section of an array. + * @param start The beginning of the specified portion of the array. + * @param end The end of the specified portion of the array. This is exclusive of the element at the index 'end'. + */ + slice(start?: number, end?: number): Array; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls + * the callbackfn function for each element in the array until the callbackfn returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some( + callbackfn: (value: T, index: number, array: $ReadOnlyArray) => boolean, + thisArg?: any + ): boolean; + + +[key: number]: T; + + /** + * Returns a string representation of an array. + */ + toString(): string; + + /** + * Gets the length of the array. This is a number one higher than the highest element defined in an array. + */ + +length: number; + } + + declare class Array extends $ReadOnlyArray { + /** + * Determines whether all the members of an array satisfy the specified test. + * @param callbackfn A function that accepts up to three arguments. The every method calls + * the callbackfn function for each element in the array until the callbackfn returns a value + * which is coercible to the Boolean value false, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + every( + callbackfn: (value: T, index: number, array: Array) => boolean, + thisArg?: any + ): boolean; + + /** + * Returns the elements of an array that meet the condition specified in a callback function. + * @param callbackfn A function that accepts up to three arguments. The filter method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + filter( + callbackfn: (value: T, index: number, array: Array) => boolean, + thisArg?: any + ): Array; + + /** + * Performs the specified action for each element in an array. + * @param callbackfn A function that accepts up to three arguments. forEach calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + forEach( + callbackfn: (value: T, index: number, array: Array) => void, + thisArg?: any + ): void; + + /** + * Calls a defined callback function on each element of an array, and returns an array that contains the results. + * @param callbackfn A function that accepts up to three arguments. The map method calls the callbackfn function one time for each element in the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. If thisArg is omitted, undefined is used as the this value. + */ + map( + callbackfn: (value: T, index: number, array: Array) => U, + thisArg?: any + ): Array; + + /** + * Removes the last element from an array and returns it. + */ + pop(): T; + + /** + * Appends new elements to an array, and returns the new length of the array. + * @param items New elements of the Array. + */ + push(...items: Array): number; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + */ + reduce( + callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: Array) => T, + ): T; + + /** + * Calls the specified callback function for all the elements in an array. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduce method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduce( + callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: Array) => U, + initialValue: U + ): U; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + */ + reduceRight( + callbackfn: (previousValue: T, currentValue: T, currentIndex: number, array: Array) => T, + ): T; + + /** + * Calls the specified callback function for all the elements in an array, in descending order. The return value of the callback function is the accumulated result, and is provided as an argument in the next call to the callback function. + * @param callbackfn A function that accepts up to four arguments. The reduceRight method calls the callbackfn function one time for each element in the array. + * @param initialValue If initialValue is specified, it is used as the initial value to start the accumulation. The first call to the callbackfn function provides this value as an argument instead of an array value. + */ + reduceRight( + callbackfn: (previousValue: U, currentValue: T, currentIndex: number, array: Array) => U, + initialValue: U + ): U; + + /** + * Reverses the elements in an Array. + */ + reverse(): Array; + + /** + * Removes the first element from an array and returns it. + */ + shift(): T; + + /** + * Determines whether the specified callback function returns true for any element of an array. + * @param callbackfn A function that accepts up to three arguments. The some method calls + * the callbackfn function for each element in the array until the callbackfn returns a value + * which is coercible to the Boolean value true, or until the end of the array. + * @param thisArg An object to which the this keyword can refer in the callbackfn function. + * If thisArg is omitted, undefined is used as the this value. + */ + some( + callbackfn: (value: T, index: number, array: Array) => boolean, + thisArg?: any + ): boolean; + + /** + * Sorts an array. + * @param compareFn Function used to determine the order of the elements. It is expected to return + * a negative value if first argument is less than second argument, zero if they're equal and a positive + * value otherwise. If omitted, the elements are sorted in ascending, ASCII character order. + * ```ts + * [11,2,22,1].sort((a, b) => a - b) + * ``` + */ + sort(compareFn?: (a: T, b: T) => number): Array; + + /** + * Removes elements from an array and, if necessary, inserts new elements in their place, returning the deleted elements. + * @param start The zero-based location in the array from which to start removing elements. + * @param deleteCount The number of elements to remove. + * @param items Elements to insert into the array in place of the deleted elements. + */ + splice(start: number, deleteCount: number, ...items: Array): Array; + + /** + * Inserts new elements at the start of an array. + * @param items Elements to insert at the start of the Array. + */ + unshift(...items: Array): number; + + [key: number]: T; + + /** + * Gets or sets the length of the array. This is a number one higher than the highest element defined in an array. + */ + length: number; + + static (length: number): Array; + static (...values:Array): Array; + + static isArray(arg: mixed): boolean; + } + + type $ArrayLike = { + [indexer: number]: T, + length: number, + ... + } + + type RegExp$flags = $CharSet<"gimsuy">; + type RegExp$matchResult = Array & { + index?: number, + input?: string, + ... + }; + + /** + * Allows manipulation and formatting of text strings and determination and location of substrings within strings. + */ + declare class String { + /** + * Returns the character at the specified index. + * @param pos The zero-based index of the desired character. + */ + charAt(pos: number): string; + + /** + * Returns the Unicode value of the character at the specified location. + * @param index The zero-based index of the desired character. If there is no character at the specified index, NaN is returned. + */ + charCodeAt(index: number): number; + + /** + * Returns a string that contains the concatenation of two or more strings. + * @param strings The strings to append to the end of the string. + */ + concat(...strings: Array): string; + + constructor(value?: mixed): String; + + /** + * Returns the position of the first occurrence of a substring. + * @param searchString The substring to search for in the string + * @param position The index at which to begin searching the String object. If omitted, search starts at the beginning of the string. + */ + indexOf(searchString: string, position?: number): number; + + /** + * Returns the last occurrence of a substring in the string. + * @param searchString The substring to search for. + * @param position The index at which to begin searching. If omitted, the search begins at the end of the string. + */ + lastIndexOf(searchString: string, position?: number): number; + + /** + * Determines whether two strings are equivalent in the current locale. + * @param that String to compare to target string + */ + localeCompare(that: string): number; + + /** + * Determines whether two strings are equivalent in the current or specified locale. + * @param that String to compare to target string + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. This parameter must conform to BCP 47 standards; see the Intl.Collator object for details. + * @param options An object that contains one or more properties that specify comparison options. see the Intl.Collator object for details. + */ + localeCompare( + that: string, + locales?: string | Array, + options?: Intl$CollatorOptions + ): number; + + /** + * Matches a string with a regular expression, and returns an array containing the results of that search. + * @param regexp A variable name or string literal containing the regular expression pattern and flags. + */ + match(regexp: string | RegExp): RegExp$matchResult | null; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replaceValue A string containing the text to replace for every successful match of searchValue in this string. + */ + replace(searchValue: string | RegExp, replaceValue: string): string; + + /** + * Replaces text in a string, using a regular expression or search string. + * @param searchValue A string to search for. + * @param replacer A function that returns the replacement text. + */ + replace( + searchValue: string | RegExp, + replacer: (substring: string, ...args: Array) => string + ): string; + + /** + * Finds the first substring match in a regular expression search. + * @param regexp The regular expression pattern and applicable flags. + */ + search(regexp: string | RegExp): number; + + /** + * Returns a section of a string. + * @param start The index to the beginning of the specified portion of stringObj. + * @param end The index to the end of the specified portion of stringObj. The substring includes the characters up to, but not including, the character indicated by end. + * If this value is not specified, the substring continues to the end of stringObj. + */ + slice(start?: number, end?: number): string; + + /** + * Split a string into substrings using the specified separator and return them as an array. + * @param separator A string that identifies character or characters to use in separating the string. If omitted, a single-element array containing the entire string is returned. + * @param limit A value used to limit the number of elements returned in the array. + */ + split(separator: string | RegExp, limit?: number): Array; + + /** + * Gets a substring beginning at the specified location and having the specified length. + * @param from The starting position of the desired substring. The index of the first character in the string is zero. + * @param length The number of characters to include in the returned substring. + */ + substr(from: number, length?: number): string; + + /** + * Returns the substring at the specified location within a String object. + * @param start The zero-based index number indicating the beginning of the substring. + * @param end Zero-based index number indicating the end of the substring. The substring includes the characters up to, but not including, the character indicated by end. + * If end is omitted, the characters from start through the end of the original string are returned. + */ + substring(start: number, end?: number): string; + + /** + * Converts all alphabetic characters to lowercase, taking into account the host environment's current locale. + */ + toLocaleLowerCase(locale?: string | Array): string; + + /** + * Returns a string where all alphabetic characters have been converted to uppercase, taking into account the host environment's current locale. + */ + toLocaleUpperCase(locale?: string | Array): string; + + /** + * Converts all the alphabetic characters in a string to lowercase. + */ + toLowerCase(): string; + + /** + * Converts all the alphabetic characters in a string to uppercase. + */ + toUpperCase(): string; + + /** + * Removes the leading and trailing white space and line terminator characters from a string. + */ + trim(): string; + + /** + * Returns the primitive value of the specified object. + */ + valueOf(): string; + + /** + * Returns a string representation of a string. + */ + toString(): string; + + /** + * Returns the length of a String object. + */ + +length: number; + + [index: number]: string; + + static (value?: mixed): string; + static fromCharCode(...codes: Array): string; + } + + declare class RegExp { + static (pattern: RegExp): RegExp; + static (pattern: string, flags?: RegExp$flags): RegExp; + compile(): RegExp; + constructor(pattern: RegExp): RegExp; + constructor(pattern: string, flags?: RegExp$flags): RegExp; + static lastMatch: string; + + /** + * Executes a search on a string using a regular expression pattern, and returns an array containing the results of that search. + * @param string The String object or string literal on which to perform the search. + */ + exec(string: string): RegExp$matchResult | null; + + /** + * Returns a Boolean value indicating the state of the global flag (g) used with a regular expression. Default is false. Read-only. + */ + +global: boolean; + + /** + * Returns a Boolean value indicating the state of the ignoreCase flag (i) used with a regular expression. Default is false. Read-only. + */ + +ignoreCase: boolean; + + lastIndex: number; + + /** + * Returns a Boolean value indicating the state of the multiline flag (m) used with a regular expression. Default is false. Read-only. + */ + +multiline: boolean; + + /** + * Returns a copy of the text of the regular expression pattern. Read-only. The regExp argument is a Regular expression object. It can be a variable name or a literal. + */ + +source: string; + + /** + * Returns a Boolean value that indicates whether or not a pattern exists in a searched string. + * @param string String on which to perform the search. + */ + test(string: string): boolean; + } + + /** + * Enables basic storage and retrieval of dates and times. + */ + declare class Date { + constructor(): Date; + constructor(timestamp: number): Date; + constructor(date: Date): Date; + constructor(dateString: string): Date; + constructor( + year: number, + month: number, + day?: number, + hours?: number, + minutes?: number, + seconds?: number, + ms?: number + ): Date; + + /** + * Gets the day-of-the-month, using local time. + */ + getDate(): number; + + /** + * Gets the day of the week, using local time. + */ + getDay(): number; + + /** + * Gets the year, using local time. + */ + getFullYear(): number; + + /** + * Gets the hours in a date, using local time. + */ + getHours(): number; + + /** + * Gets the milliseconds of a Date, using local time. + */ + getMilliseconds(): number; + + /** + * Gets the minutes of a Date object, using local time. + */ + getMinutes(): number; + + /** + * Gets the month, using local time. + */ + getMonth(): number; + + /** + * Gets the seconds of a Date object, using local time. + */ + getSeconds(): number; + + /** + * Gets the time value in milliseconds. + */ + getTime(): number; + + /** + * Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). + */ + getTimezoneOffset(): number; + + /** + * Gets the day-of-the-month, using Universal Coordinated Time (UTC). + */ + getUTCDate(): number; + + /** + * Gets the day of the week using Universal Coordinated Time (UTC). + */ + getUTCDay(): number; + + /** + * Gets the year using Universal Coordinated Time (UTC). + */ + getUTCFullYear(): number; + + /** + * Gets the hours value in a Date object using Universal Coordinated Time (UTC). + */ + getUTCHours(): number; + + /** + * Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). + */ + getUTCMilliseconds(): number; + + /** + * Gets the minutes of a Date object using Universal Coordinated Time (UTC). + */ + getUTCMinutes(): number; + + /** + * Gets the month of a Date object using Universal Coordinated Time (UTC). + */ + getUTCMonth(): number; + + /** + * Gets the seconds of a Date object using Universal Coordinated Time (UTC). + */ + getUTCSeconds(): number; + + /** + * Sets the numeric day-of-the-month value of the Date object using local time. + * @param date A numeric value equal to the day of the month. + */ + setDate(date: number): number; + + /** + * Sets the year of the Date object using local time. + * @param year A numeric value for the year. + * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified. + * @param date A numeric value equal for the day of the month. + */ + setFullYear(year: number, month?: number, date?: number): number; + + /** + * Sets the hour value in the Date object using local time. + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setHours(hours: number, min?: number, sec?: number, ms?: number): number; + + /** + * Sets the milliseconds value in the Date object using local time. + * @param ms A numeric value equal to the millisecond value. + */ + setMilliseconds(ms: number): number; + + /** + * Sets the minutes value in the Date object using local time. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setMinutes(min: number, sec?: number, ms?: number): number; + + /** + * Sets the month value in the Date object using local time. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used. + */ + setMonth(month: number, date?: number): number; + + /** + * Sets the seconds value in the Date object using local time. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setSeconds(sec: number, ms?: number): number; + + /** + * Sets the date and time value in the Date object. + * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT. + */ + setTime(time: number): number; + + /** + * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC). + * @param date A numeric value equal to the day of the month. + */ + setUTCDate(date: number): number; + + /** + * Sets the year value in the Date object using Universal Coordinated Time (UTC). + * @param year A numeric value equal to the year. + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied. + * @param date A numeric value equal to the day of the month. + */ + setUTCFullYear(year: number, month?: number, date?: number): number; + + /** + * Sets the hours value in the Date object using Universal Coordinated Time (UTC). + * @param hours A numeric value equal to the hours value. + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number; + + /** + * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC). + * @param ms A numeric value equal to the millisecond value. + */ + setUTCMilliseconds(ms: number): number; + + /** + * Sets the minutes value in the Date object using Universal Coordinated Time (UTC). + * @param min A numeric value equal to the minutes value. + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCMinutes(min: number, sec?: number, ms?: number): number; + + /** + * Sets the month value in the Date object using Universal Coordinated Time (UTC). + * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. + * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used. + */ + setUTCMonth(month: number, date?: number): number; + + /** + * Sets the seconds value in the Date object using Universal Coordinated Time (UTC). + * @param sec A numeric value equal to the seconds value. + * @param ms A numeric value equal to the milliseconds value. + */ + setUTCSeconds(sec: number, ms?: number): number; + + /** + * Returns a string representation of a date. The format of the string depends on the locale. + */ + toString(): string; + + /** + * Returns a date as a string value. + */ + toDateString(): string; + + /** + * Returns a date as a string value in ISO format. + */ + toISOString(): string; + + /** + * Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. + */ + toJSON(key?: any): string; + + /** + * Returns a date as a string value appropriate to the host environment's current locale. + */ + toLocaleDateString(): string; + + /** + * Converts a date to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleDateString( + locales?: string | Array, + options?: Intl$DateTimeFormatOptions + ): string; + + /** + * Returns a value as a string value appropriate to the host environment's current locale. + */ + toLocaleString(): string; + + /** + * Converts a date and time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleString( + locales?: string | Array, + options?: Intl$DateTimeFormatOptions + ): string; + + /** + * Returns a time as a string value appropriate to the host environment's current locale. + */ + toLocaleTimeString(): string; + + /** + * Converts a time to a string by using the current or specified locale. + * @param locales A locale string or array of locale strings that contain one or more language or locale tags. If you include more than one locale string, list them in descending order of priority so that the first entry is the preferred locale. If you omit this parameter, the default locale of the JavaScript runtime is used. + * @param options An object that contains one or more properties that specify comparison options. + */ + toLocaleTimeString( + locales?: string | Array, + options?: Intl$DateTimeFormatOptions + ): string; + + /** + * Returns a time as a string value. + */ + toTimeString(): string; + + /** + * Returns a date converted to a string using Universal Coordinated Time (UTC). + */ + toUTCString(): string; + + /** + * Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. + */ + valueOf(): number; + + static (): string; + static now(): number; + + /** + * Parses a string containing a date, and returns the number of milliseconds between that date and midnight, January 1, 1970. + * @param s A date string + */ + static parse(s: string): number; + + /** + * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. + * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. + * @param month The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. + */ + static UTC( + year: number, + month: number, + date?: number, + hours?: number, + minutes?: number, + seconds?: number, + ms?: number + ): number; + } + + declare class Error { + static (message?: mixed): Error; + constructor(message?: mixed): Error; + + name: string; + message: string; + stack?: string; + } + + declare class EvalError extends Error { + static (message?: mixed): EvalError; + } + + declare class RangeError extends Error { + static (message?: mixed): RangeError; + } + + declare class ReferenceError extends Error { + static (message?: mixed): ReferenceError; + } + + declare class SyntaxError extends Error { + static (message?: mixed): SyntaxError; + } + + declare class TypeError extends Error { + static (message?: mixed): TypeError; + } + + declare class URIError extends Error { + static (message?: mixed): URIError; + } + + /** + * An intrinsic object that provides functions to convert JavaScript values to and from the JavaScript Object Notation (JSON) format. + */ + declare class JSON { + /** + * Converts a JavaScript Object Notation (JSON) string into an object. + * @param text A valid JSON string. + * @param reviver A function that transforms the results. This function is called for each member of the object. + * If a member contains nested objects, the nested objects are transformed before the parent object is. + */ + static parse(text: string, reviver?: (key: string, value: mixed) => any): any; + + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer A function that transforms the results. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + static stringify( + value: null | string | number | boolean | {...} | $ReadOnlyArray, + replacer?: (key: string, value: mixed) => any, + space?: string | number + ): string; + + /** + * Converts a JavaScript value to a JavaScript Object Notation (JSON) string. + * @param value A JavaScript value, usually an object or array, to be converted. + * @param replacer An array of strings and numbers that acts as a approved list for selecting the object properties that will be stringified. + * @param space Adds indentation, white space, and line break characters to the return-value JSON text to make it easier to read. + */ + static stringify( + value: null | string | number | boolean | {...} | $ReadOnlyArray, + replacer?: ?Array, + space?: string | number + ): string; + + // avoids massive breaking changes + static stringify( + value: mixed, + replacer?: ?((key: string, value: any) => any) | Array, + space?: string | number + ): string | void; + } + + /** + * Represents the completion of an asynchronous operation + */ + declare class Promise<+R> { + constructor(callback: ( + resolve: (result: Promise | R) => void, + reject: (error: any) => void + ) => void): void; + + /** + * Attaches callbacks for the resolution and/or rejection of the Promise. + * @param onfulfilled The callback to execute when the Promise is resolved. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of which ever callback is executed. + */ + then(onFulfill: null | void, onReject: null | void): Promise; + then( + onFulfill: null | void, + onReject: (error: any) => Promise | U + ): Promise; + then( + onFulfill: (value: R) => Promise | U, + onReject: null | void | ((error: any) => Promise | U) + ): Promise; + + /** + * Attaches a callback for only the rejection of the Promise. + * @param onrejected The callback to execute when the Promise is rejected. + * @returns A Promise for the completion of the callback. + */ + catch(onReject: null | void): Promise; + catch( + onReject: (error: any) => Promise | U + ): Promise; + } + + /** + * Computes a new string in which certain characters have been replaced by a hexadecimal escape sequence. + * @param string A string value + */ + declare function escape(str: string): string; + + /** + * Computes a new string in which hexadecimal escape sequences are replaced with the character that it represents. + * @param string A string value + */ + declare function unescape(str: string): string; diff --git a/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/test_lib.js b/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/test_lib.js new file mode 100644 index 0000000000..21a45c8e5d --- /dev/null +++ b/definitions/npm/core.es5_v5.1.0/flow_v0.104.x-v0.142.x/test_lib.js @@ -0,0 +1,12 @@ +// @flow strict + +// $FlowExpectedError[incompatible-type] +var x:string = NaN +// $FlowExpectedError[incompatible-type] +var y:string = Number.MAX_VALUE; +// $FlowExpectedError[incompatible-type] +var z:number = new TypeError().name; +// $FlowExpectedError[incompatible-type] +var w:string = parseInt("..."); +// $FlowExpectedError[incompatible-type] +const ra: $ReadOnlyArray = Object.freeze({q:2}); From cbd9c96545713e1b17a02b1cdd65d374ab22cb60 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 16:50:41 +1100 Subject: [PATCH 18/23] add docs about core defintions --- docs/_sidebar.md | 2 ++ docs/core-definitions.md | 37 +++++++++++++++++++++++++++++++++++++ docs/ft-config.md | 17 +++++++++++++++++ 3 files changed, 56 insertions(+) create mode 100644 docs/core-definitions.md create mode 100644 docs/ft-config.md diff --git a/docs/_sidebar.md b/docs/_sidebar.md index c68d9a648f..0c6b05f180 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -3,6 +3,7 @@ - [Importing types](usage.md) - [Advanced configuration](advanced.md) - [Contributing](contributing.md) + - [ft-config](ft-config.md) - CLI commands - [install](install.md) - [outdated](outdated.md) @@ -13,5 +14,6 @@ - [update-cache](cache.md) - [validate-defs](validate.md) - [version](version.md) +- [Core definitions](core-definitions.md) - [FAQ](faq.md) - [Changelog](changelog.md) diff --git a/docs/core-definitions.md b/docs/core-definitions.md new file mode 100644 index 0000000000..7822852ec6 --- /dev/null +++ b/docs/core-definitions.md @@ -0,0 +1,37 @@ +# Core Definitions + +Flow is a static analysis tool that exposes a range of global definitions to help you type your application. But flow only supports for the most part, two types of environments, node and browser and sometimes you want something a little extra that flow just doesn't support and isn't quite right to have flow support as a core system. + +That's where core definitions from flow-typed come into play, a home for all those global definitions to share and reuse and standardize for specific environments. + +To make it more concrete, lets take a look at some examples of when you might want to create to leverage a core definition. + +### jsx + +Flow is built by Meta and ships with react definitions it does not type or provide a list of available jsx properties. These can live as a core definition instead. + +``` +type Props = {| + ...jsx$HTMLElementProps, + foo: string, +|}; + +const Input = ({ + foo, + ...otherProps +}: Props) => { + return ( + + ); +}; +``` + +### node + +Although flow ships with both node and browser library definitions there is no mode to distinguish between the two. Sometimes this can cause conflict if there are api's that have the same name but drastically different type definitions depending on how which environment it's used in. A core definition could solve this as it's loaded after the built-in's and could override functionality of a declared var. + +--- + +These are just a couple examples but core definitions could serve a range of purposes for just about anything that isn't related to npm packages. + +The rules of creating a core definition are also quite similar to npm library definitions in that they support flow version ranges but differ in that they do not declare any modules nor have package versions. diff --git a/docs/ft-config.md b/docs/ft-config.md new file mode 100644 index 0000000000..15eb2983a1 --- /dev/null +++ b/docs/ft-config.md @@ -0,0 +1,17 @@ +# ft-config.json + +Flow-typed supports a config file to help you set various project level settings. + +`./flow-typed/ft-config.json` + +## env + +`env` accepts an array of strings that map to environment (core) definitions that you can you can find [here](https://github.com/flow-typed/flow-typed/tree/master/definitions/core). + +```json +{ + "env": ["jsx", "node"] +} +``` + +Learn more about [core definitions](core-definitions.md) From 47b4fda02c03d0df1a06db1cba2e938398051544 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Sun, 20 Feb 2022 18:38:13 +1100 Subject: [PATCH 19/23] add contributing docs --- CONTRIBUTING.md | 72 +++++++++++++++++++++++++++++++------------------ 1 file changed, 46 insertions(+), 26 deletions(-) diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fe607f707e..88bf462ec9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,6 +12,7 @@ Contributing library definitions is as easy as sending a pull request! * [Create tests](#4-write-a-test-file-whose-name-starts-with-test_-in-the-flow-version-directory) * [Run tests](#5-run-your-tests) * [Raise pull request](#6-send-a-pull-request) + * [Core definitions](core-definitions) * [Writing libdefs best practices](#writing-libdefs-best-practices) * [Read flow docs](#read-flow-docs) * [Don't import types from other libdefs](#dont-import-types-from-other-libdefs) @@ -34,35 +35,48 @@ directory. They all must follow the following directory structure and naming format: ``` -└ definitions/npm/ - ├ yargs_v4.x.x/ # <-- The name of the library, followed by _v - | | - | ├ flow_v0.83.x/ # <-- A folder containing libdefs tested against the - | | | # specified version(s) of Flow (v0.83.x in this - | | | # case). - | | | - | | └ yargs_v4.x.x.js # <-- The libdef file meant for the Flow version - | | # specified by the containing directory's name. - | | # Must be named `_v.js`. - | | - | ├ flow_v0.85.x-v0.91.x/ # <-- A folder containing libdefs tested against a - | | | # different range of Flow versions: - | | | # Anything from v0.85.x to v0.91.x (inclusive) - | | | - | | ├ yargs_v4.x.x.js # <-- The libdef file for versions of Flow from - | | | # v0.85.x to v0.91.x (inclusive) - | | | - | | └ test_yargs.js # <-- Tests in this directory only apply to the - | | # adjacent libdef (and thus, are specific to - | | # the libdefs for this specific Flow version) - | | - | └ test_yargs.js # <-- Tests in this directory apply to libdefs for - | # all versions of Flow. - ├ color_v0.7.x/ +└ definitions/ + ├ npm/ + ├ yargs_v4.x.x/ # <-- The name of the library, followed by _v + | | + | ├ flow_v0.83.x/ # <-- A folder containing libdefs tested against the + | | | # specified version(s) of Flow (v0.83.x in this + | | | # case). + | | | + | | └ yargs_v4.x.x.js # <-- The libdef file meant for the Flow version + | | # specified by the containing directory's name. + | | # Must be named `_v.js`. + | | + | ├ flow_v0.85.x-v0.91.x/ # <-- A folder containing libdefs tested against a + | | | # different range of Flow versions: + | | | # Anything from v0.85.x to v0.91.x (inclusive) + | | | + | | ├ yargs_v4.x.x.js # <-- The libdef file for versions of Flow from + | | | # v0.85.x to v0.91.x (inclusive) + | | | + | | └ test_yargs.js # <-- Tests in this directory only apply to the + | | # adjacent libdef (and thus, are specific to + | | # the libdefs for this specific Flow version) + | | + | └ test_yargs.js # <-- Tests in this directory apply to libdefs for + | # all versions of Flow. + ├ color_v0.7.x/ + ├ ... + | + ├ core/ + ├ jsx/ # <-- The name of the core environment + | | + | ├ flow_v0.83.x-/ # <-- A folder containing definition tested against the + | | | # specified version(s) of Flow (v0.83.x and onwards + | | | # in this case). + | | | + | | └ jsx.js # <-- The core definition file meant for the Flow version + | ├ ... + ├ ... ├ ... ``` -Versions are semantically versioned (semver) with some restrictions: +Flow versions are semantically versioned (semver) with some restrictions: * All of MAJOR, MINOR, and PATCH versions must be specified. It's acceptable to specify `x` in place of a number for MINOR and PATCH, but MAJOR cannot be `x`. @@ -178,6 +192,12 @@ node cli/dist/cli.js run-tests You know how to do it. +--- + +#### Core definitions + +The above are instructions on how to submit a library definition against npm packages though the process is similar if contributing core definitions except instead of a package directory you just have an environment package that is the name of the environment without the need of versions. + ## Libdef best practices ### Read flow docs From c031923a22db7bad46f8acbed5929dce58023835 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 2 Mar 2022 21:05:02 +1100 Subject: [PATCH 20/23] remove references of core to rename with environment --- CONTRIBUTING.md | 12 +-- .../jsx/flow_v0.83.x-/jsx.js | 0 .../jsx/flow_v0.83.x-/jsx.js | 0 cli/src/commands/__tests__/install-test.js | 88 ++++++++++++++----- cli/src/commands/__tests__/outdated-test.js | 30 ++++--- cli/src/commands/install.js | 39 ++++---- cli/src/commands/outdated.js | 18 ++-- cli/src/commands/runTests.js | 22 ++--- cli/src/lib/{coreDefs.js => envDefs.js} | 54 ++++++------ cli/src/lib/ftConfig.js | 7 +- cli/src/lib/libDefs.js | 4 +- cli/src/lib/npm/npmLibDefs.js | 8 +- .../{core => environments}/es5-1/README.md | 0 .../es5-1/flow_v0.104.x-v0.142.x/es5-1.js | 0 .../flow_v0.104.x-v0.142.x/test_es5-1.js | 0 .../jsx/flow_v0.83.x-/jsx.js | 0 .../jsx/flow_v0.83.x-/test_jsx.js | 0 docs/_sidebar.md | 6 +- ...core-definitions.md => env-definitions.md} | 12 +-- docs/flow-typed-config.md | 17 ++++ docs/ft-config.md | 17 ---- 21 files changed, 190 insertions(+), 144 deletions(-) rename cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/{core => environments}/jsx/flow_v0.83.x-/jsx.js (100%) rename cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/{core => environments}/jsx/flow_v0.83.x-/jsx.js (100%) rename cli/src/lib/{coreDefs.js => envDefs.js} (77%) rename definitions/{core => environments}/es5-1/README.md (100%) rename definitions/{core => environments}/es5-1/flow_v0.104.x-v0.142.x/es5-1.js (100%) rename definitions/{core => environments}/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js (100%) rename definitions/{core => environments}/jsx/flow_v0.83.x-/jsx.js (100%) rename definitions/{core => environments}/jsx/flow_v0.83.x-/test_jsx.js (100%) rename docs/{core-definitions.md => env-definitions.md} (63%) create mode 100644 docs/flow-typed-config.md delete mode 100644 docs/ft-config.md diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 20a26c6618..191209be8e 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -12,7 +12,7 @@ Contributing library definitions is as easy as sending a pull request! * [Create tests](#4-write-a-test-file-whose-name-starts-with-test_-in-the-flow-version-directory) * [Run tests](#5-run-your-tests) * [Raise pull request](#6-send-a-pull-request) - * [Core definitions](core-definitions) + * [Environment definitions](environment-definitions) * [Writing libdefs best practices](#writing-libdefs-best-practices) * [Read flow docs](#read-flow-docs) * [Don't import types from other libdefs](#dont-import-types-from-other-libdefs) @@ -63,14 +63,14 @@ format: ├ color_v0.7.x/ ├ ... | - ├ core/ - ├ jsx/ # <-- The name of the core environment + ├ environments/ + ├ jsx/ # <-- The name of the env environment | | | ├ flow_v0.83.x-/ # <-- A folder containing definition tested against the | | | # specified version(s) of Flow (v0.83.x and onwards | | | # in this case). | | | - | | └ jsx.js # <-- The core definition file meant for the Flow version + | | └ jsx.js # <-- The environment definition file meant for the Flow version | ├ ... ├ ... ├ ... @@ -196,9 +196,9 @@ You know how to do it. --- -#### Core definitions +#### Environment definitions -The above are instructions on how to submit a library definition against npm packages though the process is similar if contributing core definitions except instead of a package directory you just have an environment package that is the name of the environment without the need of versions. +The above are instructions on how to submit a library definition against npm packages though the process is similar if contributing environment definitions. Except instead of a package directory you just have an environment package that is the name of the environment without the need of versions. ## Libdef best practices diff --git a/cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js b/cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/environments/jsx/flow_v0.83.x-/jsx.js similarity index 100% rename from cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js rename to cli/src/commands/__tests__/__install-fixtures__/end-to-end/fakeCacheRepo/definitions/environments/jsx/flow_v0.83.x-/jsx.js diff --git a/cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js b/cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/environments/jsx/flow_v0.83.x-/jsx.js similarity index 100% rename from cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/core/jsx/flow_v0.83.x-/jsx.js rename to cli/src/commands/__tests__/__outdated-fixtures__/end-to-end/fakeCacheRepo/definitions/environments/jsx/flow_v0.83.x-/jsx.js diff --git a/cli/src/commands/__tests__/install-test.js b/cli/src/commands/__tests__/install-test.js index cb18bcd7c6..11a6e02daa 100644 --- a/cli/src/commands/__tests__/install-test.js +++ b/cli/src/commands/__tests__/install-test.js @@ -1233,8 +1233,8 @@ describe('install (command)', () => { }); }); - describe('core defs', () => { - it('installs core definitions if it exists in ft-config', () => { + describe('env defs', () => { + it('installs env definitions if it exists in flow-typed.config.json', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ @@ -1251,10 +1251,10 @@ describe('install (command)', () => { await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); await touchFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), ); await fs.writeJson( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), {env: ['jsx']}, ); @@ -1264,10 +1264,16 @@ describe('install (command)', () => { rootDir: path.join(FLOWPROJ_DIR, 'src'), }); - // Installs core definitions + // Installs env definitions expect( await fs.exists( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), ), ).toEqual(true); }); @@ -1294,19 +1300,33 @@ declare type jsx$HTMLElementProps = {||}`; await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); - await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core')); + await mkdirp( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'environments'), + ); await touchFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), ); await fs.writeFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), installedDef, ); await touchFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), ); await fs.writeJson( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), {env: ['jsx']}, ); @@ -1316,17 +1336,23 @@ declare type jsx$HTMLElementProps = {||}`; rootDir: path.join(FLOWPROJ_DIR, 'src'), }); - // Installs core definitions + // Installs env definitions expect( await fs.readFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), 'utf-8', ), ).toEqual(installedDef); }); }); - it('overrides the core definition if overwrite arg is passed in', () => { + it('overrides the env definition if overwrite arg is passed in', () => { const installedDef = `// flow-typed signature: fa26c13e83581eea415de59d5f03e123 // flow-typed version: /jsx/flow_>=v0.83.x @@ -1347,19 +1373,33 @@ declare type jsx$HTMLElementProps = {||}`; await touchFile(path.join(FLOWPROJ_DIR, 'src', '.flowconfig')); await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed')); - await mkdirp(path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core')); + await mkdirp( + path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'environments'), + ); await touchFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), ); await fs.writeFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), installedDef, ); await touchFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), ); await fs.writeJson( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'src', 'flow-typed.config.json'), {env: ['jsx']}, ); @@ -1370,10 +1410,16 @@ declare type jsx$HTMLElementProps = {||}`; overwrite: true, }); - // Installs core definitions + // Installs env definitions expect( await fs.readFile( - path.join(FLOWPROJ_DIR, 'src', 'flow-typed', 'core', 'jsx.js'), + path.join( + FLOWPROJ_DIR, + 'src', + 'flow-typed', + 'environments', + 'jsx.js', + ), 'utf-8', ), ).not.toEqual(installedDef); diff --git a/cli/src/commands/__tests__/outdated-test.js b/cli/src/commands/__tests__/outdated-test.js index f592f8a839..83ebda05b5 100644 --- a/cli/src/commands/__tests__/outdated-test.js +++ b/cli/src/commands/__tests__/outdated-test.js @@ -61,16 +61,16 @@ describe('outdated (command)', () => { const FAKE_CACHE_REPO_DIR = path.join(FAKE_CACHE_DIR, 'repo'); const FLOWPROJ_DIR = path.join(ROOT_DIR, 'flowProj'); const FLOWTYPED_DIR = path.join(FLOWPROJ_DIR, 'flow-typed', 'npm'); - const FLOWTYPED_CORE_DIR = path.join( + const FLOWTYPED_ENV_DIR = path.join( FLOWPROJ_DIR, 'flow-typed', - 'core', + 'environments', ); await Promise.all([ mkdirp(FAKE_CACHE_REPO_DIR), mkdirp(FLOWTYPED_DIR), - mkdirp(FLOWTYPED_CORE_DIR), + mkdirp(FLOWTYPED_ENV_DIR), ]); await copyDir(FIXTURE_FAKE_CACHE_REPO_DIR, FAKE_CACHE_REPO_DIR); @@ -260,7 +260,7 @@ declare module 'foo' {}`; }); }); - it('reports outdated core definitions as needing updates', () => { + it('reports outdated env definitions as needing updates', () => { const fooLibdef = `// flow-typed signature: fa26c13e83581eea415de59d5f03e416 // flow-typed version: /jsx/flow_>=v0.83.x @@ -279,11 +279,11 @@ declare module 'foo' {}`; mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), fs.writeFile( - path.join(FLOWPROJ_DIR, 'flow-typed', 'core', 'jsx.js'), + path.join(FLOWPROJ_DIR, 'flow-typed', 'environments', 'jsx.js'), fooLibdef, ), fs.writeFile( - path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'flow-typed.config.json'), '{ "env": ["jsx"] }', ), ]); @@ -292,7 +292,9 @@ declare module 'foo' {}`; expect( await Promise.all([ - fs.exists(path.join(FLOWPROJ_DIR, 'flow-typed', 'core', 'jsx.js')), + fs.exists( + path.join(FLOWPROJ_DIR, 'flow-typed', 'environments', 'jsx.js'), + ), ]), ).toEqual([true]); @@ -301,14 +303,14 @@ declare module 'foo' {}`; ['Name', 'Details'], [ 'jsx', - 'This core definition does not match what we found in the registry, update it with `flow-typed update`', + 'This env definition does not match what we found in the registry, update it with `flow-typed update`', ], ]), ); }); }); - it('reports outdated core definitions which do not exist in the registry', () => { + it('reports outdated env definitions which do not exist in the registry', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ @@ -322,7 +324,7 @@ declare module 'foo' {}`; mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), fs.writeFile( - path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'flow-typed.config.json'), '{ "env": ["random"] }', ), ]); @@ -334,14 +336,14 @@ declare module 'foo' {}`; ['Name', 'Details'], [ 'random', - 'This core definition does not exist in the registry or there is no compatible definition for your version of flow', + 'This env definition does not exist in the registry or there is no compatible definition for your version of flow', ], ]), ); }); }); - it('reports outdated core definition when it exists ft-config and registry but has not been installed', () => { + it('reports outdated env definition when it exists flow-typed.config.json and registry but has not been installed', () => { return fakeProjectEnv(async FLOWPROJ_DIR => { // Create some dependencies await Promise.all([ @@ -355,7 +357,7 @@ declare module 'foo' {}`; mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'foo')), mkdirp(path.join(FLOWPROJ_DIR, 'node_modules', 'flow-bin')), fs.writeFile( - path.join(FLOWPROJ_DIR, 'flow-typed', 'ft-config.json'), + path.join(FLOWPROJ_DIR, 'flow-typed.config.json'), '{ "env": ["jsx"] }', ), ]); @@ -367,7 +369,7 @@ declare module 'foo' {}`; ['Name', 'Details'], [ 'jsx', - 'This core def has not yet been installed try running `flow-typed install`', + 'This env def has not yet been installed try running `flow-typed install`', ], ]), ); diff --git a/cli/src/commands/install.js b/cli/src/commands/install.js index dade44f223..dc1882e0ee 100644 --- a/cli/src/commands/install.js +++ b/cli/src/commands/install.js @@ -9,7 +9,7 @@ import { CACHE_REPO_EXPIRY, } from '../lib/cacheRepoUtils'; import {signCodeStream, verifySignedCode} from '../lib/codeSign'; -import {getCoreDefs, findCoreDef, getCoreDefVersionHash} from '../lib/coreDefs'; +import {getEnvDefs, findEnvDef, getEnvDefVersionHash} from '../lib/envDefs'; import {copyFile, mkdirp} from '../lib/fileUtils'; import {findFlowRoot} from '../lib/flowProjectUtils'; import { @@ -169,7 +169,7 @@ export async function run(args: Args): Promise { return dep; }); - const ftConfig = getFtConfig(cwd, libdefDir); + const ftConfig = getFtConfig(cwd); if (args.cacheDir) { const cacheDir = path.resolve(String(args.cacheDir)); @@ -197,7 +197,7 @@ export async function run(args: Args): Promise { // Must be after `installNpmLibDefs` to ensure cache is updated first if (ftConfig) { - const coreLibDefResult = await installCoreLibDefs( + const envLibDefResult = await installEnvLibDefs( ftConfig, flowVersion, cwd, @@ -205,8 +205,8 @@ export async function run(args: Args): Promise { useCacheUntil, Boolean(args.overwrite), ); - if (coreLibDefResult !== 0) { - return coreLibDefResult; + if (envLibDefResult !== 0) { + return envLibDefResult; } } @@ -223,7 +223,7 @@ export async function run(args: Args): Promise { return 0; } -async function installCoreLibDefs( +async function installEnvLibDefs( {env}: FtConfig, flowVersion: FlowVersion, flowProjectRoot, @@ -234,23 +234,27 @@ async function installCoreLibDefs( if (env) { console.log( colors.green( - '• `env` key found in `ft-config`, attempting to install core definitions...\n', + '• `env` key found in `flow-typed.config.json`, attempting to install env definitions...\n', ), ); if (!Array.isArray(env)) { console.log( colors.yellow( - 'Warning: `env` in `ft-config.json` must be of type Array - skipping', + 'Warning: `env` in `flow-typed.config.json` must be of type Array - skipping', ), ); return 0; } - // Get a list of all core defs - const coreDefs = await getCoreDefs(); + // Get a list of all environment defs + const envDefs = await getEnvDefs(); - const flowTypedDirPath = path.join(flowProjectRoot, libdefDir, 'core'); + const flowTypedDirPath = path.join( + flowProjectRoot, + libdefDir, + 'environments', + ); await mkdirp(flowTypedDirPath); // Go through each env and try to install a libdef of the same name @@ -259,12 +263,7 @@ async function installCoreLibDefs( await Promise.all( env.map(async en => { if (typeof en === 'string') { - const def = await findCoreDef( - en, - flowVersion, - useCacheUntil, - coreDefs, - ); + const def = await findEnvDef(en, flowVersion, useCacheUntil, envDefs); if (def) { const fileName = `${en}.js`; @@ -297,7 +296,7 @@ async function installCoreLibDefs( `Read more at https://github.com/flow-typed/flow-typed/blob/master/CONTRIBUTING.md`, ), colors.yellow( - `Use --overwrite to overwrite the existing core defs.`, + `Use --overwrite to overwrite the existing env defs.`, ), ); return; @@ -306,7 +305,7 @@ async function installCoreLibDefs( fs.unlink(defLocalPath); } - const repoVersion = await getCoreDefVersionHash( + const repoVersion = await getEnvDefVersionHash( getCacheRepoDir(), def, ); @@ -461,7 +460,7 @@ async function installNpmLibDefs({ ][] = []; const unavailableLibDefs = []; - // This updates the cache for all definition types, npm/core/etc + // This updates the cache for all definition types, npm/env/etc const libDefs = await getCacheNpmLibDefs(useCacheUntil, skipCache); const getLibDefsToInstall = async (entries: Array<[string, string]>) => { diff --git a/cli/src/commands/outdated.js b/cli/src/commands/outdated.js index 450e574f91..4a230d06ce 100644 --- a/cli/src/commands/outdated.js +++ b/cli/src/commands/outdated.js @@ -15,7 +15,7 @@ import {determineFlowSpecificVersion} from '../lib/flowVersion'; import {signCodeStream} from '../lib/codeSign'; import {CACHE_REPO_EXPIRY, getCacheRepoDir} from '../lib/cacheRepoUtils'; import {getFtConfig} from '../lib/ftConfig'; -import {findCoreDef, getCoreDefVersionHash, getCoreDefs} from '../lib/coreDefs'; +import {findEnvDef, getEnvDefVersionHash, getEnvDefs} from '../lib/envDefs'; const pullSignature = v => v.split('\n').slice(0, 2); @@ -183,36 +183,36 @@ export async function run(args: Args): Promise { }), ); - const ftConfig = getFtConfig(cwd, libdefDir); + const ftConfig = getFtConfig(cwd); const {env} = ftConfig ?? {}; if (Array.isArray(env)) { - const coreDefs = await getCoreDefs(); + const envDefs = await getEnvDefs(); await Promise.all( env.map(async en => { if (typeof en !== 'string') return; - const def = await findCoreDef(en, flowVersion, useCacheUntil, coreDefs); + const def = await findEnvDef(en, flowVersion, useCacheUntil, envDefs); if (def) { const localDefPath = path.join( flowProjectRoot, libdefDir, - 'core', + 'environments', `${en}.js`, ); if (!(await fs.exists(localDefPath))) { outdatedList.push({ name: en, message: - 'This core def has not yet been installed try running `flow-typed install`', + 'This env def has not yet been installed try running `flow-typed install`', }); return; } else { const installedDef = fs.readFileSync(localDefPath, 'utf-8'); const installedSignatureArray = pullSignature(installedDef); - const repoVersion = await getCoreDefVersionHash( + const repoVersion = await getEnvDefVersionHash( getCacheRepoDir(), def, ); @@ -229,7 +229,7 @@ export async function run(args: Args): Promise { outdatedList.push({ name: en, message: - 'This core definition does not match what we found in the registry, update it with `flow-typed update`', + 'This env definition does not match what we found in the registry, update it with `flow-typed update`', }); } } @@ -237,7 +237,7 @@ export async function run(args: Args): Promise { outdatedList.push({ name: en, message: - 'This core definition does not exist in the registry or there is no compatible definition for your version of flow', + 'This env definition does not exist in the registry or there is no compatible definition for your version of flow', }); } }), diff --git a/cli/src/commands/runTests.js b/cli/src/commands/runTests.js index e71cc7a7ac..ef32bc728f 100644 --- a/cli/src/commands/runTests.js +++ b/cli/src/commands/runTests.js @@ -54,14 +54,16 @@ type TestGroup = { * structs. Each TestGroup represents a Package/PackageVersion/FlowVersion * directory. */ -const basePathRegex = new RegExp('definitions/(npm|core)/(@[^/]*/)?[^/]*/?'); +const basePathRegex = new RegExp( + 'definitions/(npm|environments)/(@[^/]*/)?[^/]*/?', +); async function getTestGroups( repoDirPath, - coreDirPath, + envDirPath, onlyChanged: boolean = false, ): Promise> { let libDefs = await getLibDefs(repoDirPath); - let coreDefs = await getLibDefs(coreDirPath); + let envDefs = await getLibDefs(envDirPath); if (onlyChanged) { const diff = await getDefinitionsDiff(); const baseDiff: string[] = diff @@ -82,7 +84,7 @@ async function getTestGroups( version: `v${major}.${minor}.${patch}`, }; }); - libDefs = [...libDefs, ...coreDefs].filter(def => + libDefs = [...libDefs, ...envDefs].filter(def => changedDefs.some(d => { if (d.version === 'vx.x.x') { return d.name === def.pkgName; @@ -616,14 +618,14 @@ async function runTestGroup( async function runTests( repoDirPath: string, - coreDirPath: string, + envDirPath: string, testPatterns: Array, onlyChanged?: boolean, numberOfFlowVersions?: number, ): Promise>> { const testPatternRes = testPatterns.map(patt => new RegExp(patt, 'g')); const testGroups = ( - await getTestGroups(repoDirPath, coreDirPath, onlyChanged) + await getTestGroups(repoDirPath, envDirPath, onlyChanged) ).filter(testGroup => { if (testPatternRes.length === 0) { return true; @@ -736,9 +738,9 @@ export async function run(argv: Args): Promise { const repoDirPath = (await fs.exists(cwdDefsNPMPath)) ? cwdDefsNPMPath : path.join(__dirname, '..', '..', '..', 'definitions', 'npm'); - const cwdDefsCorePath = path.join(basePath, 'definitions', 'core'); - const coreDirPath = (await fs.exists(cwdDefsCorePath)) - ? cwdDefsCorePath + const cwdDefsEnvPath = path.join(basePath, 'definitions', 'environments'); + const envDirPath = (await fs.exists(cwdDefsEnvPath)) + ? cwdDefsEnvPath : path.join(__dirname, '..', '..', '..', 'definitions', 'npm'); if (onlyChanged) { @@ -759,7 +761,7 @@ export async function run(argv: Args): Promise { try { results = await runTests( repoDirPath, - coreDirPath, + envDirPath, testPatterns, onlyChanged, numberOfFlowVersions, diff --git a/cli/src/lib/coreDefs.js b/cli/src/lib/envDefs.js similarity index 77% rename from cli/src/lib/coreDefs.js rename to cli/src/lib/envDefs.js index 426f9f24cb..b0a2f60f6a 100644 --- a/cli/src/lib/coreDefs.js +++ b/cli/src/lib/envDefs.js @@ -14,18 +14,18 @@ import { import {TEST_FILE_NAME_RE} from './libDefs'; import {findLatestFileCommitHash} from './git'; -type CoreLibDef = { +type EnvLibDef = { name: string, flowVersion: FlowVersion, path: string, testFilePaths: Array, }; -export const getCoreDefs = async (): Promise> => { +export const getEnvDefs = async (): Promise> => { const definitionsDir = path.join(getCacheRepoDir(), 'definitions'); - const coreDefsDirPath = path.join(definitionsDir, 'core'); + const envDefsDirPath = path.join(definitionsDir, 'environments'); - const dirItems = await fs.readdir(coreDefsDirPath); + const dirItems = await fs.readdir(envDefsDirPath); const errors = []; const proms = dirItems.map(async itemName => { // If a user opens definitions dir in finder it will create `.DS_Store` @@ -33,7 +33,7 @@ export const getCoreDefs = async (): Promise> => { if (itemName === '.DS_Store') return; try { - return await getSingleCoreDef(itemName, coreDefsDirPath); + return await getSingleEnvDef(itemName, envDefsDirPath); } catch (e) { errors.push(e); } @@ -46,12 +46,12 @@ export const getCoreDefs = async (): Promise> => { return [...settled].filter(Boolean).flat(); }; -const getSingleCoreDef = async (defName, coreDefPath) => { - const itemPath = path.join(coreDefPath, defName); +const getSingleEnvDef = async (defName, envDefPath) => { + const itemPath = path.join(envDefPath, defName); const itemStat = await fs.stat(itemPath); if (itemStat.isDirectory()) { // itemPath must be an env dir - return await extractCoreDefs(itemPath, defName); + return await extractEnvDefs(itemPath, defName); } else { throw new ValidationError( `Expected only directories to be present in this directory.`, @@ -59,11 +59,11 @@ const getSingleCoreDef = async (defName, coreDefPath) => { } }; -async function extractCoreDefs( +async function extractEnvDefs( envDirPath: string, defName: string, -): Promise> { - const coreDefFileName = `${defName}.js`; +): Promise> { + const envDefFileName = `${defName}.js`; const envDirItems = await fs.readdir(envDirPath); const commonTestFiles = []; @@ -91,7 +91,7 @@ async function extractCoreDefs( throw new ValidationError('No libdef files found!'); } - const coreDefs = []; + const envDefs = []; await Promise.all( parsedFlowDirs.map(async ([flowDirPath, flowVersion]) => { const testFilePaths = [...commonTestFiles]; @@ -104,8 +104,8 @@ async function extractCoreDefs( return; } - // Is this the libdef file? - if (flowDirItem === coreDefFileName) { + // Is this the env def file? + if (flowDirItem === envDefFileName) { libDefFilePath = path.join(flowDirPath, flowDirItem); return; } @@ -119,25 +119,25 @@ async function extractCoreDefs( } throw new ValidationError( - `Unexpected file: ${coreDefFileName}. This directory can only contain test files ` + - `or a libdef file named \`${coreDefFileName}\`.`, + `Unexpected file: ${envDefFileName}. This directory can only contain test files ` + + `or a env def file named \`${envDefFileName}\`.`, ); } else { throw new ValidationError( `Unexpected sub-directory. This directory can only contain test ` + - `files or a libdef file named \`${coreDefFileName}\`.`, + `files or a env def file named \`${envDefFileName}\`.`, ); } }); if (libDefFilePath === null) { - libDefFilePath = path.join(flowDirPath, coreDefFileName); + libDefFilePath = path.join(flowDirPath, envDefFileName); throw new ValidationError( - `No libdef file found. Looking for a file named ${coreDefFileName}`, + `No env def file found. Looking for a file named ${envDefFileName}`, ); } - coreDefs.push({ + envDefs.push({ name: defName, flowVersion, path: libDefFilePath, @@ -146,16 +146,16 @@ async function extractCoreDefs( }), ); - return coreDefs; + return envDefs; } -export const findCoreDef = ( +export const findEnvDef = ( defName: string, flowVersion: FlowVersion, useCacheUntil: number, - coreDefs: Array, -): CoreLibDef | void => { - return coreDefs.filter(def => { + envDefs: Array, +): EnvLibDef | void => { + return envDefs.filter(def => { let filterMatch = def.name === defName; if (!filterMatch) { @@ -177,9 +177,9 @@ export const findCoreDef = ( })[0]; }; -export async function getCoreDefVersionHash( +export async function getEnvDefVersionHash( repoDirPath: string, - libDef: CoreLibDef, + libDef: EnvLibDef, ): Promise { const latestCommitHash = await findLatestFileCommitHash( repoDirPath, diff --git a/cli/src/lib/ftConfig.js b/cli/src/lib/ftConfig.js index b8bfaedcc1..4477e07e1a 100644 --- a/cli/src/lib/ftConfig.js +++ b/cli/src/lib/ftConfig.js @@ -5,13 +5,10 @@ export type FtConfig = { env?: mixed, // Array, }; -export const getFtConfig = ( - cwd: string, - libdefDir: string, -): FtConfig | void => { +export const getFtConfig = (cwd: string): FtConfig | void => { try { return JSON.parse( - fs.readFileSync(path.join(cwd, libdefDir, 'ft-config.json'), 'utf-8'), + fs.readFileSync(path.join(cwd, 'flow-typed.config.json'), 'utf-8'), ); } catch (e) {} }; diff --git a/cli/src/lib/libDefs.js b/cli/src/lib/libDefs.js index e545104924..e3d3f46018 100644 --- a/cli/src/lib/libDefs.js +++ b/cli/src/lib/libDefs.js @@ -331,8 +331,8 @@ export function parseRepoDirItem( |} { const dirItem = path.basename(dirItemPath); - // Core definitions don't have versions nor need any sort of name validation - if (dirItemPath.includes('definitions/core')) { + // env definitions don't have versions nor need any sort of name validation + if (dirItemPath.includes('definitions/environments')) { return { pkgName: dirItem, pkgVersion: { diff --git a/cli/src/lib/npm/npmLibDefs.js b/cli/src/lib/npm/npmLibDefs.js index 6dcb18ceee..cbb96bec4c 100644 --- a/cli/src/lib/npm/npmLibDefs.js +++ b/cli/src/lib/npm/npmLibDefs.js @@ -57,7 +57,7 @@ async function extractLibDefsFromNpmPkgDir( pkgDirPath: string, scope: null | string, pkgNameVer: string, - // Remove eslint error after `core.es5` change + // Remove eslint error after `environments.es5` change // eslint-disable-next-line no-unused-vars validating?: boolean, ): Promise> { @@ -73,8 +73,8 @@ async function extractLibDefsFromNpmPkgDir( /** * TODO: - * The following block is commented out until `core.es5` has been moved to - * somewhere else such as core + * The following block is commented out until `environments.es5` has been moved to + * somewhere else such as environments */ // if (validating) { // const fullPkgName = `${scope === null ? '' : scope + '/'}${pkgName}`; @@ -366,7 +366,7 @@ function filterLibDefs( }); } -// TODO Unused until `core.es5` +// TODO Unused until `environments.es5` // async function _npmExists(pkgName: string): Promise { // const pkgUrl = `https://api.npms.io/v2/package/${encodeURIComponent( // pkgName, diff --git a/definitions/core/es5-1/README.md b/definitions/environments/es5-1/README.md similarity index 100% rename from definitions/core/es5-1/README.md rename to definitions/environments/es5-1/README.md diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js b/definitions/environments/es5-1/flow_v0.104.x-v0.142.x/es5-1.js similarity index 100% rename from definitions/core/es5-1/flow_v0.104.x-v0.142.x/es5-1.js rename to definitions/environments/es5-1/flow_v0.104.x-v0.142.x/es5-1.js diff --git a/definitions/core/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js b/definitions/environments/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js similarity index 100% rename from definitions/core/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js rename to definitions/environments/es5-1/flow_v0.104.x-v0.142.x/test_es5-1.js diff --git a/definitions/core/jsx/flow_v0.83.x-/jsx.js b/definitions/environments/jsx/flow_v0.83.x-/jsx.js similarity index 100% rename from definitions/core/jsx/flow_v0.83.x-/jsx.js rename to definitions/environments/jsx/flow_v0.83.x-/jsx.js diff --git a/definitions/core/jsx/flow_v0.83.x-/test_jsx.js b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js similarity index 100% rename from definitions/core/jsx/flow_v0.83.x-/test_jsx.js rename to definitions/environments/jsx/flow_v0.83.x-/test_jsx.js diff --git a/docs/_sidebar.md b/docs/_sidebar.md index 3af114e10a..5c773fd374 100644 --- a/docs/_sidebar.md +++ b/docs/_sidebar.md @@ -3,7 +3,7 @@ - [Importing types](usage.md) - [Advanced configuration](advanced.md) - [Contributing](contributing.md) - - [ft-config](ft-config.md) + - [flow-typed config](flow-typed-config.md) - CLI commands - [install](install.md) - [outdated](outdated.md) @@ -14,7 +14,7 @@ - [update-cache](cache.md) - [validate-defs](validate.md) - [version](version.md) -- [Core definitions](core-definitions.md) -- [Test Harness](harness.md) +- [Environment definitions](env-definitions.md) +- [Test harness](harness.md) - [FAQ](faq.md) - [Changelog](changelog.md) diff --git a/docs/core-definitions.md b/docs/env-definitions.md similarity index 63% rename from docs/core-definitions.md rename to docs/env-definitions.md index 7822852ec6..cdafd03bb7 100644 --- a/docs/core-definitions.md +++ b/docs/env-definitions.md @@ -1,14 +1,14 @@ -# Core Definitions +# Environment Definitions Flow is a static analysis tool that exposes a range of global definitions to help you type your application. But flow only supports for the most part, two types of environments, node and browser and sometimes you want something a little extra that flow just doesn't support and isn't quite right to have flow support as a core system. -That's where core definitions from flow-typed come into play, a home for all those global definitions to share and reuse and standardize for specific environments. +That's where env definitions from flow-typed come into play, a home for all those global definitions to share and reuse and standardize for specific environments. To make it more concrete, lets take a look at some examples of when you might want to create to leverage a core definition. ### jsx -Flow is built by Meta and ships with react definitions it does not type or provide a list of available jsx properties. These can live as a core definition instead. +Flow is built by Meta and ships with react definitions it does not type or provide a list of available jsx properties. These can live as an env definition instead. ``` type Props = {| @@ -28,10 +28,10 @@ const Input = ({ ### node -Although flow ships with both node and browser library definitions there is no mode to distinguish between the two. Sometimes this can cause conflict if there are api's that have the same name but drastically different type definitions depending on how which environment it's used in. A core definition could solve this as it's loaded after the built-in's and could override functionality of a declared var. +Although flow ships with both node and browser library definitions there is no mode to distinguish between the two. Sometimes this can cause conflict if there are api's that have the same name but drastically different type definitions depending on which environment it's used in. An env definition could solve this as it's loaded after the built-in's and could override functionality of a declared var. --- -These are just a couple examples but core definitions could serve a range of purposes for just about anything that isn't related to npm packages. +These are just a couple examples but env definitions could serve a range of purposes for just about anything that isn't related to npm packages. -The rules of creating a core definition are also quite similar to npm library definitions in that they support flow version ranges but differ in that they do not declare any modules nor have package versions. +The rules of creating an env definition are also quite similar to npm library definitions in that they support flow version ranges but differ in that they do not declare any modules nor have package versions. diff --git a/docs/flow-typed-config.md b/docs/flow-typed-config.md new file mode 100644 index 0000000000..2d30aa9cd8 --- /dev/null +++ b/docs/flow-typed-config.md @@ -0,0 +1,17 @@ +# flow-typed.config.json + +Flow-typed supports a config file to help you set various project level settings. + +`/flow-typed.config.json` + +## env + +`env` accepts an array of strings that map to environment definitions that you can you can find [here](https://github.com/flow-typed/flow-typed/tree/master/definitions/environments). + +```json +{ + "env": ["jsx", "node"] +} +``` + +Learn more about [environment definitions](env-definitions.md) diff --git a/docs/ft-config.md b/docs/ft-config.md deleted file mode 100644 index 15eb2983a1..0000000000 --- a/docs/ft-config.md +++ /dev/null @@ -1,17 +0,0 @@ -# ft-config.json - -Flow-typed supports a config file to help you set various project level settings. - -`./flow-typed/ft-config.json` - -## env - -`env` accepts an array of strings that map to environment (core) definitions that you can you can find [here](https://github.com/flow-typed/flow-typed/tree/master/definitions/core). - -```json -{ - "env": ["jsx", "node"] -} -``` - -Learn more about [core definitions](core-definitions.md) From 53f7de6e15bb9043c5506a459ae4d0e1a36e99e3 Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 2 Mar 2022 21:11:36 +1100 Subject: [PATCH 21/23] rename jsx types and add doc references --- .../environments/jsx/flow_v0.83.x-/jsx.js | 19 ++++++++++++++----- .../jsx/flow_v0.83.x-/test_jsx.js | 2 +- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/definitions/environments/jsx/flow_v0.83.x-/jsx.js b/definitions/environments/jsx/flow_v0.83.x-/jsx.js index 4739ab4da5..c2f5987559 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/jsx.js @@ -1,4 +1,7 @@ -declare type jsx$HTMLElementProps = {| +/** + * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#list_of_global_attributes + */ +declare type jsx$HTMLElement$Attributes = {| /** * Specifies a shortcut key to activate/focus an element */ @@ -53,7 +56,10 @@ declare type jsx$HTMLElementProps = {| translate?: string, |}; -declare type jsx$HTMLInputElementProps$Type = +/** + * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types + */ +declare type jsx$HTMLInputElement$Attributes$Type = | 'button' | 'checkbox' | 'color' @@ -77,8 +83,11 @@ declare type jsx$HTMLInputElementProps$Type = | 'url' | 'week'; -declare type jsx$HTMLInputElementProps = {| - ...jsx$HTMLElementProps, +/** + * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes + */ +declare type jsx$HTMLInputElement$Attributes = {| + ...jsx$HTMLElement$Attributes, value?: string, - type?: jsx$HTMLInputElementProps$Type, + type?: jsx$HTMLInputElement$Attributes$Type, |}; diff --git a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js index 6f312f5642..a67fa88c01 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js @@ -5,7 +5,7 @@ import * as React from 'react'; describe('jsx', () => { it('has input props', () => { type Props = {| - ...jsx$HTMLElementProps, + ...jsx$HTMLElement$Attributes, foo: string, |} From 75949475adb12bdde1c6d04bb9f523c53e7ec12f Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Wed, 2 Mar 2022 21:26:13 +1100 Subject: [PATCH 22/23] add jsx context --- definitions/environments/jsx/flow_v0.83.x-/jsx.js | 10 ++++++---- .../environments/jsx/flow_v0.83.x-/test_jsx.js | 2 +- docs/env-definitions.md | 14 ++++++++++++-- 3 files changed, 19 insertions(+), 7 deletions(-) diff --git a/definitions/environments/jsx/flow_v0.83.x-/jsx.js b/definitions/environments/jsx/flow_v0.83.x-/jsx.js index c2f5987559..1ee76d36f3 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/jsx.js @@ -1,7 +1,7 @@ /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#list_of_global_attributes */ -declare type jsx$HTMLElement$Attributes = {| +declare type jsx$HTMLElement$Attributes = { /** * Specifies a shortcut key to activate/focus an element */ @@ -54,7 +54,8 @@ declare type jsx$HTMLElement$Attributes = {| * Specifies whether the content of an element should be translated or not */ translate?: string, -|}; + ... +}; /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types @@ -86,8 +87,9 @@ declare type jsx$HTMLInputElement$Attributes$Type = /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes */ -declare type jsx$HTMLInputElement$Attributes = {| +declare type jsx$HTMLInputElement$Attributes = { ...jsx$HTMLElement$Attributes, value?: string, type?: jsx$HTMLInputElement$Attributes$Type, -|}; + ... +}; diff --git a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js index a67fa88c01..5670ea23f1 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js @@ -5,7 +5,7 @@ import * as React from 'react'; describe('jsx', () => { it('has input props', () => { type Props = {| - ...jsx$HTMLElement$Attributes, + ...$Exact, foo: string, |} diff --git a/docs/env-definitions.md b/docs/env-definitions.md index cdafd03bb7..f9fd980bbe 100644 --- a/docs/env-definitions.md +++ b/docs/env-definitions.md @@ -8,11 +8,21 @@ To make it more concrete, lets take a look at some examples of when you might wa ### jsx -Flow is built by Meta and ships with react definitions it does not type or provide a list of available jsx properties. These can live as an env definition instead. +Flow is built by Meta and ships with `react` library definitions. You'd expect because of that, everything react related would work perfectly and has sound static analysis working out of the box with a react stack. It however does not, you get no type checking or intellisense when using jsx elements nor are there any available list of HTML attributes for each HTML element type. + +```js +const Comp = () => ( + +); +``` + +Typically you'd expect the above to error in some capacity because `foo` is not a valid `type` and `anything` isn't a prop that `` accepts. But you get nothing and there's currently no way to add type definitions to primitive jsx as a third party tool. + +But with environment definitions serving reusable type definitions, at the minimum you can soundly type reusable components across your application. ``` type Props = {| - ...jsx$HTMLElementProps, + ...$Exact, foo: string, |}; From d7e083a1215ea45213236818ce0cef5ebc1733fd Mon Sep 17 00:00:00 2001 From: Brian Chen Date: Thu, 3 Mar 2022 05:27:13 +1100 Subject: [PATCH 23/23] add more tests to jsx --- .../environments/jsx/flow_v0.83.x-/jsx.js | 10 +-- .../jsx/flow_v0.83.x-/test_jsx.js | 83 +++++++++++++++---- 2 files changed, 74 insertions(+), 19 deletions(-) diff --git a/definitions/environments/jsx/flow_v0.83.x-/jsx.js b/definitions/environments/jsx/flow_v0.83.x-/jsx.js index 1ee76d36f3..4951b43fed 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/jsx.js @@ -1,7 +1,7 @@ /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes#list_of_global_attributes */ -declare type jsx$HTMLElement$Attributes = { + declare type jsx$HTMLElement = { /** * Specifies a shortcut key to activate/focus an element */ @@ -60,7 +60,7 @@ declare type jsx$HTMLElement$Attributes = { /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#input_types */ -declare type jsx$HTMLInputElement$Attributes$Type = +declare type jsx$HTMLInputElement$Type = | 'button' | 'checkbox' | 'color' @@ -87,9 +87,9 @@ declare type jsx$HTMLInputElement$Attributes$Type = /** * https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input#attributes */ -declare type jsx$HTMLInputElement$Attributes = { - ...jsx$HTMLElement$Attributes, +declare type jsx$HTMLInputElement = { + ...jsx$HTMLElement, value?: string, - type?: jsx$HTMLInputElement$Attributes$Type, + type?: jsx$HTMLInputElement$Type, ... }; diff --git a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js index 5670ea23f1..161453485b 100644 --- a/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js +++ b/definitions/environments/jsx/flow_v0.83.x-/test_jsx.js @@ -3,19 +3,74 @@ import { describe, it } from 'flow-typed-test'; import * as React from 'react'; describe('jsx', () => { - it('has input props', () => { - type Props = {| - ...$Exact, - foo: string, - |} - - const Input = ({ - foo, - - }: Props) => { - return ( - - ) - } + describe('HTMLElement', () => { + it('is inexact by default', () => { + type Props = { + ...jsx$HTMLElement, + foo: string, + ... + }; + + type ErrorProps = {| + ...jsx$HTMLElement, + foo: string, + |}; + }); + + it('can be cast to exact', () => { + type Props = {| + ...$Exact, + foo: string, + |}; + }); + + it('can override an attribute', () => { + type Props = {| + ...jsx$HTMLElement, + accessKey?: number, + className: string, + |}; + }); + }); + + describe('HTMLInputElement', () => { + it('has input props', () => { + type Props = {| + ...$Exact, + foo: string, + |}; + + const Input = ({ + foo, + // $FlowExpectedError[prop-missing] + bar, + ...otherProps + }: Props) => { + return ( + + ); + }; + }); + + it('input type can be extended', () => { + type Props = {| + ...$Exact, + type: jsx$HTMLInputElement$Type | 'extra', + |}; + + const Input = ({ + type, + ...otherProps + }: Props) => { + return ( + + ); + }; + + const a = + const b = + // $FlowExpectedError[incompatible-type] + const c = + }); }); });