mirror of
https://github.com/chenasraf/DefinitelyTyped-tools.git
synced 2026-05-18 01:49:03 +00:00
Format
This commit is contained in:
@@ -12,7 +12,7 @@ import {
|
||||
Semver,
|
||||
UncachedNpmInfoClient,
|
||||
NpmInfoRawVersions,
|
||||
NpmInfoVersion
|
||||
NpmInfoVersion,
|
||||
} from "@definitelytyped/utils";
|
||||
|
||||
export async function checkParseResults(
|
||||
@@ -56,11 +56,11 @@ export async function checkParseResults(
|
||||
await nAtATime(
|
||||
10,
|
||||
allPackages.allTypings(),
|
||||
pkg => checkNpm(pkg, log, dependedOn, client!),
|
||||
(pkg) => checkNpm(pkg, log, dependedOn, client!),
|
||||
options.progress
|
||||
? {
|
||||
name: "Checking for typed packages...",
|
||||
flavor: pkg => pkg.desc
|
||||
flavor: (pkg) => pkg.desc,
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
@@ -82,7 +82,7 @@ function checkTypeScriptVersions(allPackages: AllPackages): void {
|
||||
export function checkPathMappings(allPackages: AllPackages): void {
|
||||
for (const pkg of allPackages.allTypings()) {
|
||||
const unusedPathMappings = new Set(
|
||||
Object.keys(pkg.pathMappings).filter(m => m !== pkg.name && m !== pkg.unescapedName)
|
||||
Object.keys(pkg.pathMappings).filter((m) => m !== pkg.name && m !== pkg.unescapedName)
|
||||
);
|
||||
|
||||
// If A depends on B, and B has path mappings, A must have the same mappings.
|
||||
@@ -110,7 +110,7 @@ export function checkPathMappings(allPackages: AllPackages): void {
|
||||
throw new Error(`${pkg.desc} has unused path mappings for [${Array.from(unusedPathMappings).join(", ")}].
|
||||
If these mappings are actually used, they could be missing in a dependency's tsconfig.json instead.
|
||||
Check the path mappings for [${Array.from(allPackages.allDependencyTypings(pkg))
|
||||
.map(d => d.name)
|
||||
.map((d) => d.name)
|
||||
.join(", ")}].`);
|
||||
}
|
||||
}
|
||||
@@ -148,7 +148,7 @@ async function checkNpm(
|
||||
`Typings already defined for ${name} (${libraryName}) as of ${firstTypedVersion.versionString} (our version: ${ourVersion})`
|
||||
);
|
||||
const contributorUrls = contributors
|
||||
.map(c => {
|
||||
.map((c) => {
|
||||
const gh = "https://github.com/";
|
||||
return c.url.startsWith(gh) ? `@${c.url.slice(gh.length)}` : `${c.name} (${c.url})`;
|
||||
})
|
||||
@@ -222,5 +222,5 @@ const notNeededExceptions: ReadonlySet<string> = new Set([
|
||||
"raspi-serial",
|
||||
"raspi-soft-pwm",
|
||||
// Declare "typings" but don't actually have them yet (https://github.com/stampit-org/stampit/issues/245)
|
||||
"stampit"
|
||||
"stampit",
|
||||
]);
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
PackageId,
|
||||
PackageBase,
|
||||
getMangledNameForScopedPackage,
|
||||
formatDependencyVersion
|
||||
formatDependencyVersion,
|
||||
} from "./packages";
|
||||
|
||||
export interface Affected {
|
||||
@@ -16,10 +16,10 @@ export interface Affected {
|
||||
|
||||
/** Gets all packages that have changed on this branch, plus all packages affected by the change. */
|
||||
export function getAffectedPackages(allPackages: AllPackages, changedPackageIds: PackageId[]): Affected {
|
||||
const resolved = changedPackageIds.map(id => allPackages.tryResolve(id));
|
||||
const resolved = changedPackageIds.map((id) => allPackages.tryResolve(id));
|
||||
// If a package doesn't exist, that's because it was deleted.
|
||||
const changed = mapDefined(resolved, id => allPackages.tryGetTypingsData(id));
|
||||
const dependent = mapIterable(collectDependers(resolved, getReverseDependencies(allPackages, resolved)), p =>
|
||||
const changed = mapDefined(resolved, (id) => allPackages.tryGetTypingsData(id));
|
||||
const dependent = mapIterable(collectDependers(resolved, getReverseDependencies(allPackages, resolved)), (p) =>
|
||||
allPackages.getTypingsData(p)
|
||||
);
|
||||
return { changedPackages: changed, dependentPackages: sortPackages(dependent), allPackages };
|
||||
@@ -27,7 +27,7 @@ export function getAffectedPackages(allPackages: AllPackages, changedPackageIds:
|
||||
|
||||
/** Every package name in the original list, plus their dependencies (incl. dependencies' dependencies). */
|
||||
export function allDependencies(allPackages: AllPackages, packages: Iterable<TypingsData>): TypingsData[] {
|
||||
return sortPackages(transitiveClosure(packages, pkg => allPackages.allDependencyTypings(pkg)));
|
||||
return sortPackages(transitiveClosure(packages, (pkg) => allPackages.allDependencyTypings(pkg)));
|
||||
}
|
||||
|
||||
/** Collect all packages that depend on changed packages, and all that depend on those, etc. */
|
||||
@@ -35,7 +35,7 @@ function collectDependers(
|
||||
changedPackages: PackageId[],
|
||||
reverseDependencies: Map<PackageId, Set<PackageId>>
|
||||
): Set<PackageId> {
|
||||
const dependers = transitiveClosure(changedPackages, pkg => reverseDependencies.get(pkg) || []);
|
||||
const dependers = transitiveClosure(changedPackages, (pkg) => reverseDependencies.get(pkg) || []);
|
||||
// Don't include the original changed packages, just their dependers
|
||||
for (const original of changedPackages) {
|
||||
dependers.delete(original);
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
formatDependencyVersion,
|
||||
getDependencyFromFile,
|
||||
AllPackages,
|
||||
NotNeededPackage
|
||||
NotNeededPackage,
|
||||
} from "./packages";
|
||||
import {
|
||||
Logger,
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
assertDefined,
|
||||
Semver,
|
||||
UncachedNpmInfoClient,
|
||||
NpmInfo
|
||||
NpmInfo,
|
||||
} from "@definitelytyped/utils";
|
||||
import { getAffectedPackages } from "./get-affected-packages";
|
||||
|
||||
@@ -54,7 +54,7 @@ export async function gitDiff(log: Logger, definitelyTypedPath: string): Promise
|
||||
// We are probably already on master, so compare to the last commit.
|
||||
diff = (await run(`git diff ${sourceBranch}~1 --name-status`)).trim();
|
||||
}
|
||||
return diff.split("\n").map(line => {
|
||||
return diff.split("\n").map((line) => {
|
||||
const [status, file] = line.split(/\s+/, 2);
|
||||
return { status: status.trim(), file: file.trim() } as GitDiff;
|
||||
});
|
||||
@@ -95,7 +95,7 @@ export async function getAffectedPackagesFromDiff(
|
||||
) {
|
||||
const allPackages = await AllPackages.read(dt);
|
||||
const diffs = await gitDiff(consoleLogger.info, definitelyTypedPath);
|
||||
if (diffs.find(d => d.file === "notNeededPackages.json")) {
|
||||
if (diffs.find((d) => d.file === "notNeededPackages.json")) {
|
||||
const uncached = new UncachedNpmInfoClient();
|
||||
for (const deleted of getNotNeededPackages(allPackages, diffs)) {
|
||||
const source = await uncached.fetchNpmInfo(deleted.libraryName); // eg @babel/parser
|
||||
@@ -110,19 +110,19 @@ export async function getAffectedPackagesFromDiff(
|
||||
: selection === "affected"
|
||||
? getAffectedPackages(allPackages, gitChanges(diffs))
|
||||
: {
|
||||
changedPackages: allPackages.allTypings().filter(t => selection.test(t.name)),
|
||||
changedPackages: allPackages.allTypings().filter((t) => selection.test(t.name)),
|
||||
dependentPackages: [],
|
||||
allPackages
|
||||
allPackages,
|
||||
};
|
||||
|
||||
console.log(
|
||||
`Testing ${affected.changedPackages.length} changed packages: ${affected.changedPackages
|
||||
.map(t => t.desc)
|
||||
.map((t) => t.desc)
|
||||
.toString()}`
|
||||
);
|
||||
console.log(
|
||||
`Testing ${affected.dependentPackages.length} dependent packages: ${affected.dependentPackages
|
||||
.map(t => t.desc)
|
||||
.map((t) => t.desc)
|
||||
.toString()}`
|
||||
);
|
||||
return affected;
|
||||
@@ -169,9 +169,9 @@ it is supposed to replace, ${latestTypings.versionString} of ${unneeded.fullNpmN
|
||||
export function getNotNeededPackages(allPackages: AllPackages, diffs: GitDiff[]) {
|
||||
const deletedPackages = new Set(
|
||||
diffs
|
||||
.filter(d => d.status === "D")
|
||||
.filter((d) => d.status === "D")
|
||||
.map(
|
||||
d =>
|
||||
(d) =>
|
||||
assertDefined(
|
||||
getDependencyFromFile(d.file),
|
||||
`Unexpected file deleted: ${d.file}
|
||||
@@ -179,7 +179,7 @@ When removing packages, you should only delete files that are a part of removed
|
||||
).name
|
||||
)
|
||||
);
|
||||
return mapDefined(deletedPackages, p => {
|
||||
return mapDefined(deletedPackages, (p) => {
|
||||
const hasTyping = allPackages.hasTypingFor({ name: p, version: "*" });
|
||||
const notNeeded = allPackages.getNotNeededPackage(p);
|
||||
if (hasTyping) {
|
||||
|
||||
@@ -8,7 +8,7 @@ import { getTypingInfo } from "./definition-parser";
|
||||
export const definitionParserWorkerFilename = __filename;
|
||||
|
||||
if (!module.parent) {
|
||||
process.on("message", message => {
|
||||
process.on("message", (message) => {
|
||||
assert(process.argv.length === 3);
|
||||
const typesPath = process.argv[2];
|
||||
// tslint:disable-next-line no-async-without-await
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
PackageJsonDependency,
|
||||
TypingsDataRaw,
|
||||
TypingsVersionsRaw,
|
||||
DirectoryParsedTypingVersion
|
||||
DirectoryParsedTypingVersion,
|
||||
} from "../packages";
|
||||
import { getAllowedPackageJsonDependencies } from "./settings";
|
||||
import {
|
||||
@@ -26,7 +26,7 @@ import {
|
||||
unmangleScopedPackage,
|
||||
removeVersionFromPackageName,
|
||||
hasVersionNumberInMapping,
|
||||
mangleScopedPackage
|
||||
mangleScopedPackage,
|
||||
} from "@definitelytyped/utils";
|
||||
import { TypeScriptVersion } from "@definitelytyped/typescript-versions";
|
||||
|
||||
@@ -58,7 +58,7 @@ export async function getTypingInfo(packageName: string, fs: FS): Promise<Typing
|
||||
}
|
||||
const [rootDirectoryLs, olderVersionDirectories] = split<string, OlderVersionDir>(
|
||||
fs.readdir(),
|
||||
fileOrDirectoryName => {
|
||||
(fileOrDirectoryName) => {
|
||||
const version = parseVersionFromDirectoryName(fileOrDirectoryName);
|
||||
return version === undefined ? undefined : { directoryName: fileOrDirectoryName, version };
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export async function getTypingInfo(packageName: string, fs: FS): Promise<Typing
|
||||
|
||||
const latestData: TypingsDataRaw = {
|
||||
libraryVersionDirectoryName: undefined,
|
||||
...(await combineDataForAllTypesVersions(packageName, rootDirectoryLs, fs, undefined))
|
||||
...(await combineDataForAllTypesVersions(packageName, rootDirectoryLs, fs, undefined)),
|
||||
};
|
||||
|
||||
const older = await Promise.all(
|
||||
@@ -87,7 +87,7 @@ export async function getTypingInfo(packageName: string, fs: FS): Promise<Typing
|
||||
const ls = fs.readdir(directoryName);
|
||||
const data: TypingsDataRaw = {
|
||||
libraryVersionDirectoryName: formatTypingVersion(directoryVersion),
|
||||
...(await combineDataForAllTypesVersions(packageName, ls, fs.subDir(directoryName), directoryVersion))
|
||||
...(await combineDataForAllTypesVersions(packageName, ls, fs.subDir(directoryName), directoryVersion)),
|
||||
};
|
||||
|
||||
if (!matchesVersion(data, directoryVersion, considerLibraryMinorVersion)) {
|
||||
@@ -122,8 +122,8 @@ interface LsMinusTypesVersionsAndPackageJson {
|
||||
readonly hasPackageJson: boolean;
|
||||
}
|
||||
function getTypesVersionsAndPackageJson(ls: readonly string[]): LsMinusTypesVersionsAndPackageJson {
|
||||
const withoutPackageJson = ls.filter(name => name !== packageJsonName);
|
||||
const [remainingLs, typesVersions] = split(withoutPackageJson, fileOrDirectoryName => {
|
||||
const withoutPackageJson = ls.filter((name) => name !== packageJsonName);
|
||||
const [remainingLs, typesVersions] = split(withoutPackageJson, (fileOrDirectoryName) => {
|
||||
const match = /^ts(\d+\.\d+)$/.exec(fileOrDirectoryName);
|
||||
if (match === null) {
|
||||
return undefined;
|
||||
@@ -159,7 +159,7 @@ export function parseVersionFromDirectoryName(
|
||||
}
|
||||
return {
|
||||
major: Number(match[1]),
|
||||
minor: match[3] !== undefined ? Number(match[3]) : undefined // tslint:disable-line strict-type-predicates (false positive)
|
||||
minor: match[3] !== undefined ? Number(match[3]) : undefined, // tslint:disable-line strict-type-predicates (false positive)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -174,7 +174,7 @@ export function tryParsePackageVersion(versionString: string | undefined): Depen
|
||||
}
|
||||
return {
|
||||
major: Number(match[1]),
|
||||
minor: match[3] !== undefined ? Number(match[3]) : undefined // tslint:disable-line strict-type-predicates (false positive)
|
||||
minor: match[3] !== undefined ? Number(match[3]) : undefined, // tslint:disable-line strict-type-predicates (false positive)
|
||||
};
|
||||
}
|
||||
|
||||
@@ -204,7 +204,7 @@ async function combineDataForAllTypesVersions(
|
||||
libraryMinorVersion,
|
||||
typeScriptVersion: minTsVersion,
|
||||
libraryName,
|
||||
projects
|
||||
projects,
|
||||
} = parseHeaderOrFail(readFileAndThrowOnBOM("index.d.ts", fs));
|
||||
|
||||
const dataForRoot = getTypingDataForSingleTypesVersion(
|
||||
@@ -215,7 +215,7 @@ async function combineDataForAllTypesVersions(
|
||||
fs,
|
||||
directoryVersion
|
||||
);
|
||||
const dataForOtherTypesVersions = typesVersions.map(tsVersion => {
|
||||
const dataForOtherTypesVersions = typesVersions.map((tsVersion) => {
|
||||
const subFs = fs.subDir(`ts${tsVersion}`);
|
||||
return getTypingDataForSingleTypesVersion(
|
||||
tsVersion,
|
||||
@@ -242,7 +242,7 @@ async function combineDataForAllTypesVersions(
|
||||
|
||||
const files = Array.from(
|
||||
flatMap(allTypesVersions, ({ typescriptVersion, declFiles }) =>
|
||||
declFiles.map(file => (typescriptVersion === undefined ? file : `ts${typescriptVersion}/${file}`))
|
||||
declFiles.map((file) => (typescriptVersion === undefined ? file : `ts${typescriptVersion}/${file}`))
|
||||
)
|
||||
);
|
||||
|
||||
@@ -258,25 +258,25 @@ async function combineDataForAllTypesVersions(
|
||||
typesVersions,
|
||||
files,
|
||||
license,
|
||||
dependencies: Object.assign({}, ...allTypesVersions.map(v => v.dependencies)),
|
||||
dependencies: Object.assign({}, ...allTypesVersions.map((v) => v.dependencies)),
|
||||
testDependencies: getAllUniqueValues<"testDependencies", string>(allTypesVersions, "testDependencies"),
|
||||
pathMappings: Object.assign({}, ...allTypesVersions.map(v => v.pathMappings)),
|
||||
pathMappings: Object.assign({}, ...allTypesVersions.map((v) => v.pathMappings)),
|
||||
packageJsonDependencies,
|
||||
contentHash: hash(
|
||||
hasPackageJson ? [...files, packageJsonName] : files,
|
||||
mapDefined(allTypesVersions, a => a.tsconfigPathsForHash),
|
||||
mapDefined(allTypesVersions, (a) => a.tsconfigPathsForHash),
|
||||
fs
|
||||
),
|
||||
globals: getAllUniqueValues<"globals", string>(allTypesVersions, "globals"),
|
||||
declaredModules: getAllUniqueValues<"declaredModules", string>(allTypesVersions, "declaredModules"),
|
||||
imports: checkPackageJsonImports(packageJson.imports, packageJsonName),
|
||||
exports: checkPackageJsonExportsAndAddPJsonEntry(packageJson.exports, packageJsonName),
|
||||
type: checkPackageJsonType(packageJson.type, packageJsonName)
|
||||
type: checkPackageJsonType(packageJson.type, packageJsonName),
|
||||
};
|
||||
}
|
||||
|
||||
function getAllUniqueValues<K extends string, T>(records: readonly Record<K, readonly T[]>[], key: K): readonly T[] {
|
||||
return unique(flatMap(records, x => x[key]));
|
||||
return unique(flatMap(records, (x) => x[key]));
|
||||
}
|
||||
|
||||
interface TypingDataFromIndividualTypeScriptVersion {
|
||||
@@ -332,7 +332,7 @@ function getTypingDataForSingleTypesVersion(
|
||||
checkAllFilesUsed(ls, usedFiles, otherFiles, packageName, fs);
|
||||
for (const untestedTypeFile of filter(
|
||||
otherFiles,
|
||||
name => name.endsWith(".d.ts") || name.endsWith(".d.mts") || name.endsWith(".d.cts")
|
||||
(name) => name.endsWith(".d.ts") || name.endsWith(".d.mts") || name.endsWith(".d.cts")
|
||||
)) {
|
||||
// add d.ts files from OTHER_FILES.txt in order get their dependencies
|
||||
// tslint:disable-next-line:non-literal-fs-path -- Not a reference to the fs package
|
||||
@@ -340,11 +340,14 @@ function getTypingDataForSingleTypesVersion(
|
||||
}
|
||||
|
||||
const { dependencies: dependenciesWithDeclaredModules, globals, declaredModules } = getModuleInfo(packageName, types);
|
||||
const declaredRootModules = new Set(declaredModules.map(m => rootName(m, types, packageName)));
|
||||
const declaredRootModules = new Set(declaredModules.map((m) => rootName(m, types, packageName)));
|
||||
// Don't count an import of "x" as a dependency if we saw `declare module "x"` somewhere.
|
||||
const dependenciesSet = new Set(filter(dependenciesWithDeclaredModules, m => !declaredRootModules.has(m)));
|
||||
const dependenciesSet = new Set(filter(dependenciesWithDeclaredModules, (m) => !declaredRootModules.has(m)));
|
||||
const testDependencies = Array.from(
|
||||
filter(getTestDependencies(packageName, types, tests.keys(), dependenciesSet, fs), m => !declaredRootModules.has(m))
|
||||
filter(
|
||||
getTestDependencies(packageName, types, tests.keys(), dependenciesSet, fs),
|
||||
(m) => !declaredRootModules.has(m)
|
||||
)
|
||||
);
|
||||
|
||||
const { paths } = tsconfig.compilerOptions;
|
||||
@@ -373,7 +376,7 @@ function getTypingDataForSingleTypesVersion(
|
||||
globals,
|
||||
declaredModules,
|
||||
declFiles: sort(types.keys()),
|
||||
tsconfigPathsForHash
|
||||
tsconfigPathsForHash,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -494,7 +497,7 @@ Other d.ts files must either be referenced through index.d.ts, tests, or added t
|
||||
}
|
||||
|
||||
function isRelativePath(path: string) {
|
||||
return path.split(/\//).every(part => part.length > 0 && !part.match(/^\.+$|[\\\n\r]/));
|
||||
return path.split(/\//).every((part) => part.length > 0 && !part.match(/^\.+$|[\\\n\r]/));
|
||||
}
|
||||
|
||||
interface TsConfig {
|
||||
@@ -633,7 +636,7 @@ const nodeBuiltins: ReadonlySet<string> = new Set([
|
||||
"util",
|
||||
"v8",
|
||||
"vm",
|
||||
"zlib"
|
||||
"zlib",
|
||||
]);
|
||||
|
||||
function parseDependencyVersionFromPath(
|
||||
@@ -657,7 +660,7 @@ function withoutEnd(s: string, end: string): string | undefined {
|
||||
}
|
||||
|
||||
function hash(files: readonly string[], tsconfigPathsForHash: readonly string[], fs: FS): string {
|
||||
const fileContents = files.map(f => `${f}**${readFileAndThrowOnBOM(f, fs)}`);
|
||||
const fileContents = files.map((f) => `${f}**${readFileAndThrowOnBOM(f, fs)}`);
|
||||
let allContent = fileContents.join("||");
|
||||
for (const path of tsconfigPathsForHash) {
|
||||
allContent += path;
|
||||
|
||||
@@ -85,7 +85,7 @@ export function getModuleInfo(packageName: string, all: Map<string, ts.SourceFil
|
||||
* A module with only imports is not a proper module; it likely just augments some other module.
|
||||
*/
|
||||
function sourceFileExportsSomething({ statements }: ts.SourceFile): boolean {
|
||||
return statements.some(statement => {
|
||||
return statements.some((statement) => {
|
||||
switch (statement.kind) {
|
||||
case ts.SyntaxKind.ImportEqualsDeclaration:
|
||||
case ts.SyntaxKind.ImportDeclaration:
|
||||
@@ -161,7 +161,7 @@ export function allReferencedFiles(
|
||||
const types = new Map<string, ts.SourceFile>();
|
||||
const tests = new Map<string, ts.SourceFile>();
|
||||
let hasNonRelativeImports = false;
|
||||
entryFilenames.forEach(text => recur({ text, exact: true }));
|
||||
entryFilenames.forEach((text) => recur({ text, exact: true }));
|
||||
return { types, tests, hasNonRelativeImports };
|
||||
|
||||
function recur({ text, exact }: Reference): void {
|
||||
|
||||
@@ -18,7 +18,7 @@ const allowedPackageJsonDependenciesUrl =
|
||||
"https://raw.githubusercontent.com/microsoft/DefinitelyTyped-tools/master/packages/definitions-parser/allowedPackageJsonDependencies.txt";
|
||||
|
||||
export const getAllowedPackageJsonDependencies = withCache(60 * 60 * 1000, () => {
|
||||
return new Promise<ReadonlySet<string>>(async resolve => {
|
||||
return new Promise<ReadonlySet<string>>(async (resolve) => {
|
||||
let raw = readFileSync(joinPaths(root, "allowedPackageJsonDependencies.txt"));
|
||||
if (process.env.NODE_ENV !== "test") {
|
||||
try {
|
||||
|
||||
@@ -3,9 +3,9 @@ import * as https from "https";
|
||||
export function getUrlContentsAsString(url: string): Promise<string> {
|
||||
return new Promise<string>((resolve, reject) => {
|
||||
https
|
||||
.get(url, res => {
|
||||
.get(url, (res) => {
|
||||
let data = "";
|
||||
res.on("data", d => (data += d));
|
||||
res.on("data", (d) => (data += d));
|
||||
res.on("end", () => {
|
||||
resolve(data);
|
||||
});
|
||||
|
||||
@@ -13,9 +13,9 @@ class DTMock {
|
||||
packages: {
|
||||
angular: {
|
||||
libraryName: "angular",
|
||||
asOfVersion: "1.2.3"
|
||||
}
|
||||
}
|
||||
asOfVersion: "1.2.3",
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
this.fs = new InMemoryFS(this.root, "DefinitelyTyped");
|
||||
@@ -56,9 +56,9 @@ class DTMock {
|
||||
compilerOptions: {
|
||||
...tsconfig.compilerOptions,
|
||||
paths: {
|
||||
[packageName]: [`${mangleScopedPackage(packageName)}/v${olderVersion}`]
|
||||
}
|
||||
}
|
||||
[packageName]: [`${mangleScopedPackage(packageName)}/v${olderVersion}`],
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
@@ -233,10 +233,10 @@ export * from "moment"`
|
||||
JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
jquery: ["jquery/v1"]
|
||||
}
|
||||
jquery: ["jquery/v1"],
|
||||
},
|
||||
},
|
||||
files: ["index.d.ts", "has-older-test-dependency-tests.ts"]
|
||||
files: ["index.d.ts", "has-older-test-dependency-tests.ts"],
|
||||
})
|
||||
);
|
||||
|
||||
@@ -282,10 +282,10 @@ console.log(jQuery);
|
||||
JSON.stringify({
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"@wordpress/*": ["wordpress__*"]
|
||||
}
|
||||
"@wordpress/*": ["wordpress__*"],
|
||||
},
|
||||
},
|
||||
files: ["index.d.ts"]
|
||||
files: ["index.d.ts"],
|
||||
})
|
||||
);
|
||||
|
||||
@@ -315,7 +315,7 @@ function tsconfig(testNames: string[]) {
|
||||
},
|
||||
"files": [
|
||||
"index.d.ts",
|
||||
${testNames.map(s => " " + JSON.stringify(s)).join(",\n")}
|
||||
${testNames.map((s) => " " + JSON.stringify(s)).join(",\n")}
|
||||
]
|
||||
}`;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
unmangleScopedPackage,
|
||||
Semver,
|
||||
assertDefined,
|
||||
unique
|
||||
unique,
|
||||
} from "@definitelytyped/utils";
|
||||
import { AllTypeScriptVersion, TypeScriptVersion } from "@definitelytyped/typescript-versions";
|
||||
import { readDataFile } from "./data-file";
|
||||
@@ -21,7 +21,7 @@ export class AllPackages {
|
||||
|
||||
static from(data: TypesDataFile, notNeeded: readonly NotNeededPackage[]): AllPackages {
|
||||
return new AllPackages(
|
||||
mapValues(new Map(Object.entries(data)), raw => new TypingsVersions(raw)),
|
||||
mapValues(new Map(Object.entries(data)), (raw) => new TypingsVersions(raw)),
|
||||
notNeeded
|
||||
);
|
||||
}
|
||||
@@ -49,7 +49,7 @@ export class AllPackages {
|
||||
|
||||
static readSingleNotNeeded(name: string, dt: FS): NotNeededPackage {
|
||||
const notNeeded = readNotNeededPackages(dt);
|
||||
const pkg = notNeeded.find(p => p.name === name);
|
||||
const pkg = notNeeded.find((p) => p.name === name);
|
||||
if (pkg === undefined) {
|
||||
throw new Error(`Cannot find not-needed package ${name}`);
|
||||
}
|
||||
@@ -62,7 +62,7 @@ export class AllPackages {
|
||||
) {}
|
||||
|
||||
getNotNeededPackage(name: string): NotNeededPackage | undefined {
|
||||
return this.notNeeded.find(p => p.name === name);
|
||||
return this.notNeeded.find((p) => p.name === name);
|
||||
}
|
||||
|
||||
hasTypingFor(dep: PackageId): boolean {
|
||||
@@ -75,7 +75,7 @@ export class AllPackages {
|
||||
*/
|
||||
hasSeparateMinorVersions(name: string) {
|
||||
const versions = Array.from(assertDefined(this.data.get(getMangledNameForScopedPackage(name))).getAll());
|
||||
const minors = versions.map(v => v.minor);
|
||||
const minors = versions.map((v) => v.minor);
|
||||
return minors.length !== unique(minors).length;
|
||||
}
|
||||
|
||||
@@ -129,13 +129,13 @@ export class AllPackages {
|
||||
|
||||
/** Note: this includes older version directories (`foo/v0`) */
|
||||
allTypings(): readonly TypingsData[] {
|
||||
return assertSorted(Array.from(flattenData(this.data)), t => t.name);
|
||||
return assertSorted(Array.from(flattenData(this.data)), (t) => t.name);
|
||||
}
|
||||
|
||||
allLatestTypings(): readonly TypingsData[] {
|
||||
return assertSorted(
|
||||
Array.from(this.data.values()).map(versions => versions.getLatest()),
|
||||
t => t.name
|
||||
Array.from(this.data.values()).map((versions) => versions.getLatest()),
|
||||
(t) => t.name
|
||||
);
|
||||
}
|
||||
|
||||
@@ -476,7 +476,7 @@ export interface TypingsDataRaw extends BaseRaw {
|
||||
// Note that BSD is not supported -- for that, we'd have to choose a *particular* BSD license from the list at https://spdx.org/licenses/
|
||||
export const enum License {
|
||||
MIT = "MIT",
|
||||
Apache20 = "Apache-2.0"
|
||||
Apache20 = "Apache-2.0",
|
||||
}
|
||||
const allLicenses = [License.MIT, License.Apache20];
|
||||
export function getLicenseFromPackageJson(packageJsonLicense: unknown): License {
|
||||
@@ -509,7 +509,7 @@ export class TypingsVersions {
|
||||
* This is important because older versions repeatedly reset the "latest" tag to the current version.
|
||||
*/
|
||||
this.versions = Object.keys(data)
|
||||
.map(key => Semver.parse(key, true))
|
||||
.map((key) => Semver.parse(key, true))
|
||||
.sort(Semver.compare)
|
||||
.reverse();
|
||||
|
||||
@@ -544,7 +544,7 @@ export class TypingsVersions {
|
||||
|
||||
private tryGetLatestMatch(version: DirectoryParsedTypingVersion): TypingsData | undefined {
|
||||
const found = this.versions.find(
|
||||
v => v.major === version.major && (version.minor === undefined || v.minor === version.minor)
|
||||
(v) => v.major === version.major && (version.minor === undefined || v.minor === version.minor)
|
||||
);
|
||||
return found && this.map.get(found);
|
||||
}
|
||||
@@ -583,7 +583,7 @@ export class TypingsData extends PackageBase {
|
||||
return this.data.files;
|
||||
}
|
||||
get dtsFiles(): readonly string[] {
|
||||
return this.data.files.filter(f => f.endsWith(".d.ts") || f.endsWith(".d.mts") || f.endsWith(".d.cts"));
|
||||
return this.data.files.filter((f) => f.endsWith(".d.ts") || f.endsWith(".d.mts") || f.endsWith(".d.cts"));
|
||||
}
|
||||
get license(): License {
|
||||
return this.data.license;
|
||||
@@ -653,7 +653,7 @@ function readTypesDataFile(): Promise<TypesDataFile> {
|
||||
|
||||
export function readNotNeededPackages(dt: FS): readonly NotNeededPackage[] {
|
||||
const rawJson = dt.readJson("notNeededPackages.json"); // tslint:disable-line await-promise (tslint bug)
|
||||
return Object.entries((rawJson as { readonly packages: readonly NotNeededPackageRaw[] }).packages).map(entry =>
|
||||
return Object.entries((rawJson as { readonly packages: readonly NotNeededPackageRaw[] }).packages).map((entry) =>
|
||||
NotNeededPackage.fromRaw(...entry)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ export async function parseDefinitions(
|
||||
): Promise<AllPackages> {
|
||||
log.info("Parsing definitions...");
|
||||
const typesFS = dt.subDir("types");
|
||||
const packageNames = await filterNAtATimeOrdered(parallel ? parallel.nProcesses : 1, typesFS.readdir(), name =>
|
||||
const packageNames = await filterNAtATimeOrdered(parallel ? parallel.nProcesses : 1, typesFS.readdir(), (name) =>
|
||||
typesFS.isDirectory(name)
|
||||
);
|
||||
log.info(`Found ${packageNames.length} packages.`);
|
||||
@@ -35,7 +35,7 @@ export async function parseDefinitions(
|
||||
nProcesses: parallel.nProcesses,
|
||||
handleOutput({ data, packageName }: { data: TypingsVersionsRaw; packageName: string }) {
|
||||
typings[packageName] = data;
|
||||
}
|
||||
},
|
||||
});
|
||||
} else {
|
||||
log.info("Parsing in main process...");
|
||||
|
||||
@@ -36,7 +36,7 @@ testo({
|
||||
{ application: "*", error: "*" },
|
||||
[],
|
||||
makeMappings("application", "engine", "object", "routing", "controller", "service", "error")
|
||||
)
|
||||
),
|
||||
};
|
||||
expect(checkPathMappings(AllPackages.from(typesData, []))).toBeUndefined();
|
||||
},
|
||||
@@ -68,12 +68,12 @@ testo({
|
||||
{ application: "*", error: "*" },
|
||||
[],
|
||||
makeMappings("application", "engine", "object", "routing", "controller", "service", "error")
|
||||
)
|
||||
),
|
||||
};
|
||||
expect(() => checkPathMappings(AllPackages.from(typesData, []))).toThrow(
|
||||
`test-helper has unused path mappings for [controller, service].
|
||||
If these mappings are actually used, they could be missing in a dependency's tsconfig.json instead.
|
||||
Check the path mappings for [application, error].`
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -36,9 +36,9 @@ import * as utils from '@ckeditor/ckeditor5-utils';`
|
||||
files: ["index.d.ts"],
|
||||
compilerOptions: {
|
||||
paths: {
|
||||
"@ckeditor/ckeditor5-utils": ["ckeditor__ckeditor5-utils/v10"]
|
||||
}
|
||||
}
|
||||
"@ckeditor/ckeditor5-utils": ["ckeditor__ckeditor5-utils/v10"],
|
||||
},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
@@ -57,8 +57,8 @@ export function myFunction(arg:string): string;
|
||||
JSON.stringify({
|
||||
files: ["index.d.ts"],
|
||||
compilerOptions: {
|
||||
paths: {}
|
||||
}
|
||||
paths: {},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
@@ -253,15 +253,15 @@ import route = require('@ember/routing/route');
|
||||
|
||||
expect(info).toEqual({
|
||||
"1.5": expect.objectContaining({
|
||||
libraryVersionDirectoryName: "1.5"
|
||||
libraryVersionDirectoryName: "1.5",
|
||||
}),
|
||||
"2.0": expect.objectContaining({
|
||||
libraryVersionDirectoryName: "2"
|
||||
libraryVersionDirectoryName: "2",
|
||||
}),
|
||||
"3.3": expect.objectContaining({
|
||||
// The latest version does not have its own version directory
|
||||
libraryVersionDirectoryName: undefined
|
||||
})
|
||||
libraryVersionDirectoryName: undefined,
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -274,18 +274,18 @@ import route = require('@ember/routing/route');
|
||||
expect(info).toEqual({
|
||||
"1.5": expect.objectContaining({
|
||||
pathMappings: {
|
||||
jquery: { major: 1, minor: 5 }
|
||||
}
|
||||
jquery: { major: 1, minor: 5 },
|
||||
},
|
||||
}),
|
||||
"2.0": expect.objectContaining({
|
||||
pathMappings: {
|
||||
jquery: { major: 2, minor: undefined }
|
||||
}
|
||||
jquery: { major: 2, minor: undefined },
|
||||
},
|
||||
}),
|
||||
"3.3": expect.objectContaining({
|
||||
// The latest version does not have path mappings of its own
|
||||
pathMappings: {}
|
||||
})
|
||||
pathMappings: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -297,8 +297,8 @@ import route = require('@ember/routing/route');
|
||||
JSON.stringify({
|
||||
files: ["index.d.ts"],
|
||||
compilerOptions: {
|
||||
paths: {}
|
||||
}
|
||||
paths: {},
|
||||
},
|
||||
})
|
||||
);
|
||||
pkg.set(
|
||||
@@ -316,13 +316,13 @@ import route = require('@ember/routing/route');
|
||||
expect(info).toEqual({
|
||||
"10.0": expect.objectContaining({
|
||||
pathMappings: {
|
||||
"@ckeditor/ckeditor5-utils": { major: 10 }
|
||||
}
|
||||
"@ckeditor/ckeditor5-utils": { major: 10 },
|
||||
},
|
||||
}),
|
||||
"25.0": expect.objectContaining({
|
||||
// The latest version does not have path mappings of its own
|
||||
pathMappings: {}
|
||||
})
|
||||
pathMappings: {},
|
||||
}),
|
||||
});
|
||||
});
|
||||
|
||||
@@ -384,8 +384,8 @@ import first from "@ckeditor/ckeditor5-utils/src/first";
|
||||
JSON.stringify({
|
||||
files: ["index.d.ts"],
|
||||
compilerOptions: {
|
||||
paths: {}
|
||||
}
|
||||
paths: {},
|
||||
},
|
||||
})
|
||||
);
|
||||
|
||||
|
||||
@@ -4,14 +4,14 @@ import { testo, createTypingsVersionRaw } from "./utils";
|
||||
|
||||
const typesData: TypesDataFile = {
|
||||
"has-older-test-dependency": createTypingsVersionRaw("has-older-test-dependency", {}, ["jquery"], {
|
||||
jquery: { major: 1 }
|
||||
jquery: { major: 1 },
|
||||
}),
|
||||
jquery: createTypingsVersionRaw("jquery", {}, [], {}),
|
||||
known: createTypingsVersionRaw("known", { jquery: { major: 1 } }, [], {}),
|
||||
"known-test": createTypingsVersionRaw("known-test", {}, ["jquery"], {}),
|
||||
"most-recent": createTypingsVersionRaw("most-recent", { jquery: "*" }, [], {}),
|
||||
unknown: createTypingsVersionRaw("unknown", { "COMPLETELY-UNKNOWN": { major: 1 } }, [], {}),
|
||||
"unknown-test": createTypingsVersionRaw("unknown-test", {}, ["WAT"], {})
|
||||
"unknown-test": createTypingsVersionRaw("unknown-test", {}, ["WAT"], {}),
|
||||
};
|
||||
typesData.jquery["2.0"] = { ...typesData.jquery["1.0"], libraryMajorVersion: 2 };
|
||||
|
||||
@@ -21,13 +21,13 @@ const allPackages = AllPackages.from(typesData, notNeeded);
|
||||
testo({
|
||||
updatedPackage() {
|
||||
const { changedPackages, dependentPackages } = getAffectedPackages(allPackages, [
|
||||
{ name: "jquery", version: { major: 2 } }
|
||||
{ name: "jquery", version: { major: 2 } },
|
||||
]);
|
||||
expect(changedPackages.map(({ id }) => id)).toEqual([{ name: "jquery", version: { major: 2, minor: 0 } }]);
|
||||
expect((changedPackages[0] as any).data).toEqual(typesData.jquery["2.0"]);
|
||||
expect(dependentPackages.map(({ id }) => id)).toEqual([
|
||||
{ name: "known-test", version: { major: 1, minor: 0 } },
|
||||
{ name: "most-recent", version: { major: 1, minor: 0 } }
|
||||
{ name: "most-recent", version: { major: 1, minor: 0 } },
|
||||
]);
|
||||
},
|
||||
deletedPackage() {
|
||||
@@ -41,12 +41,12 @@ testo({
|
||||
},
|
||||
olderVersion() {
|
||||
const { changedPackages, dependentPackages } = getAffectedPackages(allPackages, [
|
||||
{ name: "jquery", version: { major: 1 } }
|
||||
{ name: "jquery", version: { major: 1 } },
|
||||
]);
|
||||
expect(changedPackages.map(({ id }) => id)).toEqual([{ name: "jquery", version: { major: 1, minor: 0 } }]);
|
||||
expect(dependentPackages.map(({ id }) => id)).toEqual([
|
||||
{ name: "has-older-test-dependency", version: { major: 1, minor: 0 } },
|
||||
{ name: "known", version: { major: 1, minor: 0 } }
|
||||
{ name: "known", version: { major: 1, minor: 0 } },
|
||||
]);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ testo({
|
||||
{
|
||||
definitelyTypedPath: undefined,
|
||||
parseInParallel: false,
|
||||
progress: false
|
||||
progress: false,
|
||||
},
|
||||
quietLoggerWithErrors()[0]
|
||||
);
|
||||
@@ -30,5 +30,5 @@ testo({
|
||||
expect(fs.exists("file1.txt")).toBe(true);
|
||||
expect(fs.readFile("file1.txt")).toBe("ok");
|
||||
expect(fs.readFile("sub1/file2.txt")).toBe("x");
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -9,7 +9,7 @@ const typesData: TypesDataFile = {
|
||||
"known-test": createTypingsVersionRaw("known-test", {}, ["jquery"], {}),
|
||||
"most-recent": createTypingsVersionRaw("most-recent", { jquery: "*" }, [], {}),
|
||||
unknown: createTypingsVersionRaw("unknown", { "COMPLETELY-UNKNOWN": { major: 1 } }, [], {}),
|
||||
"unknown-test": createTypingsVersionRaw("unknown-test", {}, ["WAT"], {})
|
||||
"unknown-test": createTypingsVersionRaw("unknown-test", {}, ["WAT"], {}),
|
||||
};
|
||||
|
||||
const jestNotNeeded = [new NotNeededPackage("jest", "jest", "100.0.0")];
|
||||
@@ -18,7 +18,7 @@ const allPackages = AllPackages.from(typesData, jestNotNeeded);
|
||||
const deleteJestDiffs: GitDiff[] = [
|
||||
{ status: "M", file: "notNeededPackages.json" },
|
||||
{ status: "D", file: "types/jest/index.d.ts" },
|
||||
{ status: "D", file: "types/jest/jest-tests.d.ts" }
|
||||
{ status: "D", file: "types/jest/jest-tests.d.ts" },
|
||||
];
|
||||
|
||||
testo({
|
||||
@@ -49,7 +49,7 @@ testo({
|
||||
{ status: "A", file: "oooooooooooops.txt" },
|
||||
{ status: "M", file: "notNeededPackages.json" },
|
||||
{ status: "D", file: "types/jest/index.d.ts" },
|
||||
{ status: "D", file: "types/jest/jest-tests.d.ts" }
|
||||
{ status: "D", file: "types/jest/jest-tests.d.ts" },
|
||||
])
|
||||
).toEqual(jestNotNeeded);
|
||||
},
|
||||
@@ -60,7 +60,7 @@ testo({
|
||||
[{ status: "D", file: "types/ember__object/index.d.ts" }]
|
||||
)
|
||||
).toEqual([new NotNeededPackage("ember__object", "@ember/object", "1.0.0")]);
|
||||
}
|
||||
},
|
||||
// TODO: Test npm info (and with scoped names)
|
||||
// TODO: Test with dependents, etc etc
|
||||
});
|
||||
@@ -69,7 +69,7 @@ const empty: NpmInfo = {
|
||||
homepage: "",
|
||||
distTags: new Map(),
|
||||
versions: new Map(),
|
||||
time: new Map()
|
||||
time: new Map(),
|
||||
};
|
||||
testo({
|
||||
missingSource() {
|
||||
@@ -93,7 +93,7 @@ testo({
|
||||
homepage: "jest.com",
|
||||
distTags: new Map([["latest", "100.0.0"]]),
|
||||
versions: new Map(),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
});
|
||||
}).toThrow(`The specified version 100.0.0 of jest must be newer than the version
|
||||
it is supposed to replace, 100.0.0 of @types/jest.`);
|
||||
@@ -104,7 +104,7 @@ it is supposed to replace, 100.0.0 of @types/jest.`);
|
||||
homepage: "jest.com",
|
||||
distTags: new Map([["latest", "999.0.0"]]),
|
||||
versions: new Map(),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
});
|
||||
}).toThrow(`The specified version 100.0.0 of jest must be newer than the version
|
||||
it is supposed to replace, 999.0.0 of @types/jest.`);
|
||||
@@ -115,7 +115,7 @@ it is supposed to replace, 999.0.0 of @types/jest.`);
|
||||
homepage: "jest.com",
|
||||
distTags: new Map([["latest", "4.0.0"]]),
|
||||
versions: new Map(),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
});
|
||||
}).toThrow("The specified version 100.0.0 of jest is not on npm.");
|
||||
},
|
||||
@@ -127,13 +127,13 @@ it is supposed to replace, 999.0.0 of @types/jest.`);
|
||||
homepage: "jest.com",
|
||||
distTags: new Map(),
|
||||
versions: new Map([["50.0.0", {}]]),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
},
|
||||
{
|
||||
homepage: "jest.com",
|
||||
distTags: new Map([["latest", "4.0.0"]]),
|
||||
versions: new Map(),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
}
|
||||
)
|
||||
).toThrow("The specified version 100.0.0 of jest is not on npm.");
|
||||
@@ -145,14 +145,14 @@ it is supposed to replace, 999.0.0 of @types/jest.`);
|
||||
homepage: "jest.com",
|
||||
distTags: new Map(),
|
||||
versions: new Map([["100.0.0", {}]]),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
},
|
||||
{
|
||||
homepage: "jest.com",
|
||||
distTags: new Map([["latest", "4.0.0"]]),
|
||||
versions: new Map(),
|
||||
time: new Map([["modified", ""]])
|
||||
time: new Map([["modified", ""]]),
|
||||
}
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ testo({
|
||||
"quaternary.d.ts",
|
||||
"tertiary.d.ts",
|
||||
"commonjs.d.ts",
|
||||
"v1.d.ts"
|
||||
"v1.d.ts",
|
||||
]);
|
||||
expect(Array.from(tests.keys())).toEqual(["boring-tests.ts"]);
|
||||
},
|
||||
@@ -38,7 +38,7 @@ testo({
|
||||
"quaternary.d.ts",
|
||||
"tertiary.d.ts",
|
||||
"commonjs.d.ts",
|
||||
"v1.d.ts"
|
||||
"v1.d.ts",
|
||||
]);
|
||||
expect(Array.from(tests.keys())).toEqual(["boring-tests.ts"]);
|
||||
},
|
||||
@@ -82,10 +82,7 @@ testo({
|
||||
"untested.d.ts",
|
||||
ts.createSourceFile(
|
||||
"untested.d.ts",
|
||||
fs
|
||||
.subDir("types")
|
||||
.subDir("boring")
|
||||
.readFile("untested.d.ts"),
|
||||
fs.subDir("types").subDir("boring").readFile("untested.d.ts"),
|
||||
ts.ScriptTarget.Latest,
|
||||
false
|
||||
)
|
||||
@@ -184,5 +181,5 @@ testo({
|
||||
const i = getModuleInfo("boring", types);
|
||||
const d = getTestDependencies("boring", types, tests.keys(), i.dependencies, fs.subDir("types").subDir("boring"));
|
||||
expect(d).toEqual(new Set(["super-big-fun-hus"]));
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
getMangledNameForScopedPackage,
|
||||
NotNeededPackage,
|
||||
getLicenseFromPackageJson,
|
||||
getDependencyFromFile
|
||||
getDependencyFromFile,
|
||||
} from "../src/packages";
|
||||
import { parseDefinitions } from "../src/parse-definitions";
|
||||
import { quietLoggerWithErrors } from "@definitelytyped/utils";
|
||||
@@ -28,7 +28,7 @@ describe(AllPackages, () => {
|
||||
it("applies path mappings to test dependencies", () => {
|
||||
const pkg = allPackages.tryGetLatestVersion("has-older-test-dependency")!;
|
||||
expect(Array.from(allPackages.allDependencyTypings(pkg), ({ id }) => id)).toEqual([
|
||||
{ name: "jquery", version: { major: 1, minor: 0 } }
|
||||
{ name: "jquery", version: { major: 1, minor: 0 } },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -45,13 +45,13 @@ describe(AllPackages, () => {
|
||||
expect(
|
||||
allPackages.hasTypingFor({
|
||||
name: "jquery",
|
||||
version: "*"
|
||||
version: "*",
|
||||
})
|
||||
).toBe(true);
|
||||
expect(
|
||||
allPackages.hasTypingFor({
|
||||
name: "nonExistent",
|
||||
version: "*"
|
||||
version: "*",
|
||||
})
|
||||
).toBe(false);
|
||||
});
|
||||
@@ -70,7 +70,7 @@ describe(TypingsVersions, () => {
|
||||
});
|
||||
|
||||
it("sorts the data from latest to oldest version", () => {
|
||||
expect(Array.from(versions.getAll()).map(v => v.major)).toEqual([3, 2, 2, 1]);
|
||||
expect(Array.from(versions.getAll()).map((v) => v.major)).toEqual([3, 2, 2, 1]);
|
||||
});
|
||||
|
||||
it("returns the latest version", () => {
|
||||
@@ -109,7 +109,7 @@ describe(TypingsData, () => {
|
||||
const versions = createTypingsVersionRaw(
|
||||
"known",
|
||||
{
|
||||
"dependency-1": "*"
|
||||
"dependency-1": "*",
|
||||
},
|
||||
[],
|
||||
{}
|
||||
@@ -124,8 +124,8 @@ describe(TypingsData, () => {
|
||||
{
|
||||
name: "Bender",
|
||||
url: "futurama.com",
|
||||
githubUsername: "bender"
|
||||
}
|
||||
githubUsername: "bender",
|
||||
},
|
||||
]);
|
||||
expect(data.major).toBe(1);
|
||||
expect(data.minor).toBe(0);
|
||||
@@ -140,14 +140,14 @@ describe(TypingsData, () => {
|
||||
expect(data.globals).toEqual([]);
|
||||
expect(data.pathMappings).toEqual({});
|
||||
expect(data.dependencies).toEqual({
|
||||
"dependency-1": "*"
|
||||
"dependency-1": "*",
|
||||
});
|
||||
expect(data.id).toEqual({
|
||||
name: "known",
|
||||
version: {
|
||||
major: 1,
|
||||
minor: 0
|
||||
}
|
||||
minor: 0,
|
||||
},
|
||||
});
|
||||
expect(data.isNotNeeded()).toBe(false);
|
||||
});
|
||||
@@ -222,7 +222,7 @@ describe(NotNeededPackage, () => {
|
||||
expect(data.version).toEqual({
|
||||
major: 1,
|
||||
minor: 0,
|
||||
patch: 0
|
||||
patch: 0,
|
||||
});
|
||||
expect(data.major).toBe(1);
|
||||
expect(data.minor).toBe(0);
|
||||
@@ -281,22 +281,22 @@ describe(getDependencyFromFile, () => {
|
||||
name: "a",
|
||||
version: {
|
||||
major: 3,
|
||||
minor: 5
|
||||
}
|
||||
minor: 5,
|
||||
},
|
||||
});
|
||||
expect(getDependencyFromFile("types/a/v3")).toEqual({
|
||||
name: "a",
|
||||
version: {
|
||||
major: 3,
|
||||
minor: undefined
|
||||
}
|
||||
minor: undefined,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("returns undefined for unversioned subpaths", () => {
|
||||
expect(getDependencyFromFile("types/a/vnotaversion")).toEqual({
|
||||
name: "a",
|
||||
version: "*"
|
||||
version: "*",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -26,5 +26,5 @@ testo({
|
||||
expect(j!.fullNpmName).toContain("types");
|
||||
expect(j!.fullNpmName).toContain("jquery");
|
||||
expect(defs.allPackages().length).toEqual(defs.allTypings().length + defs.allNotNeeded().length);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -30,7 +30,7 @@ export function createTypingsVersionRaw(
|
||||
contentHash: "11111111111111",
|
||||
projectName: "zombo.com",
|
||||
globals: [],
|
||||
declaredModules: []
|
||||
}
|
||||
declaredModules: [],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
checkSource,
|
||||
findDtsName,
|
||||
CheckOptions,
|
||||
parseMode
|
||||
parseMode,
|
||||
} from "./index";
|
||||
|
||||
const sourcesDir = "sources";
|
||||
@@ -102,7 +102,7 @@ function getUnpopularNpmPackages(count: number, dtPath: string): string[] {
|
||||
function getDtNpmPackages(dtPath: string): string[] {
|
||||
const dtPackages = fs.readdirSync(getDtTypesPath(dtPath));
|
||||
const isNpmJson = getAllIsNpm(dtPath);
|
||||
return dtPackages.filter(pkg => isNpmPackage(pkg, /* header */ undefined, isNpmJson));
|
||||
return dtPackages.filter((pkg) => isNpmPackage(pkg, /* header */ undefined, isNpmJson));
|
||||
}
|
||||
|
||||
function getNonNpm(args: { dtPath: string }): void {
|
||||
@@ -122,7 +122,7 @@ function getNonNpm(args: { dtPath: string }): void {
|
||||
nonNpm.push(item);
|
||||
}
|
||||
}
|
||||
console.log(`List of non-npm packages on DT:\n${nonNpm.map(name => `DT name: ${name}\n`).join("")}`);
|
||||
console.log(`List of non-npm packages on DT:\n${nonNpm.map((name) => `DT name: ${name}\n`).join("")}`);
|
||||
}
|
||||
|
||||
interface CommonArgs {
|
||||
@@ -147,7 +147,7 @@ function checkUnpopular(args: { count: number } & CommonArgs): void {
|
||||
}
|
||||
|
||||
function checkPackages(args: { packages: string[] } & CommonArgs): void {
|
||||
const results = args.packages.map(pkg => doCheck({ package: pkg, ...args }));
|
||||
const results = args.packages.map((pkg) => doCheck({ package: pkg, ...args }));
|
||||
printResults(results, args.json);
|
||||
}
|
||||
|
||||
@@ -196,7 +196,7 @@ function getEnabledErrors(errorNames: string[]): Map<ExportErrorKind, boolean> {
|
||||
}
|
||||
errors.push(error);
|
||||
}
|
||||
return new Map(errors.map(err => [err, true]));
|
||||
return new Map(errors.map((err) => [err, true]));
|
||||
}
|
||||
|
||||
function checkFile(args: { jsFile: string; dtsFile: string; debug: boolean }): void {
|
||||
@@ -261,29 +261,29 @@ function main() {
|
||||
dtPath: {
|
||||
type: "string",
|
||||
default: "../DefinitelyTyped",
|
||||
describe: "Path of DT repository cloned locally."
|
||||
describe: "Path of DT repository cloned locally.",
|
||||
},
|
||||
mode: {
|
||||
type: "string",
|
||||
required: true,
|
||||
choices: [Mode.NameOnly, Mode.Code],
|
||||
describe: "Mode that defines which group of checks will be made."
|
||||
describe: "Mode that defines which group of checks will be made.",
|
||||
},
|
||||
enableError: {
|
||||
type: "array",
|
||||
string: true,
|
||||
describe: "Enable checking for a specific export error."
|
||||
describe: "Enable checking for a specific export error.",
|
||||
},
|
||||
debug: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Turn debug logging on."
|
||||
describe: "Turn debug logging on.",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Format output result as json."
|
||||
}
|
||||
describe: "Format output result as json.",
|
||||
},
|
||||
},
|
||||
checkAll
|
||||
)
|
||||
@@ -295,34 +295,34 @@ function main() {
|
||||
alias: "c",
|
||||
type: "number",
|
||||
required: true,
|
||||
describe: "Number of packages to be checked."
|
||||
describe: "Number of packages to be checked.",
|
||||
},
|
||||
dtPath: {
|
||||
type: "string",
|
||||
default: "../DefinitelyTyped",
|
||||
describe: "Path of DT repository cloned locally."
|
||||
describe: "Path of DT repository cloned locally.",
|
||||
},
|
||||
mode: {
|
||||
type: "string",
|
||||
required: true,
|
||||
choices: [Mode.NameOnly, Mode.Code],
|
||||
describe: "Mode that defines which group of checks will be made."
|
||||
describe: "Mode that defines which group of checks will be made.",
|
||||
},
|
||||
enableError: {
|
||||
type: "array",
|
||||
string: true,
|
||||
describe: "Enable checking for a specific export error."
|
||||
describe: "Enable checking for a specific export error.",
|
||||
},
|
||||
debug: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Turn debug logging on."
|
||||
describe: "Turn debug logging on.",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Format output result as json."
|
||||
}
|
||||
describe: "Format output result as json.",
|
||||
},
|
||||
},
|
||||
checkPopular
|
||||
)
|
||||
@@ -334,34 +334,34 @@ function main() {
|
||||
alias: "c",
|
||||
type: "number",
|
||||
required: true,
|
||||
describe: "Number of packages to be checked."
|
||||
describe: "Number of packages to be checked.",
|
||||
},
|
||||
dtPath: {
|
||||
type: "string",
|
||||
default: "../DefinitelyTyped",
|
||||
describe: "Path of DT repository cloned locally."
|
||||
describe: "Path of DT repository cloned locally.",
|
||||
},
|
||||
mode: {
|
||||
type: "string",
|
||||
required: true,
|
||||
choices: [Mode.NameOnly, Mode.Code],
|
||||
describe: "Mode that defines which group of checks will be made."
|
||||
describe: "Mode that defines which group of checks will be made.",
|
||||
},
|
||||
enableError: {
|
||||
type: "array",
|
||||
string: true,
|
||||
describe: "Enable checking for a specific export error."
|
||||
describe: "Enable checking for a specific export error.",
|
||||
},
|
||||
debug: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Turn debug logging on."
|
||||
describe: "Turn debug logging on.",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Format output result as json."
|
||||
}
|
||||
describe: "Format output result as json.",
|
||||
},
|
||||
},
|
||||
checkUnpopular
|
||||
)
|
||||
@@ -373,34 +373,34 @@ function main() {
|
||||
alias: "p",
|
||||
type: "string",
|
||||
required: true,
|
||||
describe: "DT name of a package."
|
||||
describe: "DT name of a package.",
|
||||
},
|
||||
dtPath: {
|
||||
type: "string",
|
||||
default: "../DefinitelyTyped",
|
||||
describe: "Path of DT repository cloned locally."
|
||||
describe: "Path of DT repository cloned locally.",
|
||||
},
|
||||
mode: {
|
||||
type: "string",
|
||||
required: true,
|
||||
choices: [Mode.NameOnly, Mode.Code],
|
||||
describe: "Mode that defines which group of checks will be made."
|
||||
describe: "Mode that defines which group of checks will be made.",
|
||||
},
|
||||
enableError: {
|
||||
type: "array",
|
||||
string: true,
|
||||
describe: "Enable checking for a specific export error."
|
||||
describe: "Enable checking for a specific export error.",
|
||||
},
|
||||
debug: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Turn debug logging on."
|
||||
describe: "Turn debug logging on.",
|
||||
},
|
||||
json: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Format output result as json."
|
||||
}
|
||||
describe: "Format output result as json.",
|
||||
},
|
||||
},
|
||||
checkPackage
|
||||
)
|
||||
@@ -412,19 +412,19 @@ function main() {
|
||||
alias: "j",
|
||||
type: "string",
|
||||
required: true,
|
||||
describe: "Path of JavaScript file."
|
||||
describe: "Path of JavaScript file.",
|
||||
},
|
||||
dtsFile: {
|
||||
alias: "d",
|
||||
type: "string",
|
||||
required: true,
|
||||
describe: "Path of declaration file."
|
||||
describe: "Path of declaration file.",
|
||||
},
|
||||
debug: {
|
||||
type: "boolean",
|
||||
default: false,
|
||||
describe: "Turn debug logging on."
|
||||
}
|
||||
describe: "Turn debug logging on.",
|
||||
},
|
||||
},
|
||||
checkFile
|
||||
)
|
||||
@@ -435,8 +435,8 @@ function main() {
|
||||
dtPath: {
|
||||
type: "string",
|
||||
default: "../DefinitelyTyped",
|
||||
describe: "Path of DT repository cloned locally."
|
||||
}
|
||||
describe: "Path of DT repository cloned locally.",
|
||||
},
|
||||
},
|
||||
getNonNpm
|
||||
)
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
dtsCritic,
|
||||
checkSource,
|
||||
ErrorKind,
|
||||
ExportErrorKind
|
||||
ExportErrorKind,
|
||||
} from "./index";
|
||||
|
||||
function suite(description: string, tests: { [s: string]: () => void }) {
|
||||
@@ -33,7 +33,7 @@ suite("findDtsName", {
|
||||
},
|
||||
emptyDirectory() {
|
||||
expect(findDtsName("")).toBe("DefinitelyTyped-tools");
|
||||
}
|
||||
},
|
||||
});
|
||||
suite("getNpmInfo", {
|
||||
nonNpm() {
|
||||
@@ -43,9 +43,9 @@ suite("getNpmInfo", {
|
||||
expect(getNpmInfo("typescript")).toEqual({
|
||||
isNpm: true,
|
||||
versions: expect.arrayContaining(["3.7.5"]),
|
||||
tags: expect.objectContaining({ latest: expect.stringContaining("") })
|
||||
tags: expect.objectContaining({ latest: expect.stringContaining("") }),
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
suite("dtToNpmName", {
|
||||
nonScoped() {
|
||||
@@ -53,7 +53,7 @@ suite("dtToNpmName", {
|
||||
},
|
||||
scoped() {
|
||||
expect(dtToNpmName("babel__core")).toBe("@babel/core");
|
||||
}
|
||||
},
|
||||
});
|
||||
suite("parseExportErrorKind", {
|
||||
existent() {
|
||||
@@ -64,7 +64,7 @@ suite("parseExportErrorKind", {
|
||||
},
|
||||
nonexistent() {
|
||||
expect(parseExportErrorKind("FakeError")).toBe(undefined);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
const allErrors: Map<ExportErrorKind, true> = new Map([
|
||||
@@ -73,7 +73,7 @@ const allErrors: Map<ExportErrorKind, true> = new Map([
|
||||
[ErrorKind.JsSignatureNotInDts, true],
|
||||
[ErrorKind.DtsSignatureNotInJs, true],
|
||||
[ErrorKind.DtsPropertyNotInJs, true],
|
||||
[ErrorKind.JsPropertyNotInDts, true]
|
||||
[ErrorKind.JsPropertyNotInDts, true],
|
||||
]);
|
||||
|
||||
function testsource(filename: string) {
|
||||
@@ -100,8 +100,8 @@ suite("checkSource", {
|
||||
{
|
||||
kind: ErrorKind.JsPropertyNotInDts,
|
||||
message: `The declaration doesn't match the JavaScript module 'missingJsProperty'. Reason:
|
||||
The JavaScript module exports a property named 'foo', which is missing from the declaration module.`
|
||||
}
|
||||
The JavaScript module exports a property named 'foo', which is missing from the declaration module.`,
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -133,9 +133,9 @@ The JavaScript module exports a property named 'foo', which is missing from the
|
||||
The declaration module exports a property named 'foo', which is missing from the JavaScript module.`,
|
||||
position: {
|
||||
start: 65,
|
||||
length: 11
|
||||
}
|
||||
}
|
||||
length: 11,
|
||||
},
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -159,9 +159,9 @@ The most common way to resolve this error is to use 'export =' syntax instead of
|
||||
To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require.`,
|
||||
position: {
|
||||
start: 0,
|
||||
length: 32
|
||||
}
|
||||
}
|
||||
length: 32,
|
||||
},
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -179,8 +179,8 @@ To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/h
|
||||
{
|
||||
kind: ErrorKind.JsSignatureNotInDts,
|
||||
message: `The declaration doesn't match the JavaScript module 'missingJsSignatureExportEquals'. Reason:
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.`
|
||||
}
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.`,
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -201,8 +201,8 @@ The JavaScript module can be called or constructed, but the declaration module c
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.
|
||||
|
||||
The most common way to resolve this error is to use 'export =' syntax.
|
||||
To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require.`
|
||||
}
|
||||
To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require.`,
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -220,8 +220,8 @@ To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/h
|
||||
{
|
||||
kind: ErrorKind.DtsSignatureNotInJs,
|
||||
message: `The declaration doesn't match the JavaScript module 'missingDtsSignature'. Reason:
|
||||
The declaration module can be called or constructed, but the JavaScript module cannot.`
|
||||
}
|
||||
The declaration module can be called or constructed, but the JavaScript module cannot.`,
|
||||
},
|
||||
])
|
||||
);
|
||||
},
|
||||
@@ -241,11 +241,11 @@ The declaration module can be called or constructed, but the JavaScript module c
|
||||
message: `The declaration doesn't match the JavaScript module 'missingExportEquals'. Reason:
|
||||
The declaration should use 'export =' syntax because the JavaScript source uses 'module.exports =' syntax and 'module.exports' can be called or constructed.
|
||||
|
||||
To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require.`
|
||||
}
|
||||
To learn more about 'export =' syntax, see https://www.typescriptlang.org/docs/handbook/modules.html#export--and-import--require.`,
|
||||
},
|
||||
])
|
||||
);
|
||||
}
|
||||
},
|
||||
});
|
||||
suite("dtsCritic", {
|
||||
noErrors() {
|
||||
@@ -263,8 +263,8 @@ To resolve this error, either:
|
||||
|
||||
// Type definitions for non-npm package wenceslas-browser
|
||||
|
||||
Add -browser to the end of your name to make sure it doesn't conflict with existing npm packages.`
|
||||
}
|
||||
Add -browser to the end of your name to make sure it doesn't conflict with existing npm packages.`,
|
||||
},
|
||||
]);
|
||||
},
|
||||
noMatchingNpmVersion() {
|
||||
@@ -272,8 +272,8 @@ Add -browser to the end of your name to make sure it doesn't conflict with exist
|
||||
{
|
||||
kind: ErrorKind.NoMatchingNpmVersion,
|
||||
message: expect.stringContaining(`The types for 'typescript' must match a version that exists on npm.
|
||||
You should copy the major and minor version from the package on npm.`)
|
||||
}
|
||||
You should copy the major and minor version from the package on npm.`),
|
||||
},
|
||||
]);
|
||||
},
|
||||
nonNpmHasMatchingPackage() {
|
||||
@@ -284,8 +284,8 @@ You should copy the major and minor version from the package on npm.`)
|
||||
Try adding -browser to the end of the name to get
|
||||
|
||||
tslib-browser
|
||||
`
|
||||
}
|
||||
`,
|
||||
},
|
||||
]);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
@@ -28,14 +28,14 @@ export enum ErrorKind {
|
||||
/** JavaScript module has signatures, but declaration module does not. */
|
||||
JsSignatureNotInDts = "JsSignatureNotInDts",
|
||||
/** Declaration module has signatures, but JavaScript module does not. */
|
||||
DtsSignatureNotInJs = "DtsSignatureNotInJs"
|
||||
DtsSignatureNotInJs = "DtsSignatureNotInJs",
|
||||
}
|
||||
|
||||
export enum Mode {
|
||||
/** Checks based only on the package name and on the declaration's DefinitelyTyped header. */
|
||||
NameOnly = "name-only",
|
||||
/** Checks based on the source JavaScript code, in addition to the checks performed in name-only mode. */
|
||||
Code = "code"
|
||||
Code = "code",
|
||||
}
|
||||
|
||||
export function parseMode(mode: string): Mode | undefined {
|
||||
@@ -150,23 +150,23 @@ function main() {
|
||||
)
|
||||
.option("dts", {
|
||||
describe: "Path of declaration file to be critiqued.",
|
||||
type: "string"
|
||||
type: "string",
|
||||
})
|
||||
.demandOption("dts", "Please provide a path to a d.ts file for me to critique.")
|
||||
.option("js", {
|
||||
describe: "Path of JavaScript file to be used as source.",
|
||||
type: "string"
|
||||
type: "string",
|
||||
})
|
||||
.option("mode", {
|
||||
describe: "Mode defines what checks will be performed.",
|
||||
type: "string",
|
||||
default: Mode.NameOnly,
|
||||
choices: [Mode.NameOnly, Mode.Code]
|
||||
choices: [Mode.NameOnly, Mode.Code],
|
||||
})
|
||||
.option("debug", {
|
||||
describe: "Turn debug logging on.",
|
||||
type: "boolean",
|
||||
default: false
|
||||
default: false,
|
||||
})
|
||||
.help().argv;
|
||||
|
||||
@@ -193,7 +193,7 @@ const npmNotFound = "E404";
|
||||
export function getNpmInfo(name: string): NpmInfo {
|
||||
const npmName = dtToNpmName(name);
|
||||
const infoResult = cp.spawnSync("npm", ["info", npmName, "--json", "--silent", "versions", "dist-tags"], {
|
||||
encoding: "utf8"
|
||||
encoding: "utf8",
|
||||
});
|
||||
const info = JSON.parse(infoResult.stdout || infoResult.stderr);
|
||||
if (info.error !== undefined) {
|
||||
@@ -209,7 +209,7 @@ export function getNpmInfo(name: string): NpmInfo {
|
||||
return {
|
||||
isNpm: true,
|
||||
versions: info.versions as string[],
|
||||
tags: info["dist-tags"] as { [tag: string]: string | undefined }
|
||||
tags: info["dist-tags"] as { [tag: string]: string | undefined },
|
||||
};
|
||||
}
|
||||
|
||||
@@ -224,7 +224,7 @@ function checkNonNpm(name: string, npmInfo: NpmInfo): NonNpmError | undefined {
|
||||
Try adding -browser to the end of the name to get
|
||||
|
||||
${name}-browser
|
||||
`
|
||||
`,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
@@ -246,7 +246,7 @@ To resolve this error, either:
|
||||
|
||||
// Type definitions for non-npm package ${name}-browser
|
||||
|
||||
Add -browser to the end of your name to make sure it doesn't conflict with existing npm packages.`
|
||||
Add -browser to the end of your name to make sure it doesn't conflict with existing npm packages.`,
|
||||
};
|
||||
}
|
||||
const target = getHeaderVersion(header);
|
||||
@@ -264,7 +264,7 @@ You should copy the major and minor version from the package on npm.
|
||||
To resolve this error, change the version in the header, ${headerstring},
|
||||
to match one on npm: ${verstring}.
|
||||
|
||||
For example, if you're trying to match the latest version, use ${lateststring}.`
|
||||
For example, if you're trying to match the latest version, use ${lateststring}.`,
|
||||
};
|
||||
}
|
||||
return npmVersion;
|
||||
@@ -358,7 +358,7 @@ export function checkSource(
|
||||
console.log(formatDebug(name, diagnostics));
|
||||
}
|
||||
|
||||
return diagnostics.errors.filter(err => enabledErrors.get(err.kind) ?? defaultErrors.includes(err.kind));
|
||||
return diagnostics.errors.filter((err) => enabledErrors.get(err.kind) ?? defaultErrors.includes(err.kind));
|
||||
}
|
||||
|
||||
function formatDebug(name: string, diagnostics: ExportsDiagnostics): string {
|
||||
@@ -403,13 +403,13 @@ function formatType(type: ts.Type): string {
|
||||
const properties = type.getProperties();
|
||||
if (properties.length > 0) {
|
||||
lines.push("Type's properties:");
|
||||
lines.push(...properties.map(p => p.getName()));
|
||||
lines.push(...properties.map((p) => p.getName()));
|
||||
}
|
||||
|
||||
const signatures = type.getConstructSignatures().concat(type.getCallSignatures());
|
||||
if (signatures.length > 0) {
|
||||
lines.push("Type's signatures:");
|
||||
lines.push(...signatures.map(s => checker.signatureToString(s)));
|
||||
lines.push(...signatures.map((s) => checker.signatureToString(s)));
|
||||
}
|
||||
lines.push(`Type string: ${checker.typeToString(type)}`);
|
||||
return lines.join("\n");
|
||||
@@ -422,7 +422,7 @@ const exportEqualsLink = "https://www.typescriptlang.org/docs/handbook/modules.h
|
||||
*/
|
||||
function checkExports(name: string, dtsPath: string, sourcePath: string): ExportsDiagnostics {
|
||||
const tscOpts = {
|
||||
allowJs: true
|
||||
allowJs: true,
|
||||
};
|
||||
|
||||
const jsProgram = ts.createProgram([sourcePath], tscOpts);
|
||||
@@ -448,7 +448,7 @@ function checkExports(name: string, dtsPath: string, sourcePath: string): Export
|
||||
message: `The declaration doesn't match the JavaScript module '${name}'. Reason:
|
||||
The declaration should use 'export =' syntax because the JavaScript source uses 'module.exports =' syntax and ${sourceDiagnostics.exportEquals.result.reason}.
|
||||
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`,
|
||||
} as const;
|
||||
errors.push(error);
|
||||
}
|
||||
@@ -472,7 +472,7 @@ To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
The declaration specifies 'export default' but the JavaScript source does not mention 'default' anywhere.
|
||||
|
||||
The most common way to resolve this error is to use 'export =' syntax instead of 'export default'.
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -481,7 +481,7 @@ To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
jsExportType: sourceDiagnostics.exportType,
|
||||
dtsExportKind: dtsDiagnostics.exportKind,
|
||||
dtsExportType: dtsDiagnostics.exportType,
|
||||
errors
|
||||
errors,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -616,12 +616,12 @@ function inspectDts(dtsPath: string, name: string): DtsExportDiagnostics {
|
||||
function createDtProgram(dtsPath: string): ts.Program {
|
||||
const dtsDir = path.dirname(dtsPath);
|
||||
const configPath = path.join(dtsDir, "tsconfig.json");
|
||||
const { config } = ts.readConfigFile(configPath, p => fs.readFileSync(p, { encoding: "utf8" }));
|
||||
const { config } = ts.readConfigFile(configPath, (p) => fs.readFileSync(p, { encoding: "utf8" }));
|
||||
const parseConfigHost: ts.ParseConfigHost = {
|
||||
fileExists: fs.existsSync,
|
||||
readDirectory: ts.sys.readDirectory,
|
||||
readFile: file => fs.readFileSync(file, { encoding: "utf8" }),
|
||||
useCaseSensitiveFileNames: true
|
||||
readFile: (file) => fs.readFileSync(file, { encoding: "utf8" }),
|
||||
useCaseSensitiveFileNames: true,
|
||||
};
|
||||
const parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, path.resolve(dtsDir));
|
||||
const host = ts.createCompilerHost(parsed.options, true);
|
||||
@@ -633,9 +633,9 @@ function getDtsModuleSymbol(
|
||||
checker: ts.TypeChecker,
|
||||
name: string
|
||||
): InferenceResult<ts.Symbol> {
|
||||
if (matches(sourceFile, node => ts.isModuleDeclaration(node))) {
|
||||
if (matches(sourceFile, (node) => ts.isModuleDeclaration(node))) {
|
||||
const npmName = dtToNpmName(name);
|
||||
const moduleSymbol = checker.getAmbientModules().find(symbol => symbol.getName() === `"${npmName}"`);
|
||||
const moduleSymbol = checker.getAmbientModules().find((symbol) => symbol.getName() === `"${npmName}"`);
|
||||
if (moduleSymbol) {
|
||||
return inferenceSuccess(moduleSymbol);
|
||||
}
|
||||
@@ -699,7 +699,7 @@ function getDtsDefaultExport(sourceFile: ts.SourceFile, moduleType: InferenceRes
|
||||
if (exportDefault > -1 && src.indexOf("export =") === -1 && !/declare module ['"]/.test(src)) {
|
||||
return {
|
||||
start: exportDefault,
|
||||
length: "export default".length
|
||||
length: "export default".length,
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
@@ -709,7 +709,7 @@ function getDtsDefaultExport(sourceFile: ts.SourceFile, moduleType: InferenceRes
|
||||
if (exportDefault?.declarations) {
|
||||
return {
|
||||
start: exportDefault.declarations[0].getStart(),
|
||||
length: exportDefault.declarations[0].getWidth()
|
||||
length: exportDefault.declarations[0].getWidth(),
|
||||
};
|
||||
}
|
||||
return undefined;
|
||||
@@ -757,7 +757,7 @@ function exportTypesCompatibility(
|
||||
errors.push({
|
||||
kind: ErrorKind.JsSignatureNotInDts,
|
||||
message: `The declaration doesn't match the JavaScript module '${name}'. Reason:
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.`
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.`,
|
||||
});
|
||||
} else {
|
||||
errors.push({
|
||||
@@ -766,7 +766,7 @@ The JavaScript module can be called or constructed, but the declaration module c
|
||||
The JavaScript module can be called or constructed, but the declaration module cannot.
|
||||
|
||||
The most common way to resolve this error is to use 'export =' syntax.
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
To learn more about 'export =' syntax, see ${exportEqualsLink}.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -775,7 +775,7 @@ To learn more about 'export =' syntax, see ${exportEqualsLink}.`
|
||||
errors.push({
|
||||
kind: ErrorKind.DtsSignatureNotInJs,
|
||||
message: `The declaration doesn't match the JavaScript module '${name}'. Reason:
|
||||
The declaration module can be called or constructed, but the JavaScript module cannot.`
|
||||
The declaration module can be called or constructed, but the JavaScript module cannot.`,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -784,11 +784,11 @@ The declaration module can be called or constructed, but the JavaScript module c
|
||||
for (const sourceProperty of sourceProperties) {
|
||||
// TODO: check `prototype` properties.
|
||||
if (ignoreProperty(sourceProperty)) continue;
|
||||
if (!dtsProperties.find(s => s.getName() === sourceProperty.getName())) {
|
||||
if (!dtsProperties.find((s) => s.getName() === sourceProperty.getName())) {
|
||||
errors.push({
|
||||
kind: ErrorKind.JsPropertyNotInDts,
|
||||
message: `The declaration doesn't match the JavaScript module '${name}'. Reason:
|
||||
The JavaScript module exports a property named '${sourceProperty.getName()}', which is missing from the declaration module.`
|
||||
The JavaScript module exports a property named '${sourceProperty.getName()}', which is missing from the declaration module.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -796,18 +796,18 @@ The JavaScript module exports a property named '${sourceProperty.getName()}', wh
|
||||
for (const dtsProperty of dtsProperties) {
|
||||
// TODO: check `prototype` properties.
|
||||
if (ignoreProperty(dtsProperty)) continue;
|
||||
if (!sourceProperties.find(s => s.getName() === dtsProperty.getName())) {
|
||||
if (!sourceProperties.find((s) => s.getName() === dtsProperty.getName())) {
|
||||
const error: MissingExport = {
|
||||
kind: ErrorKind.DtsPropertyNotInJs,
|
||||
message: `The declaration doesn't match the JavaScript module '${name}'. Reason:
|
||||
The declaration module exports a property named '${dtsProperty.getName()}', which is missing from the JavaScript module.`
|
||||
The declaration module exports a property named '${dtsProperty.getName()}', which is missing from the JavaScript module.`,
|
||||
};
|
||||
const declaration =
|
||||
dtsProperty.declarations && dtsProperty.declarations.length > 0 ? dtsProperty.declarations[0] : undefined;
|
||||
if (declaration) {
|
||||
error.position = {
|
||||
start: declaration.getStart(),
|
||||
length: declaration.getWidth()
|
||||
length: declaration.getWidth(),
|
||||
};
|
||||
}
|
||||
errors.push(error);
|
||||
@@ -831,7 +831,7 @@ function isExportConstruct(node: ts.Node): boolean {
|
||||
|
||||
function hasExportModifier(node: ts.Node): boolean {
|
||||
if (node.modifiers) {
|
||||
return node.modifiers.some(modifier => modifier.kind === ts.SyntaxKind.ExportKeyword);
|
||||
return node.modifiers.some((modifier) => modifier.kind === ts.SyntaxKind.ExportKeyword);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -952,7 +952,7 @@ interface JsExportsInfo {
|
||||
|
||||
enum JsExportKind {
|
||||
CommonJs = "CommonJs",
|
||||
ES6 = "ES6"
|
||||
ES6 = "ES6",
|
||||
}
|
||||
|
||||
interface ExportEqualsDiagnostics {
|
||||
@@ -962,12 +962,12 @@ interface ExportEqualsDiagnostics {
|
||||
|
||||
enum ExportEqualsJudgement {
|
||||
Required = "Required",
|
||||
NotRequired = "Not required"
|
||||
NotRequired = "Not required",
|
||||
}
|
||||
|
||||
enum DtsExportKind {
|
||||
ExportEquals = "export =",
|
||||
ES6Like = "ES6-like"
|
||||
ES6Like = "ES6-like",
|
||||
}
|
||||
|
||||
interface DtsExportDiagnostics {
|
||||
@@ -992,7 +992,7 @@ type InferenceResult<T> = InferenceError | InferenceSuccess<T>;
|
||||
|
||||
enum InferenceResultKind {
|
||||
Error,
|
||||
Success
|
||||
Success,
|
||||
}
|
||||
|
||||
interface InferenceError {
|
||||
|
||||
@@ -1 +1 @@
|
||||
export default function(): void;
|
||||
export default function (): void;
|
||||
|
||||
@@ -1 +1 @@
|
||||
export default function(): void;
|
||||
export default function (): void;
|
||||
|
||||
@@ -14,64 +14,64 @@ if (!module.parent) {
|
||||
clone: {
|
||||
group: "DefinitelyTyped acquisition",
|
||||
description: "Clone DefinitelyTyped before running. Can be used as a boolean flag or set to the SHA to clone.",
|
||||
conflicts: "path"
|
||||
conflicts: "path",
|
||||
},
|
||||
path: {
|
||||
group: "DefinitelyTyped acquisition",
|
||||
description: "Path to local DefinitelyTyped clone.",
|
||||
conflicts: "clone",
|
||||
type: "string"
|
||||
type: "string",
|
||||
},
|
||||
selection: {
|
||||
group: "Package selection",
|
||||
description: "Which packages to test.",
|
||||
type: "string",
|
||||
choices: ["all", "affected"],
|
||||
default: "affected"
|
||||
default: "affected",
|
||||
},
|
||||
nProcesses: {
|
||||
group: "Parallelism",
|
||||
description: "How many processes to distribute parallelizable tasks over.",
|
||||
type: "number",
|
||||
default: os.cpus().length
|
||||
default: os.cpus().length,
|
||||
},
|
||||
shardId: {
|
||||
group: "Parallelism",
|
||||
description: "The machine index when sharding a run over multiple machines.",
|
||||
type: "number",
|
||||
implies: "shardCount"
|
||||
implies: "shardCount",
|
||||
},
|
||||
shardCount: {
|
||||
group: "Parallelism",
|
||||
description: "The total number of machines when sharding a run over multiple machines.",
|
||||
type: "number",
|
||||
implies: "shardId"
|
||||
implies: "shardId",
|
||||
},
|
||||
localTypeScriptPath: {
|
||||
group: "dtslint options",
|
||||
description:
|
||||
"Path to local TypeScript installation to be used by dtslint instead of all supported TypeScript versions.",
|
||||
type: "string",
|
||||
conflicts: "onlyTestTsNext"
|
||||
conflicts: "onlyTestTsNext",
|
||||
},
|
||||
onlyTestTsNext: {
|
||||
group: "dtslint options",
|
||||
description: "Run dtslint only with typescript@next instead of all supported TypeScript versions.",
|
||||
type: "boolean",
|
||||
conflicts: "localTypeScriptPath"
|
||||
conflicts: "localTypeScriptPath",
|
||||
},
|
||||
expectOnly: {
|
||||
group: "dtslint options",
|
||||
description: "Run only the ExpectType lint rule.",
|
||||
type: "boolean",
|
||||
default: false
|
||||
default: false,
|
||||
},
|
||||
// Not sure why you’d use this, so I’m hiding it
|
||||
noInstall: {
|
||||
hidden: true,
|
||||
type: "boolean",
|
||||
default: false
|
||||
}
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
.wrap(Math.min(yargs.terminalWidth(), 120)).argv;
|
||||
|
||||
@@ -79,11 +79,11 @@ if (!module.parent) {
|
||||
definitelyTypedAcquisition: args.clone
|
||||
? {
|
||||
kind: "clone",
|
||||
sha: typeof args.clone === "string" ? args.clone : undefined
|
||||
sha: typeof args.clone === "string" ? args.clone : undefined,
|
||||
}
|
||||
: {
|
||||
kind: "local",
|
||||
path: args.path || "../DefinitelyTyped"
|
||||
path: args.path || "../DefinitelyTyped",
|
||||
},
|
||||
onlyRunAffectedPackages: args.selection === "affected",
|
||||
nProcesses: args.nProcesses,
|
||||
@@ -91,7 +91,7 @@ if (!module.parent) {
|
||||
localTypeScriptPath: !args.onlyTestTsNext ? args.localTypeScriptPath : undefined,
|
||||
onlyTestTsNext: !!args.onlyTestTsNext,
|
||||
expectOnly: args.expectOnly,
|
||||
noInstall: args.noInstall
|
||||
noInstall: args.noInstall,
|
||||
};
|
||||
|
||||
logUncaughtErrors(async () => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
runWithListeningChildProcesses,
|
||||
CrashRecoveryState,
|
||||
installAllTypeScriptVersions,
|
||||
installTypeScriptNext
|
||||
installTypeScriptNext,
|
||||
} from "@definitelytyped/utils";
|
||||
import { remove, readFileSync, pathExists, readdirSync, existsSync } from "fs-extra";
|
||||
import { RunDTSLintOptions } from "./types";
|
||||
@@ -24,7 +24,7 @@ export async function runDTSLint({
|
||||
expectOnly,
|
||||
localTypeScriptPath,
|
||||
nProcesses,
|
||||
shard
|
||||
shard,
|
||||
}: RunDTSLintOptions) {
|
||||
let definitelyTypedPath;
|
||||
if (definitelyTypedAcquisition.kind === "clone") {
|
||||
@@ -64,14 +64,14 @@ export async function runDTSLint({
|
||||
const dtslintArgs = [
|
||||
"--listen",
|
||||
...(onlyTestTsNext ? ["--onlyTestTsNext"] : []),
|
||||
...(localTypeScriptPath ? ["--localTs", localTypeScriptPath] : [])
|
||||
...(localTypeScriptPath ? ["--localTs", localTypeScriptPath] : []),
|
||||
];
|
||||
|
||||
await runWithListeningChildProcesses({
|
||||
inputs: testedPackages.map(path => ({
|
||||
inputs: testedPackages.map((path) => ({
|
||||
path,
|
||||
onlyTestTsNext: onlyTestTsNext || !packageNames.includes(path),
|
||||
expectOnly: expectOnly || !packageNames.includes(path)
|
||||
expectOnly: expectOnly || !packageNames.includes(path),
|
||||
})),
|
||||
commandLineArgs: dtslintArgs,
|
||||
workerFile: require.resolve("@definitelytyped/dtslint"),
|
||||
@@ -96,7 +96,7 @@ export async function runDTSLint({
|
||||
prefix
|
||||
? status
|
||||
.split(/\r?\n/)
|
||||
.map(line => `${prefix}${line}`)
|
||||
.map((line) => `${prefix}${line}`)
|
||||
.join("\n")
|
||||
: status
|
||||
);
|
||||
@@ -109,7 +109,7 @@ export async function runDTSLint({
|
||||
prefix
|
||||
? status
|
||||
.split(/\r?\n/)
|
||||
.map(line => `${prefix}${line}`)
|
||||
.map((line) => `${prefix}${line}`)
|
||||
.join("\n")
|
||||
: status
|
||||
);
|
||||
@@ -131,7 +131,7 @@ export async function runDTSLint({
|
||||
break;
|
||||
default:
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
console.log("\n\n=== SUGGESTIONS ===\n");
|
||||
@@ -170,7 +170,7 @@ function getExpectedFailures(onlyRunAffectedPackages: boolean) {
|
||||
(readFileSync(joinPaths(__dirname, "../expectedFailures.txt"), "utf8") as string)
|
||||
.split("\n")
|
||||
.filter(Boolean)
|
||||
.map(s => s.trim())
|
||||
.map((s) => s.trim())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,7 +183,7 @@ async function cloneDefinitelyTyped(cwd: string, sha: string | undefined): Promi
|
||||
const commands = [
|
||||
"git remote add origin https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
"git fetch origin master --depth 50", // We can't clone the commit directly, so assume the commit is from
|
||||
`git checkout ${sha}` // recent history, pull down some recent commits, then check it out
|
||||
`git checkout ${sha}`, // recent history, pull down some recent commits, then check it out
|
||||
];
|
||||
for (const command of commands) {
|
||||
console.log(command);
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
checkParseResults,
|
||||
getAffectedPackagesFromDiff,
|
||||
allDependencies,
|
||||
TypingsData
|
||||
TypingsData,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
import { execAndThrowErrors, joinPaths, loggerWithErrors, npmInstallFlags } from "@definitelytyped/utils";
|
||||
import { PreparePackagesOptions, PreparePackagesResult } from "./types";
|
||||
@@ -13,14 +13,14 @@ import { PreparePackagesOptions, PreparePackagesResult } from "./types";
|
||||
export async function prepareAffectedPackages({
|
||||
definitelyTypedPath,
|
||||
noInstall,
|
||||
nProcesses
|
||||
nProcesses,
|
||||
}: PreparePackagesOptions): Promise<PreparePackagesResult> {
|
||||
const typesPath = joinPaths(definitelyTypedPath, "types");
|
||||
const log = loggerWithErrors()[0];
|
||||
const options = {
|
||||
definitelyTypedPath,
|
||||
progress: false,
|
||||
parseInParallel: nProcesses > 1
|
||||
parseInParallel: nProcesses > 1,
|
||||
};
|
||||
const dt = await getDefinitelyTyped(options, log);
|
||||
await parseDefinitions(dt, nProcesses ? { definitelyTypedPath, nProcesses } : undefined, log);
|
||||
@@ -42,8 +42,8 @@ export async function prepareAffectedPackages({
|
||||
}
|
||||
|
||||
return {
|
||||
packageNames: changedPackages.map(p => p.subDirectoryPath),
|
||||
dependents: dependentPackages.map(p => p.subDirectoryPath)
|
||||
packageNames: changedPackages.map((p) => p.subDirectoryPath),
|
||||
dependents: dependentPackages.map((p) => p.subDirectoryPath),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@ import {
|
||||
AllPackages,
|
||||
getDefinitelyTyped,
|
||||
checkParseResults,
|
||||
parseDefinitions
|
||||
parseDefinitions,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
import { joinPaths, loggerWithErrors } from "@definitelytyped/utils";
|
||||
import { installDependencies } from "./prepareAffectedPackages";
|
||||
@@ -11,14 +11,14 @@ import { PreparePackagesOptions, PreparePackagesResult } from "./types";
|
||||
export async function prepareAllPackages({
|
||||
definitelyTypedPath,
|
||||
noInstall,
|
||||
nProcesses
|
||||
nProcesses,
|
||||
}: PreparePackagesOptions): Promise<PreparePackagesResult> {
|
||||
const typesPath = joinPaths(definitelyTypedPath, "types");
|
||||
const [log] = loggerWithErrors();
|
||||
const options = {
|
||||
definitelyTypedPath,
|
||||
progress: false,
|
||||
parseInParallel: nProcesses > 1
|
||||
parseInParallel: nProcesses > 1,
|
||||
};
|
||||
const dt = await getDefinitelyTyped(options, log);
|
||||
await parseDefinitions(dt, nProcesses ? { definitelyTypedPath, nProcesses } : undefined, log);
|
||||
|
||||
@@ -70,7 +70,7 @@ export function checkTsconfig(options: CompilerOptions, dt: DefinitelyTypedInfo
|
||||
forceConsistentCasingInFileNames: true,
|
||||
baseUrl: relativeBaseUrl,
|
||||
typeRoots: [relativeBaseUrl],
|
||||
types: []
|
||||
types: [],
|
||||
};
|
||||
|
||||
for (const key of Object.getOwnPropertyNames(mustHave) as (keyof typeof mustHave)[]) {
|
||||
|
||||
@@ -116,11 +116,11 @@ function listen(dirPath: string, tsLocal: string | undefined, alwaysOnlyTestTsNe
|
||||
|
||||
await installationPromise;
|
||||
runTests(joinPaths(dirPath, path), onlyTestTsNext, !!expectOnly, tsLocal)
|
||||
.catch(e => e.stack)
|
||||
.then(maybeError => {
|
||||
.catch((e) => e.stack)
|
||||
.then((maybeError) => {
|
||||
process.send!({ path, status: maybeError === undefined ? "OK" : maybeError });
|
||||
})
|
||||
.catch(e => console.error(e.stack));
|
||||
.catch((e) => console.error(e.stack));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -145,7 +145,7 @@ async function runTests(
|
||||
assertPackageIsNotDeprecated(packageName, await readFile(joinPaths(dtRoot, "notNeededPackages.json"), "utf-8"));
|
||||
}
|
||||
|
||||
const typesVersions = await mapDefinedAsync(await readdir(dirPath), async name => {
|
||||
const typesVersions = await mapDefinedAsync(await readdir(dirPath), async (name) => {
|
||||
if (name === "tsconfig.json" || name === "tslint.json" || name === "tsutils") {
|
||||
return undefined;
|
||||
}
|
||||
@@ -302,7 +302,7 @@ function getMinimumTypeScriptVersionFromComment(text: string): AllTypeScriptVers
|
||||
}
|
||||
|
||||
if (!module.parent) {
|
||||
main().catch(err => {
|
||||
main().catch((err) => {
|
||||
console.error(err.stack);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -32,7 +32,7 @@ export async function lint(
|
||||
|
||||
const lintOptions: ILinterOptions = {
|
||||
fix: false,
|
||||
formatter: "stylish"
|
||||
formatter: "stylish",
|
||||
};
|
||||
const linter = new Linter(lintOptions, lintProgram);
|
||||
const configPath = expectOnly ? joinPaths(__dirname, "..", "dtslint-expect-only.json") : getConfigPath(dirPath);
|
||||
@@ -76,22 +76,22 @@ function testDependencies(
|
||||
const program = getProgram(tsconfigPath, ts, version, lintProgram);
|
||||
const diagnostics = ts
|
||||
.getPreEmitDiagnostics(program)
|
||||
.filter(d => !d.file || isExternalDependency(d.file, dirPath, program));
|
||||
.filter((d) => !d.file || isExternalDependency(d.file, dirPath, program));
|
||||
if (!diagnostics.length) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const showDiags = ts.formatDiagnostics(diagnostics, {
|
||||
getCanonicalFileName: f => f,
|
||||
getCanonicalFileName: (f) => f,
|
||||
getCurrentDirectory: () => dirPath,
|
||||
getNewLine: () => "\n"
|
||||
getNewLine: () => "\n",
|
||||
});
|
||||
|
||||
const message = `Errors in typescript@${version} for external dependencies:\n${showDiags}`;
|
||||
|
||||
// Add an edge-case for someone needing to `npm install` in react when they first edit a DT module which depends on it - #226
|
||||
const cannotFindDepsDiags = diagnostics.find(
|
||||
d => d.code === 2307 && d.messageText.toString().includes("Cannot find module")
|
||||
(d) => d.code === 2307 && d.messageText.toString().includes("Cannot find module")
|
||||
);
|
||||
if (cannotFindDepsDiags && cannotFindDepsDiags.file) {
|
||||
const path = cannotFindDepsDiags.file.fileName;
|
||||
@@ -120,7 +120,7 @@ function normalizePath(file: string) {
|
||||
// replaces '\' with '/' and forces all DOS drive letters to be upper-case
|
||||
return normalize(file)
|
||||
.replace(/\\/g, "/")
|
||||
.replace(/^[a-z](?=:)/, c => c.toUpperCase());
|
||||
.replace(/^[a-z](?=:)/, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
function isTypesVersionPath(fileName: string, dirPath: string) {
|
||||
@@ -170,7 +170,7 @@ export async function checkTslintJson(dirPath: string, dt: boolean): Promise<voi
|
||||
const configPath = getConfigPath(dirPath);
|
||||
const shouldExtend = `@definitelytyped/dtslint/${dt ? "dt" : "dtslint"}.json`;
|
||||
const validateExtends = (extend: string | string[]) =>
|
||||
extend === shouldExtend || (!dt && Array.isArray(extend) && extend.some(val => val === shouldExtend));
|
||||
extend === shouldExtend || (!dt && Array.isArray(extend) && extend.some((val) => val === shouldExtend));
|
||||
|
||||
if (!(await pathExists(configPath))) {
|
||||
if (dt) {
|
||||
@@ -212,9 +212,9 @@ async function getLintConfig(
|
||||
throw new Error("'expect' rule should be enabled, else compile errors are ignored");
|
||||
}
|
||||
if (expectRule) {
|
||||
const versionsToTest = range(minVersion, maxVersion).map(versionName => ({
|
||||
const versionsToTest = range(minVersion, maxVersion).map((versionName) => ({
|
||||
versionName,
|
||||
path: typeScriptPath(versionName, tsLocal)
|
||||
path: typeScriptPath(versionName, tsLocal),
|
||||
}));
|
||||
const expectOptions: ExpectOptions = { tsconfigPath, versionsToTest };
|
||||
expectRule.ruleArguments = [expectOptions];
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
|
||||
@@ -21,7 +21,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true,
|
||||
requiresTypeInfo: true
|
||||
requiresTypeInfo: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING_DUPLICATE_ASSERTION = "This line has 2 $ExpectType assertions.";
|
||||
@@ -37,7 +37,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
applyWithProgram(sourceFile: SourceFile, lintProgram: Program): Lint.RuleFailure[] {
|
||||
const options = this.ruleArguments[0] as Options | undefined;
|
||||
if (!options) {
|
||||
return this.applyWithFunction(sourceFile, ctx =>
|
||||
return this.applyWithFunction(sourceFile, (ctx) =>
|
||||
walk(ctx, lintProgram, TsType, "next", /*nextHigherVersion*/ undefined)
|
||||
);
|
||||
}
|
||||
@@ -51,7 +51,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
) => {
|
||||
const ts = require(path);
|
||||
const program = getProgram(tsconfigPath, ts, versionName, lintProgram);
|
||||
const failures = this.applyWithFunction(sourceFile, ctx =>
|
||||
const failures = this.applyWithFunction(sourceFile, (ctx) =>
|
||||
walk(ctx, program, ts, versionName, nextHigherVersion)
|
||||
);
|
||||
if (writeOutput) {
|
||||
@@ -60,8 +60,8 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
const d = {
|
||||
[packageName]: {
|
||||
typeCount: (program as any).getTypeCount(),
|
||||
memory: ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : 0
|
||||
}
|
||||
memory: ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : 0,
|
||||
},
|
||||
};
|
||||
if (!existsSync(cacheDir)) {
|
||||
mkdirSync(cacheDir);
|
||||
@@ -133,11 +133,11 @@ function createProgram(configFile: string, ts: typeof TsType): Program {
|
||||
const parseConfigHost: TsType.ParseConfigHost = {
|
||||
fileExists: existsSync,
|
||||
readDirectory: ts.sys.readDirectory,
|
||||
readFile: file => readFileSync(file, "utf8"),
|
||||
useCaseSensitiveFileNames: true
|
||||
readFile: (file) => readFileSync(file, "utf8"),
|
||||
useCaseSensitiveFileNames: true,
|
||||
};
|
||||
const parsed = ts.parseJsonConfigFileContent(config, parseConfigHost, resolvePath(projectDirectory), {
|
||||
noEmit: true
|
||||
noEmit: true,
|
||||
});
|
||||
const host = ts.createCompilerHost(parsed.options, true);
|
||||
return ts.createProgram(parsed.fileNames, parsed.options, host);
|
||||
@@ -387,7 +387,7 @@ function getExpectTypeFailures(
|
||||
? checker.typeToString(type, /*enclosingDeclaration*/ undefined, ts.TypeFormatFlags.NoTruncation)
|
||||
: "";
|
||||
|
||||
if (!expected.split(/\s*\|\|\s*/).some(s => actual === s || matchReadonlyArray(actual, s))) {
|
||||
if (!expected.split(/\s*\|\|\s*/).some((s) => actual === s || matchReadonlyArray(actual, s))) {
|
||||
unmetExpectations.push({ node, expected, actual });
|
||||
}
|
||||
|
||||
@@ -403,7 +403,7 @@ function getNodeForExpectType(node: TsType.Node, ts: typeof TsType): TsType.Node
|
||||
if (node.kind === ts.SyntaxKind.VariableStatement) {
|
||||
// ts2.0 doesn't have `isVariableStatement`
|
||||
const {
|
||||
declarationList: { declarations }
|
||||
declarationList: { declarations },
|
||||
} = node as TsType.VariableStatement;
|
||||
if (declarations.length === 1) {
|
||||
const { initializer } = declarations[0];
|
||||
|
||||
@@ -11,7 +11,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
@@ -26,7 +26,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
|
||||
function walk(ctx: Lint.WalkContext<void>): void {
|
||||
const {
|
||||
sourceFile: { statements }
|
||||
sourceFile: { statements },
|
||||
} = ctx;
|
||||
const exportEqualsNode = statements.find(isExportEquals) as ts.ExportAssignment | undefined;
|
||||
if (!exportEqualsNode) {
|
||||
@@ -57,7 +57,7 @@ function isJustNamespace(statements: readonly ts.Statement[], exportEqualsName:
|
||||
anyNamespace = anyNamespace || nameMatches((statement as ts.ModuleDeclaration).name);
|
||||
break;
|
||||
case ts.SyntaxKind.VariableStatement:
|
||||
if ((statement as ts.VariableStatement).declarationList.declarations.some(d => nameMatches(d.name))) {
|
||||
if ((statement as ts.VariableStatement).declarationList.declarations.some((d) => nameMatches(d.name))) {
|
||||
// OK. It's merged with a variable.
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(Rule.metadata.ruleName, "Use of `const enum`s is forbidden.");
|
||||
@@ -25,7 +25,7 @@ function walk(ctx: Lint.WalkContext<void>): void {
|
||||
if (
|
||||
ts.isEnumDeclaration(node) &&
|
||||
node.modifiers &&
|
||||
node.modifiers.some(m => m.kind === ts.SyntaxKind.ConstKeyword)
|
||||
node.modifiers.some((m) => m.kind === ts.SyntaxKind.ConstKeyword)
|
||||
) {
|
||||
ctx.addFailureAtNode(node.name, Rule.FAILURE_STRING);
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
@@ -26,7 +26,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
|
||||
function walk(ctx: Lint.WalkContext<void>): void {
|
||||
const {
|
||||
sourceFile: { statements, text }
|
||||
sourceFile: { statements, text },
|
||||
} = ctx;
|
||||
if (!statements.length) {
|
||||
return;
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
@@ -19,7 +19,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
}
|
||||
|
||||
const packageName = getCommonDirectoryName(program.getRootFileNames());
|
||||
return this.applyWithFunction(sourceFile, ctx => walk(ctx, packageName));
|
||||
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, packageName));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
@@ -22,12 +22,12 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
}
|
||||
|
||||
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
return this.applyWithFunction(sourceFile, ctx => walk(ctx, program.getTypeChecker()));
|
||||
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, program.getTypeChecker()));
|
||||
}
|
||||
}
|
||||
|
||||
function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
|
||||
eachModuleStatement(ctx.sourceFile, statement => {
|
||||
eachModuleStatement(ctx.sourceFile, (statement) => {
|
||||
if (!ts.isImportDeclaration(statement)) {
|
||||
return;
|
||||
}
|
||||
@@ -39,9 +39,9 @@ function walk(ctx: Lint.WalkContext<void>, checker: ts.TypeChecker): void {
|
||||
if (
|
||||
sym &&
|
||||
sym.declarations &&
|
||||
sym.declarations.some(d => {
|
||||
sym.declarations.some((d) => {
|
||||
const statements = getStatements(d);
|
||||
return statements !== undefined && statements.some(s => ts.isExportAssignment(s) && !!s.isExportEquals);
|
||||
return statements !== undefined && statements.some((s) => ts.isExportAssignment(s) && !!s.isExportEquals);
|
||||
})
|
||||
) {
|
||||
ctx.addFailureAtNode(defaultName, Rule.FAILURE_STRING(defaultName.text, statement.moduleSpecifier.getText()));
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
applyWithProgram(_sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
|
||||
@@ -12,7 +12,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
options: null,
|
||||
optionExamples: [true],
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
static readonly FAILURE_STRING_REDUNDANT_TYPE = "Type annotation in JSDoc is redundant in TypeScript code.";
|
||||
static readonly FAILURE_STRING_EMPTY = "JSDoc comment is empty.";
|
||||
@@ -249,5 +249,5 @@ const redundantTags = new Set([
|
||||
"property",
|
||||
"requires",
|
||||
"static",
|
||||
"this"
|
||||
"this",
|
||||
]);
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: false
|
||||
typescriptOnly: false,
|
||||
};
|
||||
|
||||
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
@@ -18,7 +18,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
return [];
|
||||
}
|
||||
|
||||
return this.applyWithFunction(sourceFile, ctx => walk(ctx, program.getTypeChecker()));
|
||||
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, program.getTypeChecker()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: false
|
||||
typescriptOnly: false,
|
||||
};
|
||||
|
||||
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
@@ -19,7 +19,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
}
|
||||
|
||||
const name = getCommonDirectoryName(program.getRootFileNames());
|
||||
return this.applyWithFunction(sourceFile, ctx => walk(ctx, name));
|
||||
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, name));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
// eslint-disable-next-line @typescript-eslint/naming-convention
|
||||
static FAILURE_STRING(typeParameter: string) {
|
||||
@@ -22,7 +22,7 @@ export class Rule extends Lint.Rules.TypedRule {
|
||||
}
|
||||
|
||||
applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): Lint.RuleFailure[] {
|
||||
return this.applyWithFunction(sourceFile, ctx => walk(ctx, program.getTypeChecker()));
|
||||
return this.applyWithFunction(sourceFile, (ctx) => walk(ctx, program.getTypeChecker()));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "functionality",
|
||||
typescriptOnly: false
|
||||
typescriptOnly: false,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(Rule.metadata.ruleName, "File has no content.");
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ExportErrorKind,
|
||||
Mode,
|
||||
parseExportErrorKind,
|
||||
parseMode
|
||||
parseMode,
|
||||
} from "@definitelytyped/dts-critic";
|
||||
import * as Lint from "tslint";
|
||||
import * as ts from "typescript";
|
||||
@@ -30,7 +30,7 @@ type ConfigOptions =
|
||||
type Options = CriticOptions & { singleLine?: boolean };
|
||||
|
||||
const defaultOptions: ConfigOptions = {
|
||||
mode: Mode.NameOnly
|
||||
mode: Mode.NameOnly,
|
||||
};
|
||||
|
||||
export class Rule extends Lint.Rules.AbstractRule {
|
||||
@@ -47,21 +47,21 @@ If \`mode\` is '${Mode.Code}', then option \`errors\` can be provided.
|
||||
properties: {
|
||||
mode: {
|
||||
type: "string",
|
||||
enum: [Mode.NameOnly]
|
||||
enum: [Mode.NameOnly],
|
||||
},
|
||||
"single-line": {
|
||||
description: "Whether to print error messages in a single line. Used for testing.",
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
},
|
||||
required: ["mode"]
|
||||
}
|
||||
required: ["mode"],
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "object",
|
||||
properties: {
|
||||
mode: {
|
||||
type: "string",
|
||||
enum: [Mode.Code]
|
||||
enum: [Mode.Code],
|
||||
},
|
||||
errors: {
|
||||
type: "array",
|
||||
@@ -71,26 +71,26 @@ If \`mode\` is '${Mode.Code}', then option \`errors\` can be provided.
|
||||
{
|
||||
description: "Name of the check.",
|
||||
type: "string",
|
||||
enum: [ErrorKind.NeedsExportEquals, ErrorKind.NoDefaultExport] as ExportErrorKind[]
|
||||
enum: [ErrorKind.NeedsExportEquals, ErrorKind.NoDefaultExport] as ExportErrorKind[],
|
||||
},
|
||||
{
|
||||
description: "Whether the check is enabled or disabled.",
|
||||
type: "boolean"
|
||||
}
|
||||
type: "boolean",
|
||||
},
|
||||
],
|
||||
minItems: 2,
|
||||
maxItems: 2
|
||||
maxItems: 2,
|
||||
},
|
||||
default: []
|
||||
default: [],
|
||||
},
|
||||
"single-line": {
|
||||
description: "Whether to print error messages in a single line. Used for testing.",
|
||||
type: "boolean"
|
||||
type: "boolean",
|
||||
},
|
||||
required: ["mode"]
|
||||
}
|
||||
}
|
||||
]
|
||||
required: ["mode"],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
optionExamples: [
|
||||
true,
|
||||
@@ -101,13 +101,13 @@ If \`mode\` is '${Mode.Code}', then option \`errors\` can be provided.
|
||||
mode: Mode.Code,
|
||||
errors: [
|
||||
[ErrorKind.NeedsExportEquals, true],
|
||||
[ErrorKind.NoDefaultExport, false]
|
||||
]
|
||||
}
|
||||
]
|
||||
[ErrorKind.NoDefaultExport, false],
|
||||
],
|
||||
},
|
||||
],
|
||||
],
|
||||
type: "functionality",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
@@ -223,13 +223,13 @@ function toOptionsWithSuggestions(options: CriticOptions): CriticOptions {
|
||||
return options;
|
||||
}
|
||||
const optionsWithSuggestions = { mode: options.mode, errors: new Map(options.errors) };
|
||||
enabledSuggestions.forEach(err => optionsWithSuggestions.errors.set(err, true));
|
||||
enabledSuggestions.forEach((err) => optionsWithSuggestions.errors.set(err, true));
|
||||
return optionsWithSuggestions;
|
||||
}
|
||||
|
||||
function filterErrors(diagnostics: CriticError[], ctx: Lint.WalkContext<Options>): CriticError[] {
|
||||
const errors: CriticError[] = [];
|
||||
diagnostics.forEach(diagnostic => {
|
||||
diagnostics.forEach((diagnostic) => {
|
||||
if (isSuggestion(diagnostic, ctx.options)) {
|
||||
addSuggestion(ctx, diagnostic.message, diagnostic.position?.start, diagnostic.position?.length);
|
||||
} else {
|
||||
@@ -311,10 +311,10 @@ export function disabler(failures: Lint.IRuleFailureJson[]): false | [true, Conf
|
||||
}
|
||||
}
|
||||
|
||||
if ((defaultErrors as ExportErrorKind[]).every(error => disabledErrors.has(error))) {
|
||||
if ((defaultErrors as ExportErrorKind[]).every((error) => disabledErrors.has(error))) {
|
||||
return [true, { mode: Mode.NameOnly }];
|
||||
}
|
||||
const errors: [ExportErrorKind, boolean][] = [];
|
||||
disabledErrors.forEach(error => errors.push([error, false]));
|
||||
disabledErrors.forEach((error) => errors.push([error, false]));
|
||||
return [true, { mode: Mode.Code, errors }];
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
@@ -24,7 +24,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
}
|
||||
|
||||
function walk(ctx: Lint.WalkContext<void>): void {
|
||||
eachModuleStatement(ctx.sourceFile, statement => {
|
||||
eachModuleStatement(ctx.sourceFile, (statement) => {
|
||||
if (ts.isVariableStatement(statement)) {
|
||||
for (const varDecl of statement.declarationList.declarations) {
|
||||
if (varDecl.type !== undefined && varDecl.type.kind === ts.SyntaxKind.FunctionType) {
|
||||
|
||||
@@ -11,7 +11,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
apply(sourceFile: ts.SourceFile): Lint.RuleFailure[] {
|
||||
@@ -23,7 +23,7 @@ function walk(ctx: Lint.WalkContext<void>): void {
|
||||
const isExternal =
|
||||
sourceFile.isDeclarationFile &&
|
||||
!sourceFile.statements.some(
|
||||
s =>
|
||||
(s) =>
|
||||
s.kind === ts.SyntaxKind.ExportAssignment ||
|
||||
(s.kind === ts.SyntaxKind.ExportDeclaration && !!(s as ts.ExportDeclaration).exportClause)
|
||||
) &&
|
||||
@@ -86,7 +86,7 @@ function walk(ctx: Lint.WalkContext<void>): void {
|
||||
}
|
||||
|
||||
function mod(node: ts.Statement, kind: ts.SyntaxKind): ts.Node {
|
||||
return node.modifiers!.find(m => m.kind === kind)!;
|
||||
return node.modifiers!.find((m) => m.kind === kind)!;
|
||||
}
|
||||
|
||||
function checkModule(moduleDeclaration: ts.ModuleDeclaration): void {
|
||||
|
||||
@@ -10,7 +10,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: false
|
||||
typescriptOnly: false,
|
||||
};
|
||||
|
||||
static FAILURE_STRING_LEADING = failure(Rule.metadata.ruleName, "File should not begin with a blank line.");
|
||||
@@ -26,7 +26,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
|
||||
function walk(ctx: Lint.WalkContext<void>): void {
|
||||
const {
|
||||
sourceFile: { text }
|
||||
sourceFile: { text },
|
||||
} = ctx;
|
||||
if (text.startsWith("\r") || text.startsWith("\n")) {
|
||||
ctx.addFailureAt(0, 0, Rule.FAILURE_STRING_LEADING);
|
||||
|
||||
@@ -11,7 +11,7 @@ export class Rule extends Lint.Rules.AbstractRule {
|
||||
optionsDescription: "Not configurable.",
|
||||
options: null,
|
||||
type: "style",
|
||||
typescriptOnly: true
|
||||
typescriptOnly: true,
|
||||
};
|
||||
|
||||
static FAILURE_STRING = failure(
|
||||
|
||||
@@ -25,7 +25,7 @@ export function addSuggestion<T>(ctx: WalkContext<T>, message: string, start?: n
|
||||
ruleName: ctx.ruleName,
|
||||
message,
|
||||
start,
|
||||
width
|
||||
width,
|
||||
};
|
||||
|
||||
const packageName = dtPackageName(ctx.sourceFile.fileName);
|
||||
@@ -59,7 +59,7 @@ function dtPackageName(filePath: string): string | undefined {
|
||||
return undefined;
|
||||
}
|
||||
const basePath = filePath.substr(dtIndex + dtPath.length);
|
||||
const dirs = basePath.split(path.sep).filter(dir => dir !== "");
|
||||
const dirs = basePath.split(path.sep).filter((dir) => dir !== "");
|
||||
if (dirs.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -29,24 +29,24 @@ function main() {
|
||||
.option("package", {
|
||||
describe: "Path of DT package.",
|
||||
type: "string",
|
||||
conflicts: "dt"
|
||||
conflicts: "dt",
|
||||
})
|
||||
.option("dt", {
|
||||
describe: "Path of local DefinitelyTyped repository.",
|
||||
type: "string",
|
||||
conflicts: "package"
|
||||
conflicts: "package",
|
||||
})
|
||||
.option("rules", {
|
||||
describe: "Names of the rules to be updated. Leave this empty to update all rules.",
|
||||
type: "array",
|
||||
string: true,
|
||||
default: [] as string[]
|
||||
default: [] as string[],
|
||||
})
|
||||
.check(arg => {
|
||||
.check((arg) => {
|
||||
if (!arg.package && !arg.dt) {
|
||||
throw new Error("You must provide either argument 'package' or 'dt'.");
|
||||
}
|
||||
const unsupportedRules = arg.rules.filter(rule => ignoredRules.includes(rule));
|
||||
const unsupportedRules = arg.rules.filter((rule) => ignoredRules.includes(rule));
|
||||
if (unsupportedRules.length > 0) {
|
||||
throw new Error(`Rules ${unsupportedRules.join(", ")} are not supported at the moment.`);
|
||||
}
|
||||
@@ -89,7 +89,7 @@ function updatePackage(pkgPath: string, baseConfig: Config.IConfigurationFile):
|
||||
const packages = walkPackageDir(pkgPath);
|
||||
|
||||
const linterOpts: ILinterOptions = {
|
||||
fix: false
|
||||
fix: false,
|
||||
};
|
||||
|
||||
for (const pkg of packages) {
|
||||
@@ -106,7 +106,7 @@ function installDependencies(pkgPath: string): void {
|
||||
if (fs.existsSync(path.join(pkgPath, "package.json"))) {
|
||||
cp.execSync("npm install --ignore-scripts --no-shrinkwrap --no-package-lock --no-bin-links", {
|
||||
encoding: "utf8",
|
||||
cwd: pkgPath
|
||||
cwd: pkgPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -172,7 +172,7 @@ class LintPackage {
|
||||
updateConfig(config: Config.RawConfigFile): void {
|
||||
fs.writeFileSync(path.join(this.rootDir, "tslint.json"), stringify(config, { space: 4 }), {
|
||||
encoding: "utf8",
|
||||
flag: "w"
|
||||
flag: "w",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,7 +41,7 @@ describe("dtslint", () => {
|
||||
typeRoots: ["../"],
|
||||
types: [],
|
||||
noEmit: true,
|
||||
forceConsistentCasingInFileNames: true
|
||||
forceConsistentCasingInFileNames: true,
|
||||
};
|
||||
describe("checks", () => {
|
||||
it("disallows unknown compiler options", () => {
|
||||
@@ -67,7 +67,7 @@ describe("dtslint", () => {
|
||||
});
|
||||
});
|
||||
describe("rules", () => {
|
||||
const tests = readdirSync(testDir).filter(x => x !== "index.test.ts");
|
||||
const tests = readdirSync(testDir).filter((x) => x !== "index.test.ts");
|
||||
for (const testName of tests) {
|
||||
const testDirectory = join(testDir, testName);
|
||||
if (existsSync(join(testDirectory, "tslint.json"))) {
|
||||
|
||||
@@ -103,7 +103,7 @@ function headerParser(strict: boolean): pm.Parser<Header> {
|
||||
nonNpm: str.endsWith("non-npm package "),
|
||||
projects,
|
||||
contributors,
|
||||
typeScriptVersion
|
||||
typeScriptVersion,
|
||||
})
|
||||
);
|
||||
}
|
||||
@@ -206,7 +206,7 @@ function parseLabel(strict: boolean): pm.Parser<Label> {
|
||||
return pm.makeSuccess<Label>(end, {
|
||||
name,
|
||||
major: intOfString(major),
|
||||
minor: minor === "x" ? 0 : intOfString(minor)
|
||||
minor: minor === "x" ? 0 : intOfString(minor),
|
||||
});
|
||||
|
||||
function fail(msg?: string): pm.Reply<Label> {
|
||||
@@ -221,7 +221,7 @@ function parseLabel(strict: boolean): pm.Parser<Label> {
|
||||
|
||||
const typeScriptVersionLineParser: pm.Parser<AllTypeScriptVersion> = pm
|
||||
.regexp(/\/\/ (?:Minimum )?TypeScript Version: (\d.(\d))/, 1)
|
||||
.chain<TypeScriptVersion>(v =>
|
||||
.chain<TypeScriptVersion>((v) =>
|
||||
TypeScriptVersion.all.includes(v as TypeScriptVersion)
|
||||
? pm.succeed(v as TypeScriptVersion)
|
||||
: pm.fail(`TypeScript ${v} is not yet supported.`)
|
||||
|
||||
@@ -20,8 +20,8 @@ describe("parse", () => {
|
||||
projects: ["https://github.com/foo/foo", "https://foo.com"],
|
||||
contributors: [
|
||||
{ name: "My Self", url: "https://github.com/me", githubUsername: "me" },
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" }
|
||||
]
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -45,8 +45,8 @@ describe("parse", () => {
|
||||
projects: ["https://github.com/foo/foo", "https://foo.com"],
|
||||
contributors: [
|
||||
{ name: "My Self", url: "https://github.com/me", githubUsername: "me" },
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" }
|
||||
]
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,8 +70,8 @@ describe("parse", () => {
|
||||
projects: ["https://github.com/foo/foo", "https://foo.com"],
|
||||
contributors: [
|
||||
{ name: "My Self", url: "https://github.com/me", githubUsername: "me" },
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" }
|
||||
]
|
||||
{ name: "Some Other Guy", url: "https://github.com/otherguy", githubUsername: "otherguy" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
@@ -82,7 +82,7 @@ describe("parse", () => {
|
||||
// Definitions by: Bad Url <sptth://hubgit.moc/em>
|
||||
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped`;
|
||||
expect(parseHeaderOrFail(src).contributors).toStrictEqual([
|
||||
{ name: "Bad Url", url: "sptth://hubgit.moc/em", githubUsername: undefined }
|
||||
{ name: "Bad Url", url: "sptth://hubgit.moc/em", githubUsername: undefined },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -188,12 +188,12 @@ describe("tagsToUpdate", () => {
|
||||
"ts4.5",
|
||||
"ts4.6",
|
||||
"ts4.7",
|
||||
"latest"
|
||||
"latest",
|
||||
]);
|
||||
});
|
||||
it("allows 3.9 onwards", () => {
|
||||
expect(TypeScriptVersion.tagsToUpdate("3.9")).toEqual(
|
||||
TypeScriptVersion.supported.map(s => "ts" + s).concat("latest")
|
||||
TypeScriptVersion.supported.map((s) => "ts" + s).concat("latest")
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -205,8 +205,8 @@ describe("makeTypesVersionsForPackageJson", () => {
|
||||
it("works for one version", () => {
|
||||
expect(makeTypesVersionsForPackageJson(["4.0"])).toEqual({
|
||||
"<=4.0": {
|
||||
"*": ["ts4.0/*"]
|
||||
}
|
||||
"*": ["ts4.0/*"],
|
||||
},
|
||||
});
|
||||
});
|
||||
it("orders versions old to new with old-to-new input", () => {
|
||||
|
||||
@@ -12,7 +12,7 @@ export interface FormatOptions {
|
||||
export const enum SignificanceLevel {
|
||||
Warning = "warning",
|
||||
Alert = "alert",
|
||||
Awesome = "awesome"
|
||||
Awesome = "awesome",
|
||||
}
|
||||
|
||||
export type GetSignificance = (
|
||||
@@ -78,69 +78,59 @@ function getOrderOfMagnitudeSignificance(percentDiff: number): SignificanceLevel
|
||||
const getInsignificant = () => undefined;
|
||||
|
||||
function proportionalTo(proportionalTo: MetricName) {
|
||||
return (getSignificance: GetSignificance): GetSignificance => (
|
||||
percentDiff,
|
||||
beforeValue,
|
||||
afterValue,
|
||||
beforeDoc,
|
||||
afterDoc
|
||||
) => {
|
||||
const proportionalToBeforeValue = metrics[proportionalTo].getValue(beforeDoc);
|
||||
const proportionalToAfterValue = metrics[proportionalTo].getValue(afterDoc);
|
||||
if (typeof proportionalToBeforeValue === "number" && typeof proportionalToAfterValue === "number") {
|
||||
const proportionalToPercentDiff = getPercentDiff(proportionalToAfterValue, proportionalToBeforeValue);
|
||||
const defaultSignificance = getSignificance(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc);
|
||||
const weightedSignificance = getSignificance(
|
||||
percentDiff - proportionalToPercentDiff,
|
||||
beforeValue,
|
||||
afterValue,
|
||||
beforeDoc,
|
||||
afterDoc
|
||||
);
|
||||
// Can’t give out a gold star unless it’s absolutely better, otherwise it looks really confusing
|
||||
// when type count increased by 400% and that gets treated as “awesome” when identifier count
|
||||
// increased by 500%. It may _be_ awesome, but it looks confusing.
|
||||
if (weightedSignificance === SignificanceLevel.Awesome && defaultSignificance !== SignificanceLevel.Awesome) {
|
||||
return undefined;
|
||||
return (getSignificance: GetSignificance): GetSignificance =>
|
||||
(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc) => {
|
||||
const proportionalToBeforeValue = metrics[proportionalTo].getValue(beforeDoc);
|
||||
const proportionalToAfterValue = metrics[proportionalTo].getValue(afterDoc);
|
||||
if (typeof proportionalToBeforeValue === "number" && typeof proportionalToAfterValue === "number") {
|
||||
const proportionalToPercentDiff = getPercentDiff(proportionalToAfterValue, proportionalToBeforeValue);
|
||||
const defaultSignificance = getSignificance(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc);
|
||||
const weightedSignificance = getSignificance(
|
||||
percentDiff - proportionalToPercentDiff,
|
||||
beforeValue,
|
||||
afterValue,
|
||||
beforeDoc,
|
||||
afterDoc
|
||||
);
|
||||
// Can’t give out a gold star unless it’s absolutely better, otherwise it looks really confusing
|
||||
// when type count increased by 400% and that gets treated as “awesome” when identifier count
|
||||
// increased by 500%. It may _be_ awesome, but it looks confusing.
|
||||
if (weightedSignificance === SignificanceLevel.Awesome && defaultSignificance !== SignificanceLevel.Awesome) {
|
||||
return undefined;
|
||||
}
|
||||
return weightedSignificance;
|
||||
}
|
||||
return weightedSignificance;
|
||||
}
|
||||
return;
|
||||
};
|
||||
return;
|
||||
};
|
||||
}
|
||||
|
||||
enum FineIf {
|
||||
LessThan = -1,
|
||||
GreaterThanOrEqualTo = 1
|
||||
GreaterThanOrEqualTo = 1,
|
||||
}
|
||||
|
||||
function withThreshold(fineIf: FineIf, threshold: number) {
|
||||
return (getSignificance: GetSignificance): GetSignificance => (
|
||||
percentDiff,
|
||||
beforeValue,
|
||||
afterValue,
|
||||
beforeDoc,
|
||||
afterDoc
|
||||
) => {
|
||||
const significance = getSignificance(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc);
|
||||
if (afterValue * fineIf >= threshold * fineIf) {
|
||||
switch (significance) {
|
||||
case undefined:
|
||||
case SignificanceLevel.Alert:
|
||||
case SignificanceLevel.Warning:
|
||||
return undefined;
|
||||
case SignificanceLevel.Awesome:
|
||||
return significance;
|
||||
default:
|
||||
assertNever(significance);
|
||||
return (getSignificance: GetSignificance): GetSignificance =>
|
||||
(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc) => {
|
||||
const significance = getSignificance(percentDiff, beforeValue, afterValue, beforeDoc, afterDoc);
|
||||
if (afterValue * fineIf >= threshold * fineIf) {
|
||||
switch (significance) {
|
||||
case undefined:
|
||||
case SignificanceLevel.Alert:
|
||||
case SignificanceLevel.Warning:
|
||||
return undefined;
|
||||
case SignificanceLevel.Awesome:
|
||||
return significance;
|
||||
default:
|
||||
assertNever(significance);
|
||||
}
|
||||
}
|
||||
}
|
||||
return significance;
|
||||
};
|
||||
return significance;
|
||||
};
|
||||
}
|
||||
|
||||
function compose(x: CreateGetSignificance, ...xs: CreateGetSignificance[]): CreateGetSignificance {
|
||||
return getSignificance => {
|
||||
return (getSignificance) => {
|
||||
let current = x(getSignificance);
|
||||
while ((x = xs.pop()!)) {
|
||||
current = x(current);
|
||||
@@ -154,95 +144,95 @@ export const metrics: { [K in MetricName]: Metric } = {
|
||||
columnName: "Type count",
|
||||
sentenceName: "type count",
|
||||
formatOptions: { precision: 0 },
|
||||
getValue: x => x.typeCount,
|
||||
getValue: (x) => x.typeCount,
|
||||
getSignificance: compose(
|
||||
proportionalTo("identifierCount"),
|
||||
withThreshold(FineIf.LessThan, 5000)
|
||||
)(getOrderOfMagnitudeSignificance)
|
||||
)(getOrderOfMagnitudeSignificance),
|
||||
},
|
||||
memoryUsage: {
|
||||
columnName: "Memory usage (MiB)",
|
||||
sentenceName: "memory usage",
|
||||
getValue: x => x.memoryUsage / 2 ** 20,
|
||||
getValue: (x) => x.memoryUsage / 2 ** 20,
|
||||
getSignificance: compose(
|
||||
proportionalTo("identifierCount"),
|
||||
withThreshold(FineIf.LessThan, 65)
|
||||
)(getOrderOfMagnitudeSignificance)
|
||||
)(getOrderOfMagnitudeSignificance),
|
||||
},
|
||||
assignabilityCacheSize: {
|
||||
columnName: "Assignability cache size",
|
||||
sentenceName: "assignability cache size",
|
||||
formatOptions: { precision: 0 },
|
||||
getValue: x => x.relationCacheSizes && x.relationCacheSizes.assignable,
|
||||
getValue: (x) => x.relationCacheSizes && x.relationCacheSizes.assignable,
|
||||
getSignificance: compose(
|
||||
proportionalTo("identifierCount"),
|
||||
withThreshold(FineIf.LessThan, 1000)
|
||||
)(getOrderOfMagnitudeSignificance)
|
||||
)(getOrderOfMagnitudeSignificance),
|
||||
},
|
||||
samplesTaken: {
|
||||
columnName: "Samples taken",
|
||||
sentenceName: "number of samples taken",
|
||||
formatOptions: { precision: 0 },
|
||||
getValue: x => Math.max(x.completions.trials, x.quickInfo.trials),
|
||||
getSignificance: getInsignificant
|
||||
getValue: (x) => Math.max(x.completions.trials, x.quickInfo.trials),
|
||||
getSignificance: getInsignificant,
|
||||
},
|
||||
identifierCount: {
|
||||
columnName: "Identifiers in tests",
|
||||
sentenceName: "number of identifiers present in test files",
|
||||
formatOptions: { precision: 0 },
|
||||
getValue: x => x.testIdentifierCount,
|
||||
getSignificance: getInsignificant
|
||||
getValue: (x) => x.testIdentifierCount,
|
||||
getSignificance: getInsignificant,
|
||||
},
|
||||
completionsMean: {
|
||||
columnName: "Mean duration (ms)",
|
||||
sentenceName: "mean duration for getting completions at a position",
|
||||
getValue: x => x.completions.mean,
|
||||
getSignificance: withThreshold(FineIf.LessThan, 150)(getDefaultSignificance)
|
||||
getValue: (x) => x.completions.mean,
|
||||
getSignificance: withThreshold(FineIf.LessThan, 150)(getDefaultSignificance),
|
||||
},
|
||||
completionsStdDev: {
|
||||
columnName: "Std. deviation (ms)",
|
||||
sentenceName: "standard deviation of the durations for getting completions at a position",
|
||||
getValue: x => x.completions.standardDeviation,
|
||||
getSignificance: getInsignificant
|
||||
getValue: (x) => x.completions.standardDeviation,
|
||||
getSignificance: getInsignificant,
|
||||
},
|
||||
completionsAvgCV: {
|
||||
columnName: "Mean [CV](https://en.wikipedia.org/wiki/Coefficient_of_variation)",
|
||||
sentenceName: "mean coefficient of variation of samples measured for completions time",
|
||||
getValue: x => x.completions.meanCoefficientOfVariation,
|
||||
getValue: (x) => x.completions.meanCoefficientOfVariation,
|
||||
getSignificance: getInsignificant,
|
||||
formatOptions: { percentage: true, noDiff: true }
|
||||
formatOptions: { percentage: true, noDiff: true },
|
||||
},
|
||||
completionsWorstMean: {
|
||||
columnName: "Worst duration (ms)",
|
||||
sentenceName: "worst-case duration for getting completions at a position",
|
||||
getValue: x => mean(x.completions.worst.completionsDurations),
|
||||
getSignificance: withThreshold(FineIf.LessThan, 200)(getDefaultSignificance)
|
||||
getValue: (x) => mean(x.completions.worst.completionsDurations),
|
||||
getSignificance: withThreshold(FineIf.LessThan, 200)(getDefaultSignificance),
|
||||
},
|
||||
quickInfoMean: {
|
||||
columnName: "Mean duration (ms)",
|
||||
sentenceName: "mean duration for getting quick info at a position",
|
||||
getValue: x => x.quickInfo.mean,
|
||||
getSignificance: withThreshold(FineIf.LessThan, 150)(getDefaultSignificance)
|
||||
getValue: (x) => x.quickInfo.mean,
|
||||
getSignificance: withThreshold(FineIf.LessThan, 150)(getDefaultSignificance),
|
||||
},
|
||||
quickInfoStdDev: {
|
||||
columnName: "Std. deviation (ms)",
|
||||
sentenceName: "standard deviation of the durations for getting quick info at a position",
|
||||
getValue: x => x.quickInfo.standardDeviation,
|
||||
getSignificance: getInsignificant
|
||||
getValue: (x) => x.quickInfo.standardDeviation,
|
||||
getSignificance: getInsignificant,
|
||||
},
|
||||
quickInfoAvgCV: {
|
||||
columnName: "Mean [CV](https://en.wikipedia.org/wiki/Coefficient_of_variation)",
|
||||
sentenceName: "mean coefficient of variation of samples measured for quick info time",
|
||||
getValue: x => x.quickInfo.meanCoefficientOfVariation,
|
||||
getValue: (x) => x.quickInfo.meanCoefficientOfVariation,
|
||||
getSignificance: getInsignificant,
|
||||
formatOptions: { percentage: true, noDiff: true }
|
||||
formatOptions: { percentage: true, noDiff: true },
|
||||
},
|
||||
quickInfoWorstMean: {
|
||||
columnName: "Worst duration (ms)",
|
||||
sentenceName: "worst-case duration for getting quick info at a position",
|
||||
getValue: x => mean(x.quickInfo.worst.quickInfoDurations),
|
||||
getSignificance: withThreshold(FineIf.LessThan, 200)(getDefaultSignificance)
|
||||
}
|
||||
getValue: (x) => mean(x.quickInfo.worst.quickInfoDurations),
|
||||
getSignificance: withThreshold(FineIf.LessThan, 200)(getDefaultSignificance),
|
||||
},
|
||||
};
|
||||
|
||||
export interface ComparedMetric {
|
||||
|
||||
@@ -8,7 +8,7 @@ export enum OverallChange {
|
||||
Same = 0,
|
||||
Worse = 1 << 0,
|
||||
Better = 1 << 1,
|
||||
Mixed = Worse | Better
|
||||
Mixed = Worse | Better,
|
||||
}
|
||||
|
||||
export function getOverallChangeForSingleComparison(before: PackageBenchmarkSummary, after: PackageBenchmarkSummary) {
|
||||
|
||||
@@ -17,7 +17,7 @@ export function summarize(benchmark: PackageBenchmark): PackageBenchmarkSummary
|
||||
testIdentifierCount: benchmark.testIdentifierCount,
|
||||
requestedLanguageServiceTestIterations: benchmark.requestedLanguageServiceTestIterations,
|
||||
languageServiceCrashed: benchmark.languageServiceCrashed,
|
||||
...summarizeStats(benchmark.languageServiceBenchmarks)
|
||||
...summarizeStats(benchmark.languageServiceBenchmarks),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ export function summarizeStats(
|
||||
): Pick<PackageBenchmarkSummary, "quickInfo" | "completions"> {
|
||||
return [
|
||||
["completions", (benchmark: LanguageServiceBenchmark) => benchmark.completionsDurations] as const,
|
||||
["quickInfo", (benchmark: LanguageServiceBenchmark) => benchmark.quickInfoDurations] as const
|
||||
["quickInfo", (benchmark: LanguageServiceBenchmark) => benchmark.quickInfoDurations] as const,
|
||||
].reduce((acc, [key, getDurations]) => {
|
||||
const [means, cvs] = benchmarks.reduce(
|
||||
(acc, b) => {
|
||||
@@ -38,19 +38,19 @@ export function summarizeStats(
|
||||
[[], []] as [number[], number[]]
|
||||
);
|
||||
|
||||
const worst = max(benchmarks, b => mean(getDurations(b)));
|
||||
const worst = max(benchmarks, (b) => mean(getDurations(b)));
|
||||
const stats: StatSummary<LanguageServiceBenchmark> = {
|
||||
mean: mean(means),
|
||||
median: median(means),
|
||||
standardDeviation: stdDev(means),
|
||||
meanCoefficientOfVariation: mean(cvs),
|
||||
trials: means.length,
|
||||
worst
|
||||
worst,
|
||||
};
|
||||
|
||||
return {
|
||||
...acc,
|
||||
[key]: stats
|
||||
[key]: stats,
|
||||
};
|
||||
}, {} as Record<"completions" | "quickInfo", StatSummary<LanguageServiceBenchmark>>);
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
PackageId,
|
||||
formatDependencyVersion,
|
||||
tryParsePackageVersion,
|
||||
AllPackages
|
||||
AllPackages,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
const currentSystem = getSystemInfo();
|
||||
|
||||
@@ -45,7 +45,7 @@ function convertArgs({ file, ...args }: BenchmarkPackageOptions): BenchmarkPacka
|
||||
groups: fileContents.groups,
|
||||
...fileContents.options,
|
||||
...args,
|
||||
failOnErrors: false
|
||||
failOnErrors: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -93,7 +93,7 @@ export async function benchmarkPackage(
|
||||
failOnErrors,
|
||||
installTypeScript,
|
||||
localTypeScriptPath,
|
||||
allPackages = (await getParsedPackages(definitelyTypedPath)).allPackages
|
||||
allPackages = (await getParsedPackages(definitelyTypedPath)).allPackages,
|
||||
} = options;
|
||||
const versionQuery = tryParsePackageVersion(packageVersion);
|
||||
const typings = allPackages.tryGetTypingsData({ name: packageName, version: versionQuery });
|
||||
@@ -115,7 +115,7 @@ export async function benchmarkPackage(
|
||||
tsPath,
|
||||
ts,
|
||||
batchRunStart,
|
||||
failOnErrors
|
||||
failOnErrors,
|
||||
});
|
||||
|
||||
const summary = summarize(benchmark);
|
||||
|
||||
@@ -5,7 +5,7 @@ import {
|
||||
PackageBenchmarkSummary,
|
||||
getParsedPackages,
|
||||
shuffle,
|
||||
forEachWithTimeLimit
|
||||
forEachWithTimeLimit,
|
||||
} from "../common";
|
||||
import { benchmarkPackage } from "./benchmark";
|
||||
import { printSummary } from "../measure";
|
||||
@@ -40,7 +40,7 @@ export async function compare({
|
||||
maxRunSeconds,
|
||||
runDependents,
|
||||
comment,
|
||||
upload
|
||||
upload,
|
||||
}: CompareArgs) {
|
||||
const { allPackages } = await getParsedPackages(definitelyTypedPath);
|
||||
const changedPackages = await getChangedPackages({ diffTo: "origin/master", definitelyTypedPath });
|
||||
@@ -57,7 +57,7 @@ export async function compare({
|
||||
const { overtime } = await forEachWithTimeLimit(
|
||||
maxRunMs,
|
||||
affectedPackages.changedPackages,
|
||||
async affectedPackage => {
|
||||
async (affectedPackage) => {
|
||||
console.log(`Comparing ${affectedPackage.id.name}/v${affectedPackage.major} because it changed...\n\n`);
|
||||
comparisons.push(
|
||||
await compareBenchmarks({
|
||||
@@ -67,11 +67,11 @@ export async function compare({
|
||||
packageName: affectedPackage.id.name,
|
||||
packageVersion: affectedPackage.id.version,
|
||||
maxRunSeconds,
|
||||
upload
|
||||
upload,
|
||||
})
|
||||
);
|
||||
},
|
||||
affectedPackage => {
|
||||
(affectedPackage) => {
|
||||
console.log(`Skipping ${affectedPackage.id.name} because we ran out of time`);
|
||||
}
|
||||
);
|
||||
@@ -82,7 +82,7 @@ export async function compare({
|
||||
const message = await postInitialComparisonResults({
|
||||
comparisons,
|
||||
dependentCount: dependentsToTest.length,
|
||||
dryRun: !comment
|
||||
dryRun: !comment,
|
||||
});
|
||||
if (message) {
|
||||
console.log("\n" + message + "\n");
|
||||
@@ -93,7 +93,7 @@ export async function compare({
|
||||
await forEachWithTimeLimit(
|
||||
maxRunMs,
|
||||
dependentsToTest,
|
||||
async affectedPackage => {
|
||||
async (affectedPackage) => {
|
||||
console.log(
|
||||
`Comparing ${affectedPackage.id.name}/v${affectedPackage.major} because it depends on something that changed...\n\n`
|
||||
);
|
||||
@@ -105,11 +105,11 @@ export async function compare({
|
||||
packageName: affectedPackage.id.name,
|
||||
packageVersion: affectedPackage.id.version,
|
||||
maxRunSeconds,
|
||||
upload
|
||||
upload,
|
||||
})
|
||||
);
|
||||
},
|
||||
affectedPackage => {
|
||||
(affectedPackage) => {
|
||||
console.log(`Skipping ${affectedPackage.id.name} because we ran out of time`);
|
||||
}
|
||||
);
|
||||
@@ -126,7 +126,7 @@ export async function compareBenchmarks({
|
||||
typeScriptVersionMajorMinor,
|
||||
packageName,
|
||||
packageVersion,
|
||||
maxRunSeconds
|
||||
maxRunSeconds,
|
||||
}: CompareOptions): Promise<[PackageBenchmarkSummary, PackageBenchmarkSummary]> {
|
||||
await execAndThrowErrors("git checkout -f origin/master && git clean -xdf types", definitelyTypedPath);
|
||||
const baseBenchmark = (
|
||||
@@ -140,7 +140,7 @@ export async function compareBenchmarks({
|
||||
nProcesses: os.cpus().length,
|
||||
failOnErrors: true,
|
||||
installTypeScript: false,
|
||||
maxRunSeconds
|
||||
maxRunSeconds,
|
||||
})
|
||||
)?.summary;
|
||||
|
||||
@@ -159,7 +159,7 @@ export async function compareBenchmarks({
|
||||
nProcesses: os.cpus().length,
|
||||
failOnErrors: true,
|
||||
installTypeScript: false,
|
||||
maxRunSeconds
|
||||
maxRunSeconds,
|
||||
}))!.summary;
|
||||
|
||||
if (baseBenchmark) {
|
||||
|
||||
@@ -8,38 +8,38 @@ import { compare } from "./compare";
|
||||
const maxRunSeconds = {
|
||||
type: "number",
|
||||
requiresArg: true,
|
||||
description: "limits the total run time of the benchmark"
|
||||
description: "limits the total run time of the benchmark",
|
||||
} as const;
|
||||
|
||||
const upload = {
|
||||
type: "boolean",
|
||||
description: "uploads benchmark results to a database",
|
||||
default: true
|
||||
default: true,
|
||||
} as const;
|
||||
|
||||
const file = {
|
||||
type: "string",
|
||||
requiresArg: true,
|
||||
description: "a path to a JSON file specifying run options"
|
||||
description: "a path to a JSON file specifying run options",
|
||||
} as const;
|
||||
|
||||
const definitelyTypedPath = {
|
||||
type: "string",
|
||||
requiresArg: true,
|
||||
description: "the directory of the DefinitelyTyped repository",
|
||||
default: process.cwd()
|
||||
default: process.cwd(),
|
||||
} as const;
|
||||
|
||||
const localTypeScriptPath = {
|
||||
type: "string",
|
||||
description: "path to a locally built TypeScript installation",
|
||||
default: path.resolve("built/local")
|
||||
default: path.resolve("built/local"),
|
||||
} as const;
|
||||
|
||||
const tsVersion = {
|
||||
type: "string",
|
||||
description: "the TypeScript major/minor version to use for the measurements",
|
||||
default: "next"
|
||||
default: "next",
|
||||
} as const;
|
||||
|
||||
void yargs
|
||||
@@ -53,38 +53,38 @@ void yargs
|
||||
progress: {
|
||||
type: "boolean",
|
||||
description: "logs progress updates during benchmarking",
|
||||
default: false
|
||||
default: false,
|
||||
},
|
||||
iterations: {
|
||||
type: "number",
|
||||
requiresArg: true,
|
||||
description: "the number of times to measure the package",
|
||||
default: 5
|
||||
default: 5,
|
||||
},
|
||||
nProcesses: {
|
||||
type: "number",
|
||||
requiresArg: true,
|
||||
description: "splits the measurment iterations across multiple child processes",
|
||||
default: os.cpus().length
|
||||
default: os.cpus().length,
|
||||
},
|
||||
maxRunSeconds,
|
||||
printSummary: {
|
||||
type: "boolean",
|
||||
description: "logs a benchmark summary before exiting",
|
||||
default: true
|
||||
default: true,
|
||||
},
|
||||
definitelyTypedPath,
|
||||
failOnErrors: {
|
||||
type: "boolean",
|
||||
description: "exits with a non-zero code if a measurement process crashes",
|
||||
default: true
|
||||
default: true,
|
||||
},
|
||||
installTypeScript: {
|
||||
type: "boolean",
|
||||
description: "installs TypeScript before running measurements",
|
||||
default: true
|
||||
default: true,
|
||||
},
|
||||
localTypeScriptPath
|
||||
localTypeScriptPath,
|
||||
},
|
||||
benchmark
|
||||
)
|
||||
@@ -95,13 +95,13 @@ void yargs
|
||||
definitelyTypedPath,
|
||||
tsVersion: {
|
||||
...tsVersion,
|
||||
demandOption: true
|
||||
demandOption: true,
|
||||
},
|
||||
maxRunSeconds,
|
||||
upload,
|
||||
comment: {
|
||||
type: "boolean",
|
||||
description: "leave a typescript-bot comment on the associated DefinitelyTyped PR"
|
||||
description: "leave a typescript-bot comment on the associated DefinitelyTyped PR",
|
||||
},
|
||||
runDependents: {
|
||||
description: "also compare packages dependent upon the modified packages",
|
||||
@@ -112,14 +112,14 @@ void yargs
|
||||
if (r === true) return 2;
|
||||
if (r === false) return false;
|
||||
return r;
|
||||
}
|
||||
}
|
||||
},
|
||||
},
|
||||
},
|
||||
compare
|
||||
)
|
||||
.help().argv;
|
||||
|
||||
process.on("unhandledRejection", err => {
|
||||
process.on("unhandledRejection", (err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@ import { assertDefined } from "@definitelytyped/utils";
|
||||
|
||||
export const config = {
|
||||
benchmarks: {
|
||||
languageServiceIterations: 5
|
||||
languageServiceIterations: 5,
|
||||
},
|
||||
github: {
|
||||
userAgent: "definitely-not-slow",
|
||||
@@ -15,12 +15,12 @@ export const config = {
|
||||
},
|
||||
commonParams: {
|
||||
owner: "DefinitelyTyped",
|
||||
repo: "DefinitelyTyped"
|
||||
}
|
||||
repo: "DefinitelyTyped",
|
||||
},
|
||||
},
|
||||
comparison: {
|
||||
percentDiffWarningThreshold: 0.2,
|
||||
percentDiffAlertThreshold: 1,
|
||||
percentDiffAwesomeThreshold: -0.25
|
||||
}
|
||||
percentDiffAwesomeThreshold: -0.25,
|
||||
},
|
||||
};
|
||||
|
||||
@@ -4,21 +4,19 @@ import {
|
||||
typesDataFilename,
|
||||
getLocallyInstalledDefinitelyTyped,
|
||||
dataFilePath,
|
||||
parseDefinitions
|
||||
parseDefinitions,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
import { FS, consoleLogger } from "@definitelytyped/utils";
|
||||
import { getSourceVersion, pathExists } from "./utils";
|
||||
|
||||
let parsedSourceVersion: string | undefined;
|
||||
export async function getParsedPackages(
|
||||
definitelyTypedPath: string
|
||||
): Promise<{
|
||||
export async function getParsedPackages(definitelyTypedPath: string): Promise<{
|
||||
definitelyTypedFS: FS;
|
||||
allPackages: AllPackages;
|
||||
}> {
|
||||
const currentSourceVersion = await getSourceVersion(definitelyTypedPath);
|
||||
const definitelyTypedFS = getLocallyInstalledDefinitelyTyped(definitelyTypedPath);
|
||||
const isDebugging = process.execArgv.some(arg => arg.startsWith("--inspect"));
|
||||
const isDebugging = process.execArgv.some((arg) => arg.startsWith("--inspect"));
|
||||
const needsReparse = !parsedSourceVersion || parsedSourceVersion !== currentSourceVersion;
|
||||
if (process.env.NODE_ENV === "production" || needsReparse || !(await pathExists(dataFilePath(typesDataFilename)))) {
|
||||
await parseDefinitions(
|
||||
@@ -27,7 +25,7 @@ export async function getParsedPackages(
|
||||
? undefined
|
||||
: {
|
||||
definitelyTypedPath,
|
||||
nProcesses: os.cpus().length
|
||||
nProcesses: os.cpus().length,
|
||||
},
|
||||
consoleLogger
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
formatDependencyVersion,
|
||||
DirectoryParsedTypingVersion,
|
||||
tryParsePackageVersion,
|
||||
PackageIdWithDefiniteVersion
|
||||
PackageIdWithDefiniteVersion,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
|
||||
export const pathExists = promisify(fs.exists);
|
||||
@@ -23,7 +23,7 @@ export function ensureExists(...pathNames: string[]): string {
|
||||
return pathName;
|
||||
}
|
||||
}
|
||||
const pathNamesPrint = pathNames.length > 1 ? "\n" + pathNames.map(s => ` - ${s}`).join("\n") : `'${pathNames[0]}`;
|
||||
const pathNamesPrint = pathNames.length > 1 ? "\n" + pathNames.map((s) => ` - ${s}`).join("\n") : `'${pathNames[0]}`;
|
||||
throw new Error(`File or directory does not exist: ${pathNamesPrint}`);
|
||||
}
|
||||
|
||||
@@ -52,14 +52,12 @@ export function getSystemInfo(): SystemInfo {
|
||||
platform: os.platform(),
|
||||
release: os.release(),
|
||||
totalmem: os.totalmem(),
|
||||
nodeVersion: process.version
|
||||
nodeVersion: process.version,
|
||||
};
|
||||
|
||||
return {
|
||||
...info,
|
||||
hash: createHash("md5")
|
||||
.update(JSON.stringify(info))
|
||||
.digest("hex")
|
||||
hash: createHash("md5").update(JSON.stringify(info)).digest("hex"),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -72,14 +70,14 @@ export interface GetChangedPackagesOptions {
|
||||
export async function getChangedPackages({
|
||||
diffFrom = "HEAD",
|
||||
diffTo,
|
||||
definitelyTypedPath
|
||||
definitelyTypedPath,
|
||||
}: GetChangedPackagesOptions) {
|
||||
const diff = await execAndThrowErrors(`git diff --name-status ${diffFrom} ${diffTo}`, definitelyTypedPath);
|
||||
if (!diff) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const changes = diff.split("\n").map(line => {
|
||||
const changes = diff.split("\n").map((line) => {
|
||||
const [status, file] = line.split(/\s+/, 2);
|
||||
return { status: status.trim() as "A" | "D" | "M", file: file.trim() };
|
||||
});
|
||||
@@ -135,12 +133,12 @@ export function toPackageKey(
|
||||
typeof packageIdOrName === "string"
|
||||
? {
|
||||
name: packageIdOrName,
|
||||
version: (typeof version === "string" ? tryParsePackageVersion(version) : version) || ("*" as const)
|
||||
version: (typeof version === "string" ? tryParsePackageVersion(version) : version) || ("*" as const),
|
||||
}
|
||||
: isVersionedBenchmark(packageIdOrName)
|
||||
? {
|
||||
name: packageIdOrName.packageName,
|
||||
version: { major: packageIdOrName.packageVersionMajor, minor: packageIdOrName.packageVersionMinor }
|
||||
version: { major: packageIdOrName.packageVersionMajor, minor: packageIdOrName.packageVersionMinor },
|
||||
}
|
||||
: packageIdOrName;
|
||||
|
||||
@@ -204,6 +202,6 @@ export async function forEachWithTimeLimit<T>(
|
||||
startTime,
|
||||
duration,
|
||||
overtime: duration > limitMs,
|
||||
complete
|
||||
complete,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ export function createComparisonTable(
|
||||
"Worst identifier",
|
||||
before,
|
||||
after,
|
||||
x =>
|
||||
(x) =>
|
||||
sourceLink(
|
||||
x.completions.worst.identifierText,
|
||||
x.sourceVersion,
|
||||
@@ -46,7 +46,7 @@ export function createComparisonTable(
|
||||
"Worst identifier",
|
||||
before,
|
||||
after,
|
||||
x =>
|
||||
(x) =>
|
||||
sourceLink(
|
||||
x.quickInfo.worst.identifierText,
|
||||
x.sourceVersion,
|
||||
@@ -55,7 +55,7 @@ export function createComparisonTable(
|
||||
),
|
||||
undefined,
|
||||
{ indent: 1 }
|
||||
)
|
||||
),
|
||||
])
|
||||
);
|
||||
}
|
||||
@@ -77,7 +77,7 @@ export function createSingleRunTable(benchmark: PackageBenchmarkSummary) {
|
||||
createSingleRunRow(
|
||||
"Worst identifier",
|
||||
benchmark,
|
||||
x =>
|
||||
(x) =>
|
||||
sourceLink(
|
||||
x.completions.worst.identifierText,
|
||||
x.sourceVersion,
|
||||
@@ -93,7 +93,7 @@ export function createSingleRunTable(benchmark: PackageBenchmarkSummary) {
|
||||
createSingleRunRow(
|
||||
"Worst identifier",
|
||||
benchmark,
|
||||
x =>
|
||||
(x) =>
|
||||
sourceLink(
|
||||
x.quickInfo.worst.identifierText,
|
||||
x.sourceVersion,
|
||||
@@ -101,7 +101,7 @@ export function createSingleRunTable(benchmark: PackageBenchmarkSummary) {
|
||||
x.quickInfo.worst.line
|
||||
),
|
||||
{ indent: 1 }
|
||||
)
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -146,7 +146,7 @@ function createSingleRunRowFromMetric(
|
||||
) {
|
||||
return createSingleRunRow(metric.columnName, benchmark, metric.getValue, {
|
||||
...metric.formatOptions,
|
||||
...formatOptions
|
||||
...formatOptions,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ function createComparisonRow(
|
||||
indent(title, formatOptions.indent || 0),
|
||||
format(aValue, formatOptions),
|
||||
format(bValue, formatOptions),
|
||||
diff || ""
|
||||
diff || "",
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
@@ -16,7 +16,7 @@ export function createTablesWithAnalysesMessage(
|
||||
before
|
||||
? createComparisonTable(before, after, getBeforeTitle(before, after), getAfterTitle(before, after, prNumber))
|
||||
: createSingleRunTable(after),
|
||||
``
|
||||
``,
|
||||
].join("\n");
|
||||
|
||||
return compact([
|
||||
@@ -29,7 +29,7 @@ export function createTablesWithAnalysesMessage(
|
||||
``,
|
||||
shouldCollapseDetails ? details(messageBody, getDetailsSummaryTitle(pairs.length, after)) : messageBody,
|
||||
``,
|
||||
interestingMetrics && getInterestingMetricsMessage(interestingMetrics)
|
||||
interestingMetrics && getInterestingMetricsMessage(interestingMetrics),
|
||||
]).join("\n");
|
||||
})
|
||||
.join("\n\n");
|
||||
@@ -95,7 +95,7 @@ function getInterestingMetricsMessage(interestingMetrics: readonly ComparedMetri
|
||||
);
|
||||
return (
|
||||
`Looks like there were a couple significant differences—take a look at ` +
|
||||
formatListForSentence(metricsToCheck.map(m => `**${m.metric.sentenceName}**`)) +
|
||||
formatListForSentence(metricsToCheck.map((m) => `**${m.metric.sentenceName}**`)) +
|
||||
` to make sure everything looks ok.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ export function getOctokit() {
|
||||
octokit ||
|
||||
(octokit = new Octokit({
|
||||
auth: config.github.typeScriptBotAuthToken,
|
||||
userAgent: config.github.userAgent
|
||||
userAgent: config.github.userAgent,
|
||||
}))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ export async function postDependentsComparisonResult({ comparisons, dryRun }: Po
|
||||
`Ok, I’m back! As promised, here are the results from dependent packages`,
|
||||
``,
|
||||
createTablesWithAnalysesMessage(comparisons, parseInt(process.env.SYSTEM_PULLREQUEST_PULLREQUESTNUMBER || "")),
|
||||
true
|
||||
true,
|
||||
]).join("\n");
|
||||
|
||||
if (!dryRun) {
|
||||
@@ -36,10 +36,10 @@ export async function postDependentsComparisonResult({ comparisons, dryRun }: Po
|
||||
issue_number: prNumber,
|
||||
body: createPerfCommentBody(
|
||||
{
|
||||
overallChange: getOverallChangeForComparisons(comparisons)
|
||||
overallChange: getOverallChangeForComparisons(comparisons),
|
||||
},
|
||||
message
|
||||
)
|
||||
),
|
||||
});
|
||||
} catch (err) {
|
||||
console.log(message);
|
||||
|
||||
@@ -17,7 +17,7 @@ export interface PostInitialComparisonResultsOptions {
|
||||
export async function postInitialComparisonResults({
|
||||
comparisons,
|
||||
dependentCount,
|
||||
dryRun
|
||||
dryRun,
|
||||
}: PostInitialComparisonResultsOptions) {
|
||||
let message;
|
||||
if (dryRun) {
|
||||
@@ -38,13 +38,13 @@ export async function postInitialComparisonResults({
|
||||
const octokit = getOctokit();
|
||||
const comments = await octokit.issues.listComments({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber
|
||||
issue_number: prNumber,
|
||||
});
|
||||
|
||||
const currentOverallChange = getOverallChangeForComparisons(comparisons);
|
||||
const mostRecentComment = findLast(comments.data, isPerfComment);
|
||||
const commentData: CommentData = {
|
||||
overallChange: currentOverallChange
|
||||
overallChange: currentOverallChange,
|
||||
};
|
||||
if (mostRecentComment) {
|
||||
const lastOverallChange = getCommentData(mostRecentComment)?.overallChange;
|
||||
@@ -69,14 +69,14 @@ export async function postInitialComparisonResults({
|
||||
await octokit.issues.createComment({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber,
|
||||
body: createPerfCommentBody(commentData, message)
|
||||
body: createPerfCommentBody(commentData, message),
|
||||
});
|
||||
} else {
|
||||
message = getFullFirstPostMessage(createTablesWithAnalysesMessage(comparisons, prNumber), dependentCount);
|
||||
await octokit.issues.createComment({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber,
|
||||
body: createPerfCommentBody(commentData, message)
|
||||
body: createPerfCommentBody(commentData, message),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -96,7 +96,7 @@ function getFullFirstPostMessage(mainMessage: string, dependentCount: number): s
|
||||
``,
|
||||
`Let’s review the numbers, shall we?`,
|
||||
``,
|
||||
mainMessage
|
||||
mainMessage,
|
||||
]).join("\n");
|
||||
}
|
||||
|
||||
@@ -110,7 +110,7 @@ function getConciseUpdateMessage(
|
||||
return [
|
||||
`Updated numbers for you here from ${sha.slice(0, 7)}. ${gotBetter ? "Nice job, these numbers look better." : ""}`,
|
||||
``,
|
||||
mainMessage
|
||||
mainMessage,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -27,19 +27,19 @@ export async function setLabels(prNumber: number, overallChange: OverallChange |
|
||||
const octokit = getOctokit();
|
||||
const labels = await octokit.issues.listLabelsOnIssue({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber
|
||||
issue_number: prNumber,
|
||||
});
|
||||
|
||||
const perfLabels = labels.data.filter(isPerfLabel);
|
||||
const newLabel = toLabel(overallChange);
|
||||
const labelsToRemove = perfLabels.filter(l => l.name !== newLabel);
|
||||
const labelToAdd = perfLabels.some(l => l.name === newLabel) ? undefined : newLabel;
|
||||
const labelsToRemove = perfLabels.filter((l) => l.name !== newLabel);
|
||||
const labelToAdd = perfLabels.some((l) => l.name === newLabel) ? undefined : newLabel;
|
||||
|
||||
for (const label of labelsToRemove) {
|
||||
await octokit.issues.removeLabel({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber,
|
||||
name: label.name
|
||||
name: label.name,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ export async function setLabels(prNumber: number, overallChange: OverallChange |
|
||||
await octokit.issues.addLabels({
|
||||
...config.github.commonParams,
|
||||
issue_number: prNumber,
|
||||
labels: [labelToAdd]
|
||||
labels: [labelToAdd],
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ export function createLanguageServiceHost(
|
||||
getScriptFileNames: () => testPaths,
|
||||
fileExists: ts.sys.fileExists,
|
||||
getDirectories: ts.sys.getDirectories,
|
||||
getScriptSnapshot: fileName => ts.ScriptSnapshot.fromString(ts.sys.readFile(ensureExists(fileName))!),
|
||||
getScriptVersion: () => (version++).toString()
|
||||
getScriptSnapshot: (fileName) => ts.ScriptSnapshot.fromString(ts.sys.readFile(ensureExists(fileName))!),
|
||||
getScriptVersion: () => (version++).toString(),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ import * as os from "os";
|
||||
import { FormatDiagnosticsHost } from "typescript";
|
||||
|
||||
export const formatDiagnosticsHost: FormatDiagnosticsHost = {
|
||||
getCanonicalFileName: fileName => fileName,
|
||||
getCanonicalFileName: (fileName) => fileName,
|
||||
getNewLine: () => os.EOL,
|
||||
getCurrentDirectory: () => process.cwd()
|
||||
getCurrentDirectory: () => process.cwd(),
|
||||
};
|
||||
|
||||
@@ -17,9 +17,9 @@ export function getParsedCommandLineForPackage(
|
||||
readDirectory: ts.sys.readDirectory,
|
||||
readFile: ts.sys.readFile,
|
||||
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
|
||||
onUnRecoverableConfigFileDiagnostic: diagnostic => {
|
||||
onUnRecoverableConfigFileDiagnostic: (diagnostic) => {
|
||||
console.error(ts.formatDiagnostic(diagnostic, formatDiagnosticsHost));
|
||||
}
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
installAllTypeScriptVersions,
|
||||
typeScriptPath,
|
||||
cleanTypeScriptInstalls,
|
||||
installTypeScriptNext
|
||||
installTypeScriptNext,
|
||||
} from "@definitelytyped/utils";
|
||||
const exists = promisify(fs.exists);
|
||||
|
||||
@@ -29,6 +29,6 @@ export async function getTypeScript(
|
||||
}
|
||||
return {
|
||||
ts: await import(tsPath),
|
||||
tsPath
|
||||
tsPath,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -11,7 +11,7 @@ export async function installDependencies(
|
||||
): Promise<void> {
|
||||
const { changedPackages, dependentPackages } = getAffectedPackages(allPackages, [packageId]);
|
||||
const dependencies = allDependencies(allPackages, [...changedPackages, ...dependentPackages]);
|
||||
await nAtATime(Math.min(os.cpus().length, 6), dependencies, async typingsData => {
|
||||
await nAtATime(Math.min(os.cpus().length, 6), dependencies, async (typingsData) => {
|
||||
const packagePath = path.join(typesPath, typingsData.name);
|
||||
if (!(await pathExists(path.join(packagePath, "package.json")))) {
|
||||
return;
|
||||
|
||||
@@ -23,7 +23,7 @@ if (!module.parent) {
|
||||
process.on("message", async ([message]: MeasureBatchCompilationChildProcessArgs[]) => {
|
||||
const ts: typeof import("typescript") = await import(message.tsPath);
|
||||
const program = ts.createProgram({ rootNames: message.fileNames, options: message.options });
|
||||
const diagnostics = program.getSemanticDiagnostics().filter(diagnostic => {
|
||||
const diagnostics = program.getSemanticDiagnostics().filter((diagnostic) => {
|
||||
return diagnostic.code === 2307; // Cannot find module
|
||||
});
|
||||
if (diagnostics.length) {
|
||||
@@ -34,13 +34,13 @@ if (!module.parent) {
|
||||
const result: MeasureBatchCompilationChildProcessResult = {
|
||||
typeCount: (program as any).getTypeCount(),
|
||||
memoryUsage: ts.sys.getMemoryUsage!(),
|
||||
relationCacheSizes: (program as any).getRelationCacheSizes && (program as any).getRelationCacheSizes()
|
||||
relationCacheSizes: (program as any).getRelationCacheSizes && (program as any).getRelationCacheSizes(),
|
||||
};
|
||||
|
||||
process.send!(result);
|
||||
});
|
||||
|
||||
process.on("unhandledRejection", err => {
|
||||
process.on("unhandledRejection", (err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
|
||||
@@ -49,7 +49,7 @@ if (!module.parent) {
|
||||
}
|
||||
});
|
||||
|
||||
process.on("unhandledRejection", err => {
|
||||
process.on("unhandledRejection", (err) => {
|
||||
console.error(err);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -62,7 +62,7 @@ async function measureLanguageService(
|
||||
return {
|
||||
fileName: args.fileName,
|
||||
start: args.start,
|
||||
...(await measureAtPosition(args.fileName, args.start))
|
||||
...(await measureAtPosition(args.fileName, args.start)),
|
||||
};
|
||||
|
||||
async function measureAtPosition(
|
||||
@@ -71,7 +71,7 @@ async function measureLanguageService(
|
||||
): Promise<Pick<LanguageServiceSingleMeasurement, "quickInfoDuration" | "completionsDuration">> {
|
||||
let quickInfoDuration = NaN;
|
||||
let completionsDuration = NaN;
|
||||
const observer = new PerformanceObserver(list => {
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
const completionsMeasurement = list.getEntriesByName("completionsMeasurement")[0];
|
||||
const quickInfoMeasurement = list.getEntriesByName("quickInfoMeasurement")[0];
|
||||
if (completionsMeasurement) {
|
||||
@@ -87,14 +87,14 @@ async function measureLanguageService(
|
||||
getQuickInfoAtPosition(languageService, fileName, position);
|
||||
// Node 16 changed the PerformanceObserver callback to happen async,
|
||||
// so we have to sit here and wait for it...
|
||||
await new Promise(resolve => setTimeout(resolve, 0));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
assert.ok(!isNaN(quickInfoDuration), "No measurement was recorded for quick info");
|
||||
assert.ok(!isNaN(completionsDuration), "No measurement was recorded for completions");
|
||||
observer.disconnect();
|
||||
|
||||
return {
|
||||
quickInfoDuration,
|
||||
completionsDuration
|
||||
completionsDuration,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,12 +8,12 @@ import { installDependencies } from "./installDependencies";
|
||||
import { getParsedCommandLineForPackage } from "./getParsedCommandLineForPackage";
|
||||
import {
|
||||
measureLanguageServiceWorkerFilename,
|
||||
MeasureLanguageServiceChildProcessArgs
|
||||
MeasureLanguageServiceChildProcessArgs,
|
||||
} from "./measureLanguageServiceWorker";
|
||||
import {
|
||||
MeasureBatchCompilationChildProcessArgs,
|
||||
measureBatchCompilationWorkerFilename,
|
||||
MeasureBatchCompilationChildProcessResult
|
||||
MeasureBatchCompilationChildProcessResult,
|
||||
} from "./measureBatchCompilationWorker";
|
||||
import { AllPackages, HeaderParsedTypingVersion } from "@definitelytyped/definitions-parser";
|
||||
import { runWithListeningChildProcesses, runWithChildProcesses, Semver } from "@definitelytyped/utils";
|
||||
@@ -47,11 +47,11 @@ export async function measurePerf({
|
||||
tsPath,
|
||||
ts,
|
||||
batchRunStart,
|
||||
failOnErrors
|
||||
failOnErrors,
|
||||
}: MeasurePerfOptions) {
|
||||
let duration = NaN;
|
||||
const sourceVersion = execSync("git rev-parse HEAD", { cwd: definitelyTypedRootPath, encoding: "utf8" }).trim();
|
||||
const observer = new PerformanceObserver(list => {
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
const totalMeasurement = list.getEntriesByName("benchmark")[0];
|
||||
duration = totalMeasurement.duration;
|
||||
});
|
||||
@@ -62,7 +62,7 @@ export async function measurePerf({
|
||||
|
||||
const typings = allPackages.getTypingsData({
|
||||
name: packageName,
|
||||
version: packageVersion
|
||||
version: packageVersion,
|
||||
});
|
||||
const packagePath = path.join(typesPath, typings.subDirectoryPath);
|
||||
const typesVersion = getLatestTypesVersionForTypeScriptVersion(typings.typesVersions, typeScriptVersion);
|
||||
@@ -92,7 +92,7 @@ export async function measurePerf({
|
||||
crashRecovery: !failOnErrors,
|
||||
cwd: process.cwd(),
|
||||
softTimeoutMs: maxRunSeconds * 1000,
|
||||
handleCrash: input => {
|
||||
handleCrash: (input) => {
|
||||
languageServiceCrashed = true;
|
||||
console.error("Failed measurement on request:", JSON.stringify(input, undefined, 2));
|
||||
},
|
||||
@@ -110,7 +110,7 @@ export async function measurePerf({
|
||||
console.log(((100 * done) / testMatrix.inputs.length).toFixed(1) + "% done...");
|
||||
lastUpdate = Date.now();
|
||||
}
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (progress && done !== testMatrix.inputs.length) {
|
||||
@@ -121,7 +121,7 @@ export async function measurePerf({
|
||||
const batchCompilationInput: MeasureBatchCompilationChildProcessArgs = {
|
||||
tsPath,
|
||||
fileNames: commandLine.fileNames,
|
||||
options: commandLine.options
|
||||
options: commandLine.options,
|
||||
};
|
||||
|
||||
let batchCompilationResult: MeasureBatchCompilationChildProcessResult | undefined;
|
||||
@@ -132,7 +132,7 @@ export async function measurePerf({
|
||||
nProcesses: 1,
|
||||
handleOutput: (result: MeasureBatchCompilationChildProcessResult) => {
|
||||
batchCompilationResult = result;
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
if (!batchCompilationResult) {
|
||||
@@ -155,7 +155,7 @@ export async function measurePerf({
|
||||
requestedLanguageServiceTestIterations: iterations,
|
||||
languageServiceCrashed,
|
||||
testIdentifierCount: testMatrix.uniquePositionCount,
|
||||
batchRunStart
|
||||
batchRunStart,
|
||||
};
|
||||
|
||||
return measurement;
|
||||
@@ -173,7 +173,7 @@ export async function measurePerf({
|
||||
}
|
||||
|
||||
function getTestFileNames(fileNames: readonly string[]) {
|
||||
return fileNames.filter(name => {
|
||||
return fileNames.filter((name) => {
|
||||
const ext = path.extname(name);
|
||||
return (ext === Extension.Ts || ext === Extension.Tsx) && !name.endsWith(Extension.Dts);
|
||||
});
|
||||
@@ -216,7 +216,7 @@ export async function measurePerf({
|
||||
line: lineAndCharacter.line + 1,
|
||||
offset: lineAndCharacter.character + 1,
|
||||
completionsDurations: [],
|
||||
quickInfoDurations: []
|
||||
quickInfoDurations: [],
|
||||
};
|
||||
positionMap.set(start, benchmark);
|
||||
}
|
||||
@@ -224,7 +224,7 @@ export async function measurePerf({
|
||||
fileName: testPath,
|
||||
start,
|
||||
packageDirectory,
|
||||
tsPath
|
||||
tsPath,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -241,13 +241,13 @@ export async function measurePerf({
|
||||
return Array.prototype.concat
|
||||
.apply(
|
||||
[],
|
||||
Array.from(fileMap.values()).map(map => Array.from(map.values()))
|
||||
Array.from(fileMap.values()).map((map) => Array.from(map.values()))
|
||||
)
|
||||
.filter(
|
||||
(benchmark: LanguageServiceBenchmark) =>
|
||||
benchmark.completionsDurations.length > 0 || benchmark.quickInfoDurations.length > 0
|
||||
);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,8 +26,9 @@ export function printSummary(summaries: PackageBenchmarkSummary[]) {
|
||||
console.log(" Completions");
|
||||
console.log(
|
||||
" Trials ",
|
||||
`${completions.trials} (sampled from ${benchmark.testIdentifierCount *
|
||||
benchmark.requestedLanguageServiceTestIterations})`
|
||||
`${completions.trials} (sampled from ${
|
||||
benchmark.testIdentifierCount * benchmark.requestedLanguageServiceTestIterations
|
||||
})`
|
||||
);
|
||||
console.log(" Mean (ms): ", toPrecision(completions.mean, 6));
|
||||
console.log(" Median (ms): ", toPrecision(completions.median, 6));
|
||||
@@ -47,8 +48,9 @@ export function printSummary(summaries: PackageBenchmarkSummary[]) {
|
||||
console.log(" Quick Info");
|
||||
console.log(
|
||||
" Trials ",
|
||||
`${quickInfo.trials} (sampled from ${benchmark.testIdentifierCount *
|
||||
benchmark.requestedLanguageServiceTestIterations})`
|
||||
`${quickInfo.trials} (sampled from ${
|
||||
benchmark.testIdentifierCount * benchmark.requestedLanguageServiceTestIterations
|
||||
})`
|
||||
);
|
||||
console.log(" Mean (ms): ", toPrecision(quickInfo.mean, 6));
|
||||
console.log(" Median (ms): ", toPrecision(quickInfo.median, 6));
|
||||
|
||||
@@ -23,7 +23,7 @@ export function stdDev(xs: number[]): number {
|
||||
|
||||
export function variance(xs: number[]): number {
|
||||
const avg = mean(xs);
|
||||
return mean(xs.map(x => (avg - x) ** 2));
|
||||
return mean(xs.map((x) => (avg - x) ** 2));
|
||||
}
|
||||
|
||||
export function coefficientOfVariation(xs: number[]): number {
|
||||
|
||||
@@ -11,7 +11,7 @@ describe("github", () => {
|
||||
expect(
|
||||
getCommentData({
|
||||
body: commentBody,
|
||||
user: { login: config.github.typeScriptBotUsername } as IssuesListResponseItemUser
|
||||
user: { login: config.github.typeScriptBotUsername } as IssuesListResponseItemUser,
|
||||
})
|
||||
).toEqual(data);
|
||||
});
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
LoggerWithErrors,
|
||||
UncachedNpmInfoClient,
|
||||
withNpmCache,
|
||||
CachedNpmInfoClient
|
||||
CachedNpmInfoClient,
|
||||
} from "@definitelytyped/utils";
|
||||
import { fetchTypesPackageVersionInfo } from "@definitelytyped/retag";
|
||||
import { cacheDirPath } from "./lib/settings";
|
||||
@@ -30,7 +30,7 @@ export default async function calculateVersions(
|
||||
log.info("=== Calculating versions ===");
|
||||
return withNpmCache(
|
||||
uncachedClient,
|
||||
async client => {
|
||||
async (client) => {
|
||||
log.info("* Reading packages...");
|
||||
const packages = await AllPackages.read(dt);
|
||||
return computeAndSaveChangedPackages(packages, log, client);
|
||||
@@ -49,7 +49,7 @@ async function computeAndSaveChangedPackages(
|
||||
changedTypings: cp.changedTypings.map(
|
||||
({ pkg: { id }, version, latestVersion }): ChangedTypingJson => ({ id, version, latestVersion })
|
||||
),
|
||||
changedNotNeededPackages: cp.changedNotNeededPackages.map(p => p.name)
|
||||
changedNotNeededPackages: cp.changedNotNeededPackages.map((p) => p.name),
|
||||
};
|
||||
await writeDataFile(versionsFilename, json);
|
||||
return cp;
|
||||
@@ -61,7 +61,7 @@ async function computeChangedPackages(
|
||||
client: CachedNpmInfoClient
|
||||
): Promise<ChangedPackages> {
|
||||
log.info("# Computing changed packages...");
|
||||
const changedTypings = await mapDefinedAsync(allPackages.allTypings(), async pkg => {
|
||||
const changedTypings = await mapDefinedAsync(allPackages.allTypings(), async (pkg) => {
|
||||
const { version, needsPublish } = await fetchTypesPackageVersionInfo(pkg, client, /*publish*/ true, log);
|
||||
if (needsPublish) {
|
||||
log.info(`Need to publish: ${pkg.desc}@${version}`);
|
||||
@@ -79,7 +79,7 @@ async function computeChangedPackages(
|
||||
return undefined;
|
||||
});
|
||||
log.info("# Computing deprecated packages...");
|
||||
const changedNotNeededPackages = await mapDefinedAsync(allPackages.allNotNeeded(), async pkg => {
|
||||
const changedNotNeededPackages = await mapDefinedAsync(allPackages.allNotNeeded(), async (pkg) => {
|
||||
if (!(await isAlreadyDeprecated(pkg, client, log))) {
|
||||
assertDefined(
|
||||
await client.fetchAndCacheNpmInfo(pkg.libraryName),
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
ProgressBar,
|
||||
strProgress,
|
||||
UncachedNpmInfoClient,
|
||||
npmRegistry
|
||||
npmRegistry,
|
||||
} from "@definitelytyped/utils";
|
||||
import { defaultLocalOptions } from "./lib/common";
|
||||
import { ParseDefinitionsOptions, writeDataFile, packageHasTypes } from "@definitelytyped/definitions-parser";
|
||||
@@ -24,11 +24,11 @@ async function main(options: ParseDefinitionsOptions): Promise<void> {
|
||||
const allTyped = await filterNAtATimeOrdered(
|
||||
10,
|
||||
all,
|
||||
pkg => packageHasTypes(pkg, client),
|
||||
(pkg) => packageHasTypes(pkg, client),
|
||||
options.progress
|
||||
? {
|
||||
name: "Checking for types...",
|
||||
flavor: (name, isTyped) => (isTyped ? name : undefined)
|
||||
flavor: (name, isTyped) => (isTyped ? name : undefined),
|
||||
}
|
||||
: undefined
|
||||
);
|
||||
@@ -59,7 +59,7 @@ function allNpmPackages(): Promise<string[]> {
|
||||
progress.done();
|
||||
resolve(all);
|
||||
})
|
||||
.fail(err => {
|
||||
.fail((err) => {
|
||||
reject(err.thrown);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -63,7 +63,7 @@ async function createSearchRecords(
|
||||
g: pkg.globals,
|
||||
t: pkg.name,
|
||||
m: pkg.declaredModules,
|
||||
d: dl[i]
|
||||
d: dl[i],
|
||||
})
|
||||
)
|
||||
.sort((a, b) => b.d - a.d);
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
loggerWithErrors,
|
||||
LoggerWithErrors,
|
||||
assertDefined,
|
||||
UncachedNpmInfoClient
|
||||
UncachedNpmInfoClient,
|
||||
} from "@definitelytyped/utils";
|
||||
import { numberOfOsProcesses } from "./util/util";
|
||||
import { defaultLocalOptions } from "./lib/common";
|
||||
|
||||
@@ -20,7 +20,7 @@ import {
|
||||
writeTgz,
|
||||
withNpmCache,
|
||||
UncachedNpmInfoClient,
|
||||
CachedNpmInfoClient
|
||||
CachedNpmInfoClient,
|
||||
} from "@definitelytyped/utils";
|
||||
import {
|
||||
getDefinitelyTyped,
|
||||
@@ -32,7 +32,7 @@ import {
|
||||
getFullNpmName,
|
||||
DependencyVersion,
|
||||
License,
|
||||
formatTypingVersion
|
||||
formatTypingVersion,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
import { readChangedPackages, ChangedPackages } from "./lib/versions";
|
||||
import { outputDirectory } from "./util/util";
|
||||
@@ -72,7 +72,7 @@ export default async function generatePackages(
|
||||
log("## Generating deprecated packages");
|
||||
await withNpmCache(
|
||||
new UncachedNpmInfoClient(),
|
||||
async client => {
|
||||
async (client) => {
|
||||
for (const pkg of changedPackages.changedNotNeededPackages) {
|
||||
log(` * ${pkg.libraryName}`);
|
||||
await generateNotNeededPackage(pkg, client, log);
|
||||
@@ -96,7 +96,7 @@ async function generateTypingPackage(
|
||||
|
||||
await writeCommonOutputs(typing, createPackageJSON(typing, version, packages), createReadme(typing, packageFS));
|
||||
await Promise.all(
|
||||
typing.files.map(async file => writeFile(await outputFilePath(typing, file), packageFS.readFile(file)))
|
||||
typing.files.map(async (file) => writeFile(await outputFilePath(typing, file), packageFS.readFile(file)))
|
||||
);
|
||||
}
|
||||
|
||||
@@ -119,7 +119,7 @@ async function writeCommonOutputs(pkg: AnyPackage, packageJson: string, readme:
|
||||
await Promise.all([
|
||||
writeOutputFile("package.json", packageJson),
|
||||
writeOutputFile("README.md", readme),
|
||||
writeOutputFile("LICENSE", getLicenseFileText(pkg))
|
||||
writeOutputFile("LICENSE", getLicenseFileText(pkg)),
|
||||
]);
|
||||
|
||||
async function writeOutputFile(filename: string, content: string): Promise<void> {
|
||||
@@ -157,12 +157,12 @@ export function createPackageJSON(typing: TypingsData, version: string, packages
|
||||
repository: {
|
||||
type: "git",
|
||||
url: "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||
directory: `types/${typing.name}`
|
||||
directory: `types/${typing.name}`,
|
||||
},
|
||||
scripts: {},
|
||||
dependencies: getDependencies(typing.packageJsonDependencies, typing, packages),
|
||||
typesPublisherContentHash: typing.contentHash,
|
||||
typeScriptVersion: typing.minTypeScriptVersion
|
||||
typeScriptVersion: typing.minTypeScriptVersion,
|
||||
};
|
||||
const exports = typing.exports;
|
||||
if (exports) {
|
||||
@@ -197,7 +197,7 @@ function getDependencies(
|
||||
const typesDependency = getFullNpmName(name);
|
||||
// A dependency "foo" is already handled if we already have a dependency on the package "foo" or "@types/foo".
|
||||
if (
|
||||
!packageJsonDependencies.some(d => d.name === name || d.name === typesDependency) &&
|
||||
!packageJsonDependencies.some((d) => d.name === name || d.name === typesDependency) &&
|
||||
allPackages.hasTypingFor({ name, version })
|
||||
) {
|
||||
dependencies[typesDependency] = dependencySemver(version);
|
||||
@@ -222,8 +222,8 @@ export function createNotNeededPackageJSON({ libraryName, license, fullNpmName,
|
||||
license,
|
||||
// No `typings`, that's provided by the dependency.
|
||||
dependencies: {
|
||||
[libraryName]: "*"
|
||||
}
|
||||
[libraryName]: "*",
|
||||
},
|
||||
};
|
||||
return JSON.stringify(out, undefined, 4);
|
||||
}
|
||||
@@ -260,10 +260,10 @@ export function createReadme(typing: TypingsData, packageFS: FS): string {
|
||||
const dependencies = Object.keys(typing.dependencies).map(getFullNpmName);
|
||||
lines.push(
|
||||
` * Dependencies: ${
|
||||
dependencies.length ? dependencies.map(d => `[${d}](https://npmjs.com/package/${d})`).join(", ") : "none"
|
||||
dependencies.length ? dependencies.map((d) => `[${d}](https://npmjs.com/package/${d})`).join(", ") : "none"
|
||||
}`
|
||||
);
|
||||
lines.push(` * Global values: ${typing.globals.length ? typing.globals.map(g => `\`${g}\``).join(", ") : "none"}`);
|
||||
lines.push(` * Global values: ${typing.globals.length ? typing.globals.map((g) => `\`${g}\``).join(", ") : "none"}`);
|
||||
lines.push("");
|
||||
|
||||
lines.push("# Credits");
|
||||
@@ -290,7 +290,7 @@ export function getLicenseFileText(typing: AnyPackage): string {
|
||||
|
||||
function apacheLicense(typing: TypingsData): string {
|
||||
const year = new Date().getFullYear();
|
||||
const names = typing.contributors.map(c => c.name);
|
||||
const names = typing.contributors.map((c) => c.name);
|
||||
// tslint:disable max-line-length
|
||||
return `Copyright ${year} ${names.join(", ")}
|
||||
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
|
||||
|
||||
@@ -14,11 +14,11 @@ export interface TesterOptions extends ParseDefinitionsOptions {
|
||||
export const defaultLocalOptions: TesterOptions = {
|
||||
definitelyTypedPath: "../../../DefinitelyTyped",
|
||||
progress: true,
|
||||
parseInParallel: true
|
||||
parseInParallel: true,
|
||||
};
|
||||
|
||||
export const defaultRemoteOptions: ParseDefinitionsOptions = {
|
||||
definitelyTypedPath: undefined,
|
||||
progress: false,
|
||||
parseInParallel: false
|
||||
parseInParallel: false,
|
||||
};
|
||||
|
||||
@@ -18,11 +18,11 @@ export enum Secret {
|
||||
*
|
||||
* We only need one token in existence, so delete old tokens at: https://www.npmjs.com/settings/tokens
|
||||
*/
|
||||
NPM_TOKEN
|
||||
NPM_TOKEN,
|
||||
}
|
||||
|
||||
export const allSecrets: Secret[] = mapDefined(Object.keys(Secret), key => {
|
||||
const value = ((Secret as unknown) as { [key: string]: unknown })[key];
|
||||
export const allSecrets: Secret[] = mapDefined(Object.keys(Secret), (key) => {
|
||||
const value = (Secret as unknown as { [key: string]: unknown })[key];
|
||||
return typeof value === "number" ? value : undefined; // tslint:disable-line strict-type-predicates (tslint bug)
|
||||
});
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
NotNeededPackage,
|
||||
PackageId,
|
||||
TypingsData,
|
||||
readDataFile
|
||||
readDataFile,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
|
||||
export const versionsFilename = "versions.json";
|
||||
@@ -40,11 +40,11 @@ export async function readChangedPackages(allPackages: AllPackages): Promise<Cha
|
||||
({ id, version, latestVersion }): ChangedTyping => ({
|
||||
pkg: allPackages.getTypingsData(id),
|
||||
version,
|
||||
latestVersion
|
||||
latestVersion,
|
||||
})
|
||||
),
|
||||
changedNotNeededPackages: json.changedNotNeededPackages.map(id =>
|
||||
changedNotNeededPackages: json.changedNotNeededPackages.map((id) =>
|
||||
assertDefined(allPackages.getNotNeededPackage(id))
|
||||
)
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ export default function main() {
|
||||
{
|
||||
definitelyTypedPath: undefined,
|
||||
parseInParallel: false,
|
||||
progress: false
|
||||
progress: false,
|
||||
},
|
||||
log
|
||||
);
|
||||
@@ -59,10 +59,10 @@ export async function withFileLock(lockFilePath: string, cb: () => Promise<void>
|
||||
await writeFile(lockFilePath, JSON.stringify({ timestamp: currentTimeStamp() }));
|
||||
cb().then(
|
||||
() => remove(lockFilePath),
|
||||
async error => {
|
||||
async (error) => {
|
||||
console.error(error?.stack || error?.message || error);
|
||||
applicationinsights.defaultClient.trackException({
|
||||
exception: error
|
||||
exception: error,
|
||||
});
|
||||
|
||||
await remove(lockFilePath);
|
||||
|
||||
@@ -7,13 +7,13 @@ import {
|
||||
getDefinitelyTyped,
|
||||
parseDefinitions,
|
||||
writeDataFile,
|
||||
typesDataFilename
|
||||
typesDataFilename,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
|
||||
if (!module.parent) {
|
||||
const { nProcesses, single: singleName } = yargs.options({
|
||||
single: { type: "string" },
|
||||
nProcesses: { type: "number" }
|
||||
nProcesses: { type: "number" },
|
||||
}).argv;
|
||||
|
||||
const options = defaultLocalOptions;
|
||||
@@ -28,7 +28,7 @@ if (!module.parent) {
|
||||
options.parseInParallel
|
||||
? {
|
||||
nProcesses: nProcesses || os.cpus().length,
|
||||
definitelyTypedPath: assertDefined(options.definitelyTypedPath)
|
||||
definitelyTypedPath: assertDefined(options.definitelyTypedPath),
|
||||
}
|
||||
: undefined,
|
||||
log
|
||||
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
writeLog,
|
||||
NpmPublishClient,
|
||||
withNpmCache,
|
||||
UncachedNpmInfoClient
|
||||
UncachedNpmInfoClient,
|
||||
} from "@definitelytyped/utils";
|
||||
import { readChangedPackages, ChangedPackages } from "./lib/versions";
|
||||
import { skipBadPublishes } from "./lib/npm";
|
||||
@@ -133,8 +133,8 @@ export default async function publishPackages(
|
||||
latency: latency.toString(),
|
||||
commitLatency: commitlatency.toString(),
|
||||
authorCommit: commits[0].sha,
|
||||
pr: latestPr.toString()
|
||||
}
|
||||
pr: latestPr.toString(),
|
||||
},
|
||||
});
|
||||
applicationinsights.defaultClient.trackMetric({ name: "publish latency", value: latency });
|
||||
applicationinsights.defaultClient.trackMetric({ name: "author commit latency", value: commitlatency });
|
||||
@@ -145,7 +145,7 @@ export default async function publishPackages(
|
||||
|
||||
await withNpmCache(
|
||||
new UncachedNpmInfoClient(),
|
||||
async infoClient => {
|
||||
async (infoClient) => {
|
||||
for (const n of changedPackages.changedNotNeededPackages) {
|
||||
const target = skipBadPublishes(n, infoClient, log);
|
||||
await publishNotNeededPackage(client, target, dry, log);
|
||||
@@ -172,8 +172,8 @@ async function postGithub(path: string, data: any, githubToken: string, fetcher:
|
||||
"User-Agent": "types-publisher",
|
||||
"Content-Type": "application/json",
|
||||
Authorization: "token " + githubToken,
|
||||
"Content-Length": Buffer.byteLength(body)
|
||||
}
|
||||
"Content-Length": Buffer.byteLength(body),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -186,7 +186,7 @@ async function queryGithub(path: string, githubToken: string, fetcher: Fetcher)
|
||||
path: path + "&access_token=" + githubToken,
|
||||
headers: {
|
||||
// arbitrary string, but something must be provided
|
||||
"User-Agent": "types-publisher"
|
||||
}
|
||||
"User-Agent": "types-publisher",
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -9,7 +9,7 @@ import {
|
||||
AllPackages,
|
||||
readNotNeededPackages,
|
||||
NotNeededPackage,
|
||||
TypingsData
|
||||
TypingsData,
|
||||
} from "@definitelytyped/definitions-parser";
|
||||
import {
|
||||
assertDefined,
|
||||
@@ -34,7 +34,7 @@ import {
|
||||
withNpmCache,
|
||||
NpmPublishClient,
|
||||
CachedNpmInfoClient,
|
||||
isObject
|
||||
isObject,
|
||||
} from "@definitelytyped/utils";
|
||||
import { getSecret, Secret } from "./lib/secrets";
|
||||
|
||||
@@ -70,7 +70,7 @@ export default async function publishRegistry(
|
||||
// Don't include not-needed packages in the registry.
|
||||
const registryJsonData = await withNpmCache(
|
||||
client,
|
||||
cachedClient => generateRegistry(allPackages.allLatestTypings(), cachedClient),
|
||||
(cachedClient) => generateRegistry(allPackages.allLatestTypings(), cachedClient),
|
||||
cacheDirPath
|
||||
);
|
||||
const registry = JSON.stringify(registryJsonData);
|
||||
@@ -163,7 +163,7 @@ async function installForValidate(log: Logger): Promise<void> {
|
||||
description: "description",
|
||||
readme: "",
|
||||
license: "",
|
||||
repository: {}
|
||||
repository: {},
|
||||
});
|
||||
|
||||
const cmd = `npm install types-registry@next ${npmInstallFlags}`;
|
||||
@@ -190,7 +190,7 @@ async function validateIsSubset(notNeeded: readonly NotNeededPackage[], log: Log
|
||||
const actual = (await readJson(joinPaths(validateTypesRegistryPath, indexJson))) as Registry;
|
||||
const expected = (await readJson(joinPaths(registryOutputPath, indexJson))) as Registry;
|
||||
for (const key of Object.keys(actual.entries)) {
|
||||
if (!(key in expected.entries) && !notNeeded.some(p => p.name === key)) {
|
||||
if (!(key in expected.entries) && !notNeeded.some((p) => p.name === key)) {
|
||||
throw new Error(`Actual types-registry has unexpected key ${key}`);
|
||||
}
|
||||
}
|
||||
@@ -235,12 +235,12 @@ function generatePackageJson(name: string, version: string, typesPublisherConten
|
||||
description: "A registry of TypeScript declaration file packages published within the @types scope.",
|
||||
repository: {
|
||||
type: "git",
|
||||
url: "https://github.com/Microsoft/types-publisher.git"
|
||||
url: "https://github.com/Microsoft/types-publisher.git",
|
||||
},
|
||||
keywords: ["TypeScript", "declaration", "files", "types", "packages"],
|
||||
author: "Microsoft Corp.",
|
||||
license: "MIT",
|
||||
typesPublisherContentHash
|
||||
typesPublisherContentHash,
|
||||
};
|
||||
return json;
|
||||
}
|
||||
@@ -259,8 +259,8 @@ async function generateRegistry(typings: readonly TypingsData[], client: CachedN
|
||||
const info = client.getNpmInfoFromCache(typing.fullEscapedNpmName);
|
||||
if (!info) {
|
||||
const missings = typings
|
||||
.filter(t => !client.getNpmInfoFromCache(t.fullEscapedNpmName))
|
||||
.map(t => t.fullEscapedNpmName);
|
||||
.filter((t) => !client.getNpmInfoFromCache(t.fullEscapedNpmName))
|
||||
.map((t) => t.fullEscapedNpmName);
|
||||
throw new Error(`${missings.toString()} not found in cached npm info.`);
|
||||
}
|
||||
entries[typing.name] = filterTags(info.distTags);
|
||||
@@ -301,7 +301,7 @@ async function fetchAndProcessNpmInfo(
|
||||
}
|
||||
function getLatestVersion(versions: Iterable<string>): Semver {
|
||||
return best(
|
||||
mapDefined(versions, v => Semver.tryParse(v)),
|
||||
mapDefined(versions, (v) => Semver.tryParse(v)),
|
||||
(a, b) => a.greaterThan(b)
|
||||
)!;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { AzureFunction, Context } from "@azure/functions";
|
||||
import main from "../main";
|
||||
|
||||
const httpTrigger: AzureFunction = async function(context: Context): Promise<void> {
|
||||
const httpTrigger: AzureFunction = async function (context: Context): Promise<void> {
|
||||
context.log("HTTP trigger function processed a request.");
|
||||
const triggerResult = await main();
|
||||
if (!triggerResult.triggered) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user