mirror of
https://github.com/elastic/kibana.git
synced 2025-06-27 18:51:07 -04:00
Transpile packages on demand, validate all TS projects (#146212)
## Dearest Reviewers 👋 I've been working on this branch with @mistic and @tylersmalley and we're really confident in these changes. Additionally, this changes code in nearly every package in the repo so we don't plan to wait for reviews to get in before merging this. If you'd like to have a concern addressed, please feel free to leave a review, but assuming that nobody raises a blocker in the next 24 hours we plan to merge this EOD pacific tomorrow, 12/22. We'll be paying close attention to any issues this causes after merging and work on getting those fixed ASAP. 🚀 --- The operations team is not confident that we'll have the time to achieve what we originally set out to accomplish by moving to Bazel with the time and resources we have available. We have also bought ourselves some headroom with improvements to babel-register, optimizer caching, and typescript project structure. In order to make sure we deliver packages as quickly as possible (many teams really want them), with a usable and familiar developer experience, this PR removes Bazel for building packages in favor of using the same JIT transpilation we use for plugins. Additionally, packages now use `kbn_references` (again, just copying the dx from plugins to packages). Because of the complex relationships between packages/plugins and in order to prepare ourselves for automatic dependency detection tools we plan to use in the future, this PR also introduces a "TS Project Linter" which will validate that every tsconfig.json file meets a few requirements: 1. the chain of base config files extended by each config includes `tsconfig.base.json` and not `tsconfig.json` 1. the `include` config is used, and not `files` 2. the `exclude` config includes `target/**/*` 3. the `outDir` compiler option is specified as `target/types` 1. none of these compiler options are specified: `declaration`, `declarationMap`, `emitDeclarationOnly`, `skipLibCheck`, `target`, `paths` 4. all references to other packages/plugins use their pkg id, ie: ```js // valid { "kbn_references": ["@kbn/core"] } // not valid { "kbn_references": [{ "path": "../../../src/core/tsconfig.json" }] } ``` 5. only packages/plugins which are imported somewhere in the ts code are listed in `kbn_references` This linter is not only validating all of the tsconfig.json files, but it also will fix these config files to deal with just about any violation that can be produced. Just run `node scripts/ts_project_linter --fix` locally to apply these fixes, or let CI take care of automatically fixing things and pushing the changes to your PR. > **Example:** [`64e93e5
` (#146212)](64e93e5806
) When I merged main into my PR it included a change which removed the `@kbn/core-injected-metadata-browser` package. After resolving the conflicts I missed a few tsconfig files which included references to the now removed package. The TS Project Linter identified that these references were removed from the code and pushed a change to the PR to remove them from the tsconfig.json files. ## No bazel? Does that mean no packages?? Nope! We're still doing packages but we're pretty sure now that we won't be using Bazel to accomplish the 'distributed caching' and 'change-based tasks' portions of the packages project. This PR actually makes packages much easier to work with and will be followed up with the bundling benefits described by the original packages RFC. Then we'll work on documentation and advocacy for using packages for any and all new code. We're pretty confident that implementing distributed caching and change-based tasks will be necessary in the future, but because of recent improvements in the repo we think we can live without them for **at least** a year. ## Wait, there are still BUILD.bazel files in the repo Yes, there are still three webpack bundles which are built by Bazel: the `@kbn/ui-shared-deps-npm` DLL, `@kbn/ui-shared-deps-src` externals, and the `@kbn/monaco` workers. These three webpack bundles are still created during bootstrap and remotely cached using bazel. The next phase of this project is to figure out how to get the package bundling features described in the RFC with the current optimizer, and we expect these bundles to go away then. Until then any package that is used in those three bundles still needs to have a BUILD.bazel file so that they can be referenced by the remaining webpack builds. Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
parent
e9c5c16bfd
commit
afb09ccf8a
2421 changed files with 17782 additions and 110627 deletions
|
@ -1,130 +0,0 @@
|
|||
load("@npm//@bazel/typescript:index.bzl", "ts_config")
|
||||
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
|
||||
load("//src/dev/bazel:index.bzl", "jsts_transpiler", "pkg_npm", "pkg_npm_types", "ts_project")
|
||||
|
||||
PKG_DIRNAME = "kbn-find-used-node-modules"
|
||||
PKG_REQUIRE_NAME = "@kbn/find-used-node-modules"
|
||||
|
||||
SOURCE_FILES = glob(
|
||||
[
|
||||
"**/*.ts",
|
||||
],
|
||||
exclude = [
|
||||
"**/*.config.js",
|
||||
"**/*.mock.*",
|
||||
"**/*.test.*",
|
||||
"**/*.stories.*",
|
||||
"**/__snapshots__/**",
|
||||
"**/integration_tests/**",
|
||||
"**/mocks/**",
|
||||
"**/scripts/**",
|
||||
"**/storybook/**",
|
||||
"**/test_fixtures/**",
|
||||
"**/test_helpers/**",
|
||||
],
|
||||
)
|
||||
|
||||
SRCS = SOURCE_FILES
|
||||
|
||||
filegroup(
|
||||
name = "srcs",
|
||||
srcs = SRCS,
|
||||
)
|
||||
|
||||
NPM_MODULE_EXTRA_FILES = [
|
||||
"package.json",
|
||||
]
|
||||
|
||||
# In this array place runtime dependencies, including other packages and NPM packages
|
||||
# which must be available for this code to run.
|
||||
#
|
||||
# To reference other packages use:
|
||||
# "//repo/relative/path/to/package"
|
||||
# eg. "//packages/kbn-utils"
|
||||
#
|
||||
# To reference a NPM package use:
|
||||
# "@npm//name-of-package"
|
||||
# eg. "@npm//lodash"
|
||||
RUNTIME_DEPS = [
|
||||
"//packages/kbn-babel-preset",
|
||||
"@npm//@babel/core",
|
||||
"@npm//@babel/types",
|
||||
"@npm//@babel/traverse",
|
||||
]
|
||||
|
||||
# In this array place dependencies necessary to build the types, which will include the
|
||||
# :npm_module_types target of other packages and packages from NPM, including @types/*
|
||||
# packages.
|
||||
#
|
||||
# To reference the types for another package use:
|
||||
# "//repo/relative/path/to/package:npm_module_types"
|
||||
# eg. "//packages/kbn-utils:npm_module_types"
|
||||
#
|
||||
# References to NPM packages work the same as RUNTIME_DEPS
|
||||
TYPES_DEPS = [
|
||||
"//packages/kbn-import-resolver:npm_module_types",
|
||||
"@npm//@types/node",
|
||||
"@npm//@types/jest",
|
||||
"@npm//@types/babel__core",
|
||||
"@npm//@babel/traverse",
|
||||
"@npm//@babel/types",
|
||||
]
|
||||
|
||||
jsts_transpiler(
|
||||
name = "target_node",
|
||||
srcs = SRCS,
|
||||
build_pkg_name = package_name(),
|
||||
)
|
||||
|
||||
ts_config(
|
||||
name = "tsconfig",
|
||||
src = "tsconfig.json",
|
||||
deps = [
|
||||
"//:tsconfig.base.json",
|
||||
"//:tsconfig.bazel.json",
|
||||
],
|
||||
)
|
||||
|
||||
ts_project(
|
||||
name = "tsc_types",
|
||||
args = ['--pretty'],
|
||||
srcs = SRCS,
|
||||
deps = TYPES_DEPS,
|
||||
declaration = True,
|
||||
emit_declaration_only = True,
|
||||
out_dir = "target_types",
|
||||
tsconfig = ":tsconfig",
|
||||
)
|
||||
|
||||
js_library(
|
||||
name = PKG_DIRNAME,
|
||||
srcs = NPM_MODULE_EXTRA_FILES,
|
||||
deps = RUNTIME_DEPS + [":target_node"],
|
||||
package_name = PKG_REQUIRE_NAME,
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
js_library(
|
||||
name = "npm_module_types",
|
||||
srcs = NPM_MODULE_EXTRA_FILES,
|
||||
deps = RUNTIME_DEPS + [":target_node", ":tsc_types"],
|
||||
package_name = PKG_REQUIRE_NAME,
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
pkg_npm(
|
||||
name = "npm_module",
|
||||
deps = [":" + PKG_DIRNAME],
|
||||
)
|
||||
|
||||
filegroup(
|
||||
name = "build",
|
||||
srcs = [":npm_module"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
||||
|
||||
pkg_npm(
|
||||
name = "build_types",
|
||||
deps = [":npm_module_types"],
|
||||
visibility = ["//visibility:public"],
|
||||
)
|
|
@ -2,7 +2,5 @@
|
|||
"type": "shared-common",
|
||||
"id": "@kbn/find-used-node-modules",
|
||||
"devOnly": true,
|
||||
"owner": "@elastic/kibana-operations",
|
||||
"runtimeDeps": [],
|
||||
"typeDeps": []
|
||||
"owner": "@elastic/kibana-operations"
|
||||
}
|
||||
|
|
|
@ -2,7 +2,5 @@
|
|||
"name": "@kbn/find-used-node-modules",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"main": "./target_node/index.js",
|
||||
"license": "SSPL-1.0 OR Elastic License 2.0",
|
||||
"types": "./target_types/index.d.ts"
|
||||
}
|
||||
"license": "SSPL-1.0 OR Elastic License 2.0"
|
||||
}
|
|
@ -6,6 +6,7 @@
|
|||
* Side Public License, v 1.
|
||||
*/
|
||||
|
||||
import * as Rx from 'rxjs';
|
||||
import { findUsedNodeModules } from './find_used_node_modules';
|
||||
import { ImportResolver } from '@kbn/import-resolver';
|
||||
|
||||
|
@ -36,14 +37,16 @@ const RESOLVER = new MockResolver();
|
|||
|
||||
beforeEach(() => {
|
||||
jest.resetAllMocks();
|
||||
jest.requireMock('./fs').readFile.mockImplementation((path: string) => {
|
||||
jest.requireMock('./fs').readFile$.mockImplementation((path: string) => {
|
||||
if (Object.hasOwn(FILES, path)) {
|
||||
return FILES[path];
|
||||
return Rx.of(FILES[path]);
|
||||
}
|
||||
|
||||
const error: any = new Error(`ENOENT, missing file [${path}]`);
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
return Rx.throwError(() => {
|
||||
const error: any = new Error(`ENOENT, missing file [${path}]`);
|
||||
error.code = 'ENOENT';
|
||||
return error;
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
@ -8,27 +8,15 @@
|
|||
|
||||
import Path from 'path';
|
||||
|
||||
import { asyncForEachWithLimit } from '@kbn/std';
|
||||
import * as Rx from 'rxjs';
|
||||
import type { ImportResolver } from '@kbn/import-resolver';
|
||||
|
||||
import { readFile, readFileSync } from './fs';
|
||||
import { getImportRequests } from './get_import_requests';
|
||||
import { readFile$ } from './fs';
|
||||
|
||||
function isObj(v: any): v is Record<string, unknown> {
|
||||
return typeof v === 'object' && v !== null;
|
||||
}
|
||||
|
||||
function getPeerDeps(thisNodeModule: string) {
|
||||
const pkgPath = require.resolve(`${thisNodeModule}/package.json`);
|
||||
const pkg = JSON.parse(readFileSync(pkgPath));
|
||||
|
||||
if (isObj(pkg) && isObj(pkg.peerDependencies)) {
|
||||
return Object.keys(pkg.peerDependencies);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
interface Options {
|
||||
resolver: ImportResolver;
|
||||
entryPaths: string[];
|
||||
|
@ -55,83 +43,130 @@ interface Options {
|
|||
* solve this by scanning the node_modules directory for all the packages which are used but that
|
||||
* was much slower and lead to extra entries in package.json.
|
||||
*/
|
||||
export async function findUsedNodeModules(options: Options) {
|
||||
const queue = new Set<string>(options.entryPaths);
|
||||
const results = new Set<string>();
|
||||
|
||||
import { getImportRequests } from './get_import_requests';
|
||||
|
||||
export async function findUsedNodeModules(options: Options) {
|
||||
const results = new Set<string>();
|
||||
const entryPathsIntoNodeModules = new Map<string, Set<string>>();
|
||||
|
||||
for (const path of queue) {
|
||||
if (Path.extname(path) !== '.js') {
|
||||
continue;
|
||||
}
|
||||
const path$ = new Rx.Subject<string>();
|
||||
|
||||
const dirname = Path.dirname(path);
|
||||
const code = await readFile(path);
|
||||
const reqs = getImportRequests(code);
|
||||
let inputs = 0;
|
||||
let outputs = 0;
|
||||
const promise = Rx.lastValueFrom(
|
||||
path$.pipe(
|
||||
Rx.filter((path) => Path.extname(path) === '.js'),
|
||||
Rx.distinct(),
|
||||
Rx.tap(() => {
|
||||
inputs += 1;
|
||||
}),
|
||||
Rx.mergeMap((path) => readFile$(path, 'utf8').pipe(Rx.map((code) => ({ code, path })))),
|
||||
Rx.mergeMap(async ({ path, code }) => {
|
||||
const reqs = getImportRequests(code);
|
||||
const dirname = Path.dirname(path);
|
||||
|
||||
for (const req of reqs) {
|
||||
// resolve the request to it's actual file on dist
|
||||
const result = options.resolver.resolve(req, dirname);
|
||||
for (const req of reqs) {
|
||||
// resolve the request to it's actual file on dist
|
||||
const result = options.resolver.resolve(req, dirname);
|
||||
|
||||
// ignore non-file resolution results, these represent files which aren't on
|
||||
// the file-system yet (like during the build) built-ins, explicitily ignored
|
||||
// files, and @types only imports
|
||||
if (result?.type !== 'file') {
|
||||
continue;
|
||||
}
|
||||
// ignore non-file resolution results, these represent files which aren't on
|
||||
// the file-system yet (like during the build) built-ins, explicitily ignored
|
||||
// files, and @types only imports
|
||||
if (result?.type !== 'file') {
|
||||
continue;
|
||||
}
|
||||
|
||||
// if the result points to a node_module (or another node_module)...
|
||||
if (result.nodeModule && result.nodeModule !== options.thisNodeModule) {
|
||||
// add it to the results
|
||||
results.add(result.nodeModule);
|
||||
if (result.pkgId) {
|
||||
results.add(result.pkgId);
|
||||
path$.next(result.absolute);
|
||||
continue;
|
||||
}
|
||||
|
||||
// record this absolute path as an entry path into the node module from our entries, if we
|
||||
// need to scan this node_module for used deps we need to know how we access it.
|
||||
const nmEntries = entryPathsIntoNodeModules.get(result.nodeModule);
|
||||
if (!nmEntries) {
|
||||
entryPathsIntoNodeModules.set(result.nodeModule, new Set([result.absolute]));
|
||||
} else {
|
||||
nmEntries.add(result.absolute);
|
||||
// if the result points to a node_module (or another node_module)...
|
||||
if (result.nodeModule && result.nodeModule !== options.thisNodeModule) {
|
||||
// add it to the results
|
||||
results.add(result.nodeModule);
|
||||
|
||||
// record this absolute path as an entry path into the node module from our entries, if we
|
||||
// need to scan this node_module for used deps we need to know how we access it.
|
||||
const nmEntries = entryPathsIntoNodeModules.get(result.nodeModule);
|
||||
if (!nmEntries) {
|
||||
entryPathsIntoNodeModules.set(result.nodeModule, new Set([result.absolute]));
|
||||
} else {
|
||||
nmEntries.add(result.absolute);
|
||||
}
|
||||
}
|
||||
|
||||
// no need to scan node_modules unless they're bazel packages
|
||||
if (
|
||||
!result.nodeModule ||
|
||||
result.nodeModule === options.thisNodeModule ||
|
||||
options.resolver.isBazelPackage(result.nodeModule)
|
||||
) {
|
||||
path$.next(result.absolute);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 40),
|
||||
Rx.tap(() => {
|
||||
outputs += 1;
|
||||
if (inputs === outputs) {
|
||||
path$.complete();
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
// no need to scan node_modules unless they're bazel packages
|
||||
if (
|
||||
!result.nodeModule ||
|
||||
result.nodeModule === options.thisNodeModule ||
|
||||
options.resolver.isBazelPackage(result.nodeModule)
|
||||
) {
|
||||
queue.add(result.absolute);
|
||||
}
|
||||
}
|
||||
for (const path of options.entryPaths) {
|
||||
path$.next(path);
|
||||
}
|
||||
|
||||
await promise;
|
||||
|
||||
if (options.findUsedPeers) {
|
||||
await asyncForEachWithLimit(results, 10, async (dep) => {
|
||||
const entryPaths = entryPathsIntoNodeModules.get(dep);
|
||||
if (!entryPaths?.size) {
|
||||
return;
|
||||
}
|
||||
await Rx.lastValueFrom(
|
||||
Rx.from(results).pipe(
|
||||
Rx.mergeMap((dep) => {
|
||||
const entryPaths = entryPathsIntoNodeModules.get(dep);
|
||||
if (!entryPaths?.size) {
|
||||
return Rx.EMPTY;
|
||||
}
|
||||
|
||||
const peerDeps = getPeerDeps(dep);
|
||||
if (!peerDeps.length) {
|
||||
return;
|
||||
}
|
||||
const pkgPath = require.resolve(`${dep}/package.json`);
|
||||
return readFile$(pkgPath, 'utf8').pipe(
|
||||
Rx.mergeMap((pkgJson) => {
|
||||
const pkg = JSON.parse(pkgJson);
|
||||
|
||||
const usedInside = await findUsedNodeModules({
|
||||
resolver: options.resolver,
|
||||
entryPaths: Array.from(entryPaths),
|
||||
findUsedPeers: false,
|
||||
thisNodeModule: dep,
|
||||
});
|
||||
if (!isObj(pkg) || !isObj(pkg.peerDependencies)) {
|
||||
return Rx.EMPTY;
|
||||
}
|
||||
|
||||
for (const peer of peerDeps) {
|
||||
if (usedInside.includes(peer)) {
|
||||
results.add(peer);
|
||||
}
|
||||
}
|
||||
});
|
||||
const peerDeps = Object.keys(pkg.peerDependencies);
|
||||
if (!peerDeps.length) {
|
||||
return Rx.EMPTY;
|
||||
}
|
||||
|
||||
return Rx.of({ entryPaths, dep, peerDeps });
|
||||
})
|
||||
);
|
||||
}, 50),
|
||||
Rx.concatMap(async ({ entryPaths, dep, peerDeps }) => {
|
||||
const usedInside = await findUsedNodeModules({
|
||||
resolver: options.resolver,
|
||||
entryPaths: Array.from(entryPaths),
|
||||
findUsedPeers: false,
|
||||
thisNodeModule: dep,
|
||||
});
|
||||
|
||||
for (const peer of peerDeps) {
|
||||
if (usedInside.includes(peer)) {
|
||||
results.add(peer);
|
||||
}
|
||||
}
|
||||
})
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
return Array.from(results).sort((a, b) => a.localeCompare(b));
|
||||
|
|
|
@ -7,12 +7,6 @@
|
|||
*/
|
||||
|
||||
import Fs from 'fs';
|
||||
import Fsp from 'fs/promises';
|
||||
import * as Rx from 'rxjs';
|
||||
|
||||
export function readFileSync(path: string) {
|
||||
return Fs.readFileSync(path, 'utf8');
|
||||
}
|
||||
|
||||
export function readFile(path: string) {
|
||||
return Fsp.readFile(path, 'utf8');
|
||||
}
|
||||
export const readFile$ = Rx.bindNodeCallback<[string, BufferEncoding], [string]>(Fs.readFile);
|
||||
|
|
|
@ -8,7 +8,6 @@
|
|||
|
||||
import * as parser from '@babel/parser';
|
||||
import traverse from '@babel/traverse';
|
||||
// @ts-expect-error Not available with types
|
||||
import babelParserOptions from '@kbn/babel-preset/common_babel_parser_options';
|
||||
|
||||
import { importVisitor } from './import_visitor';
|
||||
|
|
|
@ -1,9 +1,7 @@
|
|||
{
|
||||
"extends": "../../tsconfig.bazel.json",
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"compilerOptions": {
|
||||
"declaration": true,
|
||||
"emitDeclarationOnly": true,
|
||||
"outDir": "target_types",
|
||||
"outDir": "target/types",
|
||||
"types": [
|
||||
"jest",
|
||||
"node"
|
||||
|
@ -11,5 +9,12 @@
|
|||
},
|
||||
"include": [
|
||||
"**/*.ts"
|
||||
],
|
||||
"kbn_references": [
|
||||
"@kbn/import-resolver",
|
||||
"@kbn/babel-preset",
|
||||
],
|
||||
"exclude": [
|
||||
"target/**/*",
|
||||
]
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue