Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions changelog.d/npm-type-views.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
### Changed

- **Type checking and linting stage each npm package's type view instead of
its tree.** Each store target declares a view of its tree with the files
TypeScript's resolution reads: `package.json`, JSON, TypeScript sources and
declarations, and JavaScript with no declaration TypeScript tries in its
place. Views sit at the same paths under `node_modules.types/`, with twins
of the edge, hoist and importer links. TsEmit, TsgoCheck, TsgoDeclare and
TsLint stage the views, with the links the lint configuration's `data`
names laid over them as trees; every runtime action stages the trees.
`type_views = False` on a `ts_compile` or `ts_test` restores the trees for
that program, and `--//ts:type_views=false` for every program. Over a monorepo's 1,058
programs, TsgoCheck and TsLint stage a third fewer files and spend 10% less
worker time. `TsInfo` gains `npm_view_files`; a `TsInfo` built without it
makes its dependents' programs read the trees.
49 changes: 49 additions & 0 deletions docs/rules/node-modules.md
Original file line number Diff line number Diff line change
Expand Up @@ -228,6 +228,55 @@ Every `ts_npm_package` carries its snapshot's store as `NpmPackageInfo.store`
member's hub view carries the member's. The importer's links above read it,
and the chain below is where `ts_compile` and `ts_test` find them.

## Type Views

A type checker reads few of a package's files: TypeScript's resolution reads
`package.json`, other JSON, TypeScript sources and declarations, and
JavaScript only where it tries no declaration in its place (`.js` and `.jsx`
without a `.d.ts`, `.mjs` without a `.d.mts`, `.cjs` without a `.d.cts`).
Source maps, assets and the JavaScript a declaration describes are most of a
tree's files, so each store target also declares the tree's type view: the
files that rule keeps, copied by one `NpmTypeView` action
(`tsaction typeview`). JSON stays whole, since a program that sets
`resolveJsonModule` may import any of it.

The views mirror the layout one directory down: every `node_modules/` path
has a twin at the same path under `node_modules.types/`. A view sits at
`node_modules.types/node_modules/.pnpm/<key>/node_modules/<name>` with the
twins of its tree's edge links beside it, the hoist's links have twins under
`node_modules.types/node_modules/.pnpm/node_modules`, and an importer's links
twins at `<importer>/node_modules.types/node_modules/<name>`. A view's walk up
meets the twins of its edges, the hoist and the root importer in the order a
tree's walk meets theirs.

`NpmStoreInfo.view`, `view_links` and `view_transitive`,
`NpmLinkInfo.view_link`, `NpmHoistInfo.view_members` and
`TsInfo.npm_view_files` carry the twins. The type actions of `ts_compile` and
`ts_test` (TsEmit, TsgoCheck, TsgoDeclare and TsLint) stage `npm_view_files` in place of
`npm_files` and name the importers' twins, which tsaction lays at the
importers' `node_modules`; the ownership manifest names the views. The
written tsconfig sits in the output tree, and TypeScript resolves its `types`
entries walking up from there, so a program root on views holds the output
tree as real directories down to each importer's `node_modules`, linked to
its twin, and every other entry linked as before. A source outside every
importer's package walks up past the program root on the full layout, into
the chain's `node_modules` in the output tree; on views the root importer's
twin in the program root holds the chain behind its own names. TsLint's configuration runs under Node, so each importer link its `data`
names is laid over the root importer's twin with its tree, and the rest of
the program stays on views: a target's TsgoCheck and TsLint then share one
input root, which a worker reuses. Runtime actions, tests, bundles, the dev
server, codegen and the editor project read the trees.

A program reads the trees in its type actions when its `type_views`
attribute is False, for a package whose resolution reads a file its views
drop; its dependents keep their own choice. It also reads them when a
first-party dep's `TsInfo` carries no `npm_view_files`, and every program
does under `--//ts:type_views=false`, a build-wide switch for comparisons and
rollback.

Analysis declares the views, their links and the twin links whatever the flag
says; only an action that stages them builds them.

## The Chain

`ts_compile` and `ts_test` build no tree. Each names in `node_modules` the
Expand Down
2 changes: 2 additions & 0 deletions docs/rules/ts-compile.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ flags in `.bazelrc`. Every compiler option is the tsconfig's.
| `tsconfig` | `label` | `None` | The project's own `tsconfig.json`, or a [`ts_config`](#ts_config) target: where every compiler option comes from. See [Where compiler options come from](#where-compiler-options-come-from) |
| `node_modules` | `label` | `None` | The `node_modules` target of the nearest lockfile importer at or above the package: the chain a direct npm dep resolves along. Required when the closure holds an npm package; Gazelle writes it. See [The node_modules Chain](#the-node_modules-chain) |
| `source_node_modules` | `label_list` | `[]` | Importer chains for retained sources, searched alongside `node_modules` for declared store Files. Nearest links and their types companions keep their original importer paths. |
| `type_views` | `bool` | `True` | Stage each npm package's type view in this program's type actions. `False` stages the trees. See [Type Views](node-modules.md#type-views) |

Emission settings otherwise use build flags, one value for every target-configuration build; tools built for the exec configuration use the defaults below:

Expand All @@ -41,6 +42,7 @@ Emission settings otherwise use build flags, one value for every target-configur
| `--//ts:source_map` | `bool` | `True` | Emit a `.js.map` next to every `.js`. See [Source and declaration maps](#source-and-declaration-maps) |
| `--//ts:declaration_map` | `bool` | `False` | Emit a `.d.ts.map` next to every declaration. See [Source and declaration maps](#source-and-declaration-maps) |
| `--//ts:lib_check` | `bool` | `False` | Turn `skipLibCheck` off for every target-configuration target. See [Finding a broken declaration](#finding-a-broken-declaration) |
| `--//ts:type_views` | `bool` | `True` | `False` stages npm trees in every program's type actions, as `type_views = False` does for one. See [Type Views](node-modules.md#type-views) |
| `--//ts:checkers` | `int` | `0` | The threads tsgo checks with: `--checkers N` on TsgoCheck and TsgoDeclare, and `cpu:N` on each so Bazel schedules it as N cpus. `0` leaves tsgo's own count, the four the checkout's `tsc -p` runs with. |
| `--//ts:lint` | `label` | `@lint_config//:lint` | The `lint_config` every target runs as its `TsLint` validation: the one the root module's `ts.lint()` writes. `//ts:no_lint` names no binary, so no target lints. See [Lint](../guides/lint.md) |

Expand Down
68 changes: 65 additions & 3 deletions npm/private/store.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,12 @@ NpmStoreInfo = provider(
"transitive": "depset of File: the tree, its links and every " +
"dependency store's transitive set, a cut edge's " +
"excepted.",
"view": "File: the tree's type view, what a type checker reads of " +
"it, at `node_modules.types/node_modules/.pnpm/<key>/node_modules/<name>`.",
"view_links": "dict of string -> File: the links beside the view, " +
"into the dependencies' views.",
"view_transitive": "depset of File: `transitive` with views and " +
"view links in place of trees and links.",
},
)

Expand Down Expand Up @@ -89,6 +95,27 @@ def store_link(ctx, dir, name, store):
)
return link

TYPES_DIR = "node_modules.types"

def types_path(path):
"""The package-relative path of a `node_modules/` path's twin in the type
views' layout, the same path under `node_modules.types/`: a view's walk
up then meets the twins of the hoist and the importer's links where a
tree's meets theirs."""
if path != "node_modules" and not path.startswith("node_modules/"):
fail("types_path: {} is not under node_modules".format(path))
return TYPES_DIR + "/" + path
Comment thread
aronstrandberg marked this conversation as resolved.
Resolved

def store_view_link(ctx, dir, name, store):
"""The twin of `store_link(ctx, dir, name, store)` in the views' layout,
into `store`'s view."""
link = ctx.actions.declare_symlink(types_path("{}/{}".format(dir, name)))
ctx.actions.symlink(
output = link,
target_path = _relative(link.dirname, store.view.path),
)
return link

def _claim(ctx, name, linked, owner):
if name in linked:
fail("{}: '{}' linked twice, to {} and {}".format(
Expand Down Expand Up @@ -137,6 +164,29 @@ def _dep_links(ctx, parts, cut = {}):
links[name] = _link_by_name(ctx, parts.links_dir, name, tree)
return links

def _dep_view_links(ctx, parts, cut = {}):
"""The links beside the view: `_dep_links`' twins, into the views."""
links = {}
for dep, names in ctx.attr.deps.items():
for name in names.split(" "):
links[name] = store_view_link(ctx, parts.links_dir, name, dep[NpmStoreInfo])
for name, tree in cut.items():
links[name] = _link_by_name(ctx, types_path(parts.links_dir), name, types_path(tree))
return links

def _type_view(ctx, tree, view):
args = ctx.actions.args()
args.add("-in=" + tree.path)
args.add("-out=" + view.path)
ctx.actions.run(
executable = get_tools_toolchain(ctx).tsaction,
arguments = ["typeview", args],
inputs = [tree],
outputs = [view],
mnemonic = "NpmTypeView",
progress_message = "Writing the type view of %{label}",
)

def _stage(ctx, tree, files, dest):
args = ctx.actions.args()
args.use_param_file("@%s", use_always = True)
Expand All @@ -156,7 +206,10 @@ def _stage(ctx, tree, files, dest):
progress_message = "Staging %{label}",
)

def _store_info(ctx, parts, tree, links):
def _store_info(ctx, parts, tree, links, cut = {}):
view = ctx.actions.declare_directory(types_path(ctx.label.name))
_type_view(ctx, tree, view)
view_links = _dep_view_links(ctx, parts, cut)
return NpmStoreInfo(
key = parts.key,
tree = tree,
Expand All @@ -165,6 +218,12 @@ def _store_info(ctx, parts, tree, links):
[tree] + links.values(),
transitive = [d[NpmStoreInfo].transitive for d in ctx.attr.deps],
),
view = view,
view_links = view_links,
view_transitive = depset(
[view] + view_links.values(),
transitive = [d[NpmStoreInfo].view_transitive for d in ctx.attr.deps],
),
)

def _npm_store_impl(ctx):
Expand All @@ -186,7 +245,7 @@ def _npm_store_impl(ctx):

_stage(ctx, tree, ctx.files.files, dest)
links = _dep_links(ctx, parts, ctx.attr.cut)
info = _store_info(ctx, parts, tree, links)
info = _store_info(ctx, parts, tree, links, ctx.attr.cut)
return [DefaultInfo(files = info.transitive), info]

_DEPS = attr.label_keyed_string_dict(
Expand Down Expand Up @@ -349,6 +408,7 @@ def _npm_store_hoist_impl(ctx):
linked = {}
links = {}
members = {}
view_members = {}
for dir, entries, names in (
(ctx.label.name, ctx.attr.private, ctx.attr.private_members),
("node_modules", ctx.attr.public, ctx.attr.public_members),
Expand All @@ -358,17 +418,19 @@ def _npm_store_hoist_impl(ctx):
links[name] = NpmLinkInfo(
link = _link(ctx, dir, name, dep, linked),
store = dep[NpmStoreInfo],
view_link = store_view_link(ctx, dir, name, dep[NpmStoreInfo]),
)
for name in names:
tree = store_target(store_key(name, MEMBER_VERSION, ""), name)
_claim(ctx, name, linked, ctx.label.same_package_label(tree))
members[name] = _link_by_name(ctx, dir, name, tree)
view_members[name] = _link_by_name(ctx, types_path(dir), name, types_path(tree))
return [
DefaultInfo(files = depset(
[entry.link for entry in links.values()] + members.values(),
transitive = [entry.store.transitive for entry in links.values()],
)),
NpmHoistInfo(links = links, members = members, member_names = ctx.attr.member_names),
NpmHoistInfo(links = links, members = members, view_members = view_members, member_names = ctx.attr.member_names),
]

_HOISTED = attr.label_keyed_string_dict(
Expand Down
2 changes: 1 addition & 1 deletion tests/api_surface/providers_surface_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ fi

# TsInfo runs from `TsInfo = provider(` to the closing paren at column 0; a
# field is an 8-space-indented quoted key at that depth.
printf '%s\n' data declarations js js_maps manifest npm_files npm_packages \
printf '%s\n' data declarations js js_maps manifest npm_files npm_packages npm_view_files \
owners runtime_source_owners runtime_sources sources transitive_data transitive_es_twins transitive_js \
transitive_js_maps transitive_runtime_sources tsconfig > "${want}"
sed -n '/^TsInfo = provider($/,/^)$/p' "${PROVIDERS}" \
Expand Down
2 changes: 1 addition & 1 deletion tests/api_surface/ts_compile_attrs_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ RULE="${RUNFILES}/ts/private/rules/ts_compile.bzl"
want="${TEST_TMPDIR}/want"
got="${TEST_TMPDIR}/got"

printf '%s\n' data deps emit node_modules package_scopes source_node_modules srcs tsconfig type_inputs > "${want}"
printf '%s\n' data deps emit node_modules package_scopes source_node_modules srcs tsconfig type_inputs type_views > "${want}"

# The dict runs from `TS_COMPILE_ATTRS = {` to the closing brace at column 0; a
# public attribute is a 4-space-indented quoted key at that depth.
Expand Down
2 changes: 1 addition & 1 deletion tests/api_surface/ts_test_attrs_test.sh
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ want="${TEST_TMPDIR}/want"
got="${TEST_TMPDIR}/got"

printf '%s\n' config config_deps config_node_modules config_srcs coverage_provider data deps emit env node_modules package_scopes \
runner source_node_modules srcs test_srcs tsconfig type_inputs workers_pool wrangler_config > "${want}"
runner source_node_modules srcs test_srcs tsconfig type_inputs type_views workers_pool wrangler_config > "${want}"

# A dict runs from `<NAME> = {` to the closing brace at column 0; a public
# attribute is a 4-space-indented quoted key at that depth.
Expand Down
10 changes: 6 additions & 4 deletions tests/compiler_options/analysis/analysis_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ def _borrowed_importer_inputs_impl(ctx):
consumer_companion = source.parent.links["@types/culori"]
admitted = [source.links["culori"].link, companion.link, consumer_companion.link]
unrelated = source.links["vitest"].link
admitted_views = [source.links["culori"].view_link, companion.view_link, consumer_companion.view_link]
unrelated_view = source.links["vitest"].view_link
asserts.true(env, companion.store.tree != consumer_companion.store.tree, "the fixture must distinguish companion store Files")
asserts.true(env, all([file in info.npm_files.to_list() for file in admitted]), "each origin retains its package and companion link Files")
asserts.false(env, unrelated in info.npm_files.to_list(), "another package in the importer does not become an input")
Expand All @@ -59,14 +61,14 @@ def _borrowed_importer_inputs_impl(ctx):
generated = [file for file in info.sources.to_list() if not file.is_source]
asserts.equals(env, 1, len(generated))
asserts.true(env, all([file in checks[0].inputs.to_list() for file in generated]), "generated scalar inputs retain the same importer projection")
asserts.true(env, all([file in checks[0].inputs.to_list() for file in admitted]), "both companion identities remain compiler action inputs")
asserts.false(env, unrelated in checks[0].inputs.to_list(), "unrelated importer links stay outside the action")
asserts.true(env, "-inherit_node_modules=" + source.dir in checks[0].argv, "the action mounts the original importer directory")
asserts.true(env, all([file in checks[0].inputs.to_list() for file in admitted_views]), "both companion identities remain compiler action inputs")
asserts.false(env, unrelated_view in checks[0].inputs.to_list(), "unrelated importer links stay outside the action")
asserts.true(env, "-inherit_node_modules=" + source.dir + ".types/node_modules" in checks[0].argv, "the action mounts the original importer directory")
ownership = _written_file_action(env, ".ownership")
asserts.true(env, ownership != None, "the compiler retains its direct-store ownership manifest")
if ownership:
for selected in [companion, consumer_companion]:
asserts.true(env, "npm-direct\t@types/culori\t" + selected.store.tree.path in ownership.content, "companion admission must not overwrite another origin's declaration")
asserts.true(env, "npm-direct\t@types/culori\t" + selected.store.view.path in ownership.content, "companion admission must not overwrite another origin's declaration")
return analysistest.end(env)

borrowed_importer_inputs_test = analysistest.make(
Expand Down
2 changes: 1 addition & 1 deletion tests/integration/runners/gazelle_roundtrip/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -945,7 +945,7 @@ console.log('native wrapper module store: `+version+`');
it.Fail("an unused consumer package became a direct compiler dependency")
}
// aquery's inputs() must match the whole exec path.
query := fmt.Sprintf(`inputs(".*/%s/app/node_modules/culori", mnemonic("TsgoCheck", %s))`, base, target)
query := fmt.Sprintf(`inputs(".*/%s/app/node_modules.types/node_modules/culori", mnemonic("TsgoCheck", %s))`, base, target)
var shadowInputs struct {
Actions []json.RawMessage `json:"actions"`
}
Expand Down
4 changes: 4 additions & 0 deletions tests/lint/lint_tests.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ def _lints_impl(ctx):
asserts.true(env, "-copy=" + path in argv, path + " retains module resolution inside the program")
asserts.true(env, any([path.endswith("/node_modules/oxlint") for path in inputs]), "config npm imports are declared")
asserts.true(env, any([arg.startswith("-node_modules=") for arg in argv]), "config importer reaches dependency-free programs")
runtime_links = [arg[len("-runtime_link="):] for arg in argv if arg.startswith("-runtime_link=")]
asserts.true(env, any([link.endswith("/tests/npm/node_modules/oxlint") for link in runtime_links]), "the config's importer links are laid over the program's type views")
asserts.true(env, all([link in [f.path for f in action.inputs.to_list()] for link in runtime_links]), "each runtime link is an input")
asserts.false(env, any([arg.endswith("/tests/npm/node_modules") and arg.startswith("-inherit_node_modules=") for arg in argv]), "the config's importer is not inherited over the program's twin")
tools = [f for f in action.inputs.to_list() if f.basename == "auxiliary_tool"]
asserts.equals(env, 1, len(tools), "auxiliary executable is an action input")
if tools:
Expand Down
9 changes: 8 additions & 1 deletion tests/npm/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ load("//npm:defs.bzl", "node_modules", "node_modules_member")
load("//tests/strict_deps:strict_deps_tests.bzl", "tsgo_check_test")
load("//ts:defs.bzl", "ts_binary", "ts_codegen", "ts_compile", "ts_test")
load(":direct_version_tests.bzl", "npm_identity_runtime_test")
load(":forest_tests.bzl", "chain_test")
load(":forest_tests.bzl", "chain_test", "trees_flag_chain_test")
load(":hub_provenance_tests.bzl", "store_provenance_test")
load(
":node_modules_tests.bzl",
Expand Down Expand Up @@ -667,3 +667,10 @@ store_provenance_test(
store_package = "vite/esbuild",
target_under_test = "//vite:node_modules",
)

# `--//ts:type_views=false` stages the trees in every program's type actions.
trees_flag_chain_test(
name = "app_trees_flag_chain_test",
size = "small",
target_under_test = ":app",
)
Loading
Loading