diff --git a/changelog.d/npm-type-views.md b/changelog.d/npm-type-views.md new file mode 100644 index 00000000..4eeba7ec --- /dev/null +++ b/changelog.d/npm-type-views.md @@ -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. diff --git a/docs/rules/node-modules.md b/docs/rules/node-modules.md index 5effd937..333c3788 100644 --- a/docs/rules/node-modules.md +++ b/docs/rules/node-modules.md @@ -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//node_modules/` 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 `/node_modules.types/node_modules/`. 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 diff --git a/docs/rules/ts-compile.md b/docs/rules/ts-compile.md index 9fa20b64..816eb1f7 100644 --- a/docs/rules/ts-compile.md +++ b/docs/rules/ts-compile.md @@ -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: @@ -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) | diff --git a/npm/private/store.bzl b/npm/private/store.bzl index 05d6944d..d4bb67b9 100644 --- a/npm/private/store.bzl +++ b/npm/private/store.bzl @@ -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//node_modules/`.", + "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.", }, ) @@ -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 + +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( @@ -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) @@ -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, @@ -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): @@ -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( @@ -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), @@ -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( diff --git a/tests/api_surface/providers_surface_test.sh b/tests/api_surface/providers_surface_test.sh index b0cb3405..b7cfa175 100755 --- a/tests/api_surface/providers_surface_test.sh +++ b/tests/api_surface/providers_surface_test.sh @@ -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}" \ diff --git a/tests/api_surface/ts_compile_attrs_test.sh b/tests/api_surface/ts_compile_attrs_test.sh index 3b8dcefb..75eb9fd3 100755 --- a/tests/api_surface/ts_compile_attrs_test.sh +++ b/tests/api_surface/ts_compile_attrs_test.sh @@ -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. diff --git a/tests/api_surface/ts_test_attrs_test.sh b/tests/api_surface/ts_test_attrs_test.sh index 3472068e..3d5d06d5 100755 --- a/tests/api_surface/ts_test_attrs_test.sh +++ b/tests/api_surface/ts_test_attrs_test.sh @@ -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 ` = {` to the closing brace at column 0; a public # attribute is a 4-space-indented quoted key at that depth. diff --git a/tests/compiler_options/analysis/analysis_tests.bzl b/tests/compiler_options/analysis/analysis_tests.bzl index ce30eb0d..8cafea1d 100644 --- a/tests/compiler_options/analysis/analysis_tests.bzl +++ b/tests/compiler_options/analysis/analysis_tests.bzl @@ -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") @@ -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( diff --git a/tests/integration/runners/gazelle_roundtrip/main.go b/tests/integration/runners/gazelle_roundtrip/main.go index ff7df80b..e4cad57d 100644 --- a/tests/integration/runners/gazelle_roundtrip/main.go +++ b/tests/integration/runners/gazelle_roundtrip/main.go @@ -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"` } diff --git a/tests/lint/lint_tests.bzl b/tests/lint/lint_tests.bzl index a62e040f..2daf0e35 100644 --- a/tests/lint/lint_tests.bzl +++ b/tests/lint/lint_tests.bzl @@ -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: diff --git a/tests/npm/BUILD.bazel b/tests/npm/BUILD.bazel index 58496499..6699ca27 100644 --- a/tests/npm/BUILD.bazel +++ b/tests/npm/BUILD.bazel @@ -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", @@ -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", +) diff --git a/tests/npm/direct_version_tests.bzl b/tests/npm/direct_version_tests.bzl index f86f7c9c..49a88ff2 100644 --- a/tests/npm/direct_version_tests.bzl +++ b/tests/npm/direct_version_tests.bzl @@ -67,7 +67,7 @@ def _mixed_npm_store_identity_impl(ctx): checks = [action for action in runnable_actions(env) if action.mnemonic == "TsgoCheck"] asserts.equals(env, 1, len(checks)) if checks: - for tree in [selected.store.tree, retained.store.tree]: + for tree in [selected.store.view, retained.store.view]: asserts.true(env, tree in checks[0].inputs.to_list(), "both exact stores remain compiler inputs") writers = [action for action in runnable_actions(env) if any([file.basename.endswith(".ownership") for file in action.outputs.to_list()])] asserts.equals(env, 1, len(writers)) @@ -75,9 +75,9 @@ def _mixed_npm_store_identity_impl(ctx): rows = [line.split("\t") for line in writers[0].content.split("\n") if line] direct = [row[2] for row in rows if row[0] == "npm-direct"] reachable = [row[3] for row in rows if row[0] == "npm"] - asserts.true(env, selected.store.tree.path in direct, "selected File A is direct") - asserts.equals(env, ctx.attr.retained_direct, retained.store.tree.path in direct, "only declaring File B makes it direct") - asserts.equals(env, not ctx.attr.retained_direct, retained.store.tree.path in reachable, "same-key File B retains its closure ownership") + asserts.true(env, selected.store.view.path in direct, "selected File A is direct") + asserts.equals(env, ctx.attr.retained_direct, retained.store.view.path in direct, "only declaring File B makes it direct") + asserts.equals(env, not ctx.attr.retained_direct, retained.store.view.path in reachable, "same-key File B retains its closure ownership") return analysistest.end(env) mixed_npm_store_identity_test = analysistest.make( diff --git a/tests/npm/forest_tests.bzl b/tests/npm/forest_tests.bzl index f1a2f9cb..082cce6d 100644 --- a/tests/npm/forest_tests.bzl +++ b/tests/npm/forest_tests.bzl @@ -17,6 +17,13 @@ def _action(env, mnemonic): return action return None +def _view(rel): + """The twin a tsgo action stages of `rel`, the same path under + `node_modules.types/`; a bare `node_modules/...` suffix matches both.""" + if rel.startswith("node_modules/") or "/node_modules/" not in rel: + return rel + return rel.replace("/node_modules/", "/node_modules.types/node_modules/", 1) + def _chain_impl(ctx): env = analysistest.begin(ctx) tsgo = _action(env, "TsgoCheck") @@ -25,7 +32,7 @@ def _chain_impl(ctx): return analysistest.end(env) asserts.equals( env, - [ctx.bin_dir.path + "/" + d for d in ctx.attr.chain], + [ctx.bin_dir.path + "/" + d + ".types/node_modules" for d in ctx.attr.chain], [ arg[len("-node_modules="):] for arg in tsgo.argv @@ -57,9 +64,9 @@ def _chain_impl(ctx): [ f.path for f in inputs - if f.is_directory and "/node_modules/.pnpm/" not in f.path + if f.is_directory and "/node_modules.types/node_modules/.pnpm/" not in f.path ], - "every tree input is a store tree", + "every tree input is a store tree's type view", ) asserts.equals( env, @@ -68,7 +75,7 @@ def _chain_impl(ctx): "no npm file is staged from a source repository", ) staged = [f.short_path for f in inputs] - for rel in ctx.attr.linked: + for rel in [_view(rel) for rel in ctx.attr.linked]: asserts.true( env, len([p for p in staged if p == rel or p.endswith("/" + rel)]) > 0, @@ -117,3 +124,32 @@ chain_test = analysistest.make( ), }, ) + +def _trees_impl(ctx): + env = analysistest.begin(ctx) + tsgo = _action(env, "TsgoCheck") + lint = _action(env, "TsLint") + for action in [a for a in [tsgo, lint] if a != None]: + importers = [arg for arg in action.argv if arg.startswith("-node_modules=") or arg.startswith("-inherit_node_modules=")] + asserts.true(env, len(importers) > 0, action.mnemonic + " names its importers") + asserts.equals(env, [], [arg for arg in importers if ".types/" in arg], action.mnemonic + " names the importers' trees, not their twins") + asserts.equals( + env, + [], + [f.path for f in action.inputs.to_list() if "/node_modules.types/" in f.path], + action.mnemonic + " stages no type view", + ) + asserts.false(env, any([arg.startswith("-runtime_link=") for arg in action.argv]), action.mnemonic + " lays no runtime link over trees") + asserts.true(env, tsgo != None, "ts_compile runs no TsgoCheck") + return analysistest.end(env) + +trees_chain_test = analysistest.make( + _trees_impl, + extra_target_under_test_aspects = [runnable_action_aspect], +) + +trees_flag_chain_test = analysistest.make( + _trees_impl, + extra_target_under_test_aspects = [runnable_action_aspect], + config_settings = {str(Label("//ts:type_views")): False}, +) diff --git a/tests/npm/hoist_twice/BUILD.bazel b/tests/npm/hoist_twice/BUILD.bazel index e1647f9e..2c5e9e2a 100644 --- a/tests/npm/hoist_twice/BUILD.bazel +++ b/tests/npm/hoist_twice/BUILD.bazel @@ -1,5 +1,5 @@ load("//npm/private:store.bzl", "npm_store_hoist") -load("//tests/npm:node_modules_tests.bzl", "hoist_linked_twice_test") +load("//tests/npm:node_modules_tests.bzl", "hoist_linked_twice_test", "public_hoist_member_test") MINIMATCH = "//tests/npm:node_modules/.pnpm/minimatch@" @@ -15,3 +15,16 @@ hoist_linked_twice_test( name = "hoist_linked_twice_test", target_under_test = ":node_modules/.pnpm/node_modules", ) + +# A workspace member hoisted publicly has a twin of its link in the type views' layout. +npm_store_hoist( + name = "public_member_hoist", + public_members = ["hoisted-member"], + tags = ["manual"], +) + +public_hoist_member_test( + name = "public_hoist_member_test", + members = ["hoisted-member"], + target_under_test = ":public_member_hoist", +) diff --git a/tests/npm/node_modules_tests.bzl b/tests/npm/node_modules_tests.bzl index cb74272f..7dd0b4c7 100644 --- a/tests/npm/node_modules_tests.bzl +++ b/tests/npm/node_modules_tests.bzl @@ -44,6 +44,12 @@ def _node_modules_impl(ctx): entry.link.path, name + " sits in the directory", ) + asserts.equals( + env, + info.dir + ".types/node_modules/" + name, + entry.view_link.path, + name + "'s type view link sits in node_modules.types/node_modules", + ) asserts.true(env, entry.link in files, name + " is among the files") for f in entry.store.transitive.to_list(): if f.is_directory: @@ -83,9 +89,9 @@ def _node_modules_impl(ctx): ) asserts.equals( env, - len(info.links), + 2 * len(info.links), len(analysistest.target_actions(env)), - "one symlink action per link and no other", + "one symlink action per link and its type view twin, and no other", ) return analysistest.end(env) @@ -129,9 +135,9 @@ def _hoist_links_impl(ctx): ) asserts.equals( env, - len(info.links) + len(info.members), + 2 * (len(info.links) + len(info.members)), len(analysistest.target_actions(env)), - "one symlink action per link and no other", + "one symlink action per link and its type view twin, and no other", ) return analysistest.end(env) @@ -188,3 +194,24 @@ hoist_linked_twice_test = _fails_with( ) member_in_deps_test = _fails_with("node_modules_member(") bin_entry_missing_test = _fails_with("entry script 'cli.js' not found") + +def _public_hoist_member_impl(ctx): + env = analysistest.begin(ctx) + info = analysistest.target_under_test(env)[NpmHoistInfo] + for name in ctx.attr.members: + asserts.true( + env, + info.members[name].short_path.endswith("/node_modules/" + name), + name + "'s public link sits in the importer's node_modules", + ) + asserts.true( + env, + info.view_members[name].short_path.endswith("/node_modules.types/node_modules/" + name), + name + "'s twin sits in node_modules.types/node_modules: " + info.view_members[name].short_path, + ) + return analysistest.end(env) + +public_hoist_member_test = analysistest.make( + _public_hoist_member_impl, + attrs = {"members": attr.string_list(doc = "The workspace members hoisted publicly.")}, +) diff --git a/tests/npm/trees/BUILD.bazel b/tests/npm/trees/BUILD.bazel new file mode 100644 index 00000000..e7cf9c34 --- /dev/null +++ b/tests/npm/trees/BUILD.bazel @@ -0,0 +1,17 @@ +load("//tests/npm:forest_tests.bzl", "trees_chain_test") +load("//ts:defs.bzl", "ts_compile") + +# `type_views = False` stages the trees in one program's type actions. +ts_compile( + name = "app", + srcs = ["app.ts"], + node_modules = "//tests/npm:node_modules", + type_views = False, + deps = ["@npm//:zod"], +) + +trees_chain_test( + name = "app_chain_test", + size = "small", + target_under_test = ":app", +) diff --git a/tests/npm/trees/app.ts b/tests/npm/trees/app.ts new file mode 100644 index 00000000..7e88bc6a --- /dev/null +++ b/tests/npm/trees/app.ts @@ -0,0 +1,10 @@ +import { z } from "zod"; + +// Use zod at runtime — the type is not inferred in module position. +export function parseUser(input: unknown): { name: string; age: number } { + const schema = z.object({ + name: z.string(), + age: z.number(), + }); + return schema.parse(input) as { name: string; age: number }; +} diff --git a/tests/strict_deps/strict_deps_tests.bzl b/tests/strict_deps/strict_deps_tests.bzl index 8d048a6b..e89e37d5 100644 --- a/tests/strict_deps/strict_deps_tests.bzl +++ b/tests/strict_deps/strict_deps_tests.bzl @@ -110,10 +110,10 @@ def _tsgo_check_impl(ctx): expected = list(ctx.attr.lines) for dep in ctx.attr.npm_direct: info = dep[NpmPackageInfo] - expected.append("npm-direct\t{}\t{}".format(info.package_name, info.store.tree.path)) + expected.append("npm-direct\t{}\t{}".format(info.package_name, info.store.view.path)) for dep, label in ctx.attr.npm_reachable.items(): info = dep[NpmPackageInfo] - expected.append("npm\t{}\t{}\t{}".format(info.package_name, label, info.store.tree.path)) + expected.append("npm\t{}\t{}\t{}".format(info.package_name, label, info.store.view.path)) for line in expected: asserts.true( env, diff --git a/tests/vitest/dep_npm_runtime/test/tree_tests.bzl b/tests/vitest/dep_npm_runtime/test/tree_tests.bzl index 62dcf301..9abb2566 100644 --- a/tests/vitest/dep_npm_runtime/test/tree_tests.bzl +++ b/tests/vitest/dep_npm_runtime/test/tree_tests.bzl @@ -24,16 +24,16 @@ def _runtime_is_the_chain_impl(ctx): importer = ctx.bin_dir.path + "/tests/npm/node_modules" asserts.equals( env, - ["-node_modules=" + importer], + ["-node_modules=" + importer + ".types/node_modules"], [a for a in tsgo[0].argv if a.startswith("-node_modules=")], - "tsgo resolves through the importer's node_modules", + "tsgo resolves through the importer's type view links", ) asserts.true( env, len([ f for f in tsgo[0].inputs.to_list() - if f.path == importer + "/zod" + if f.path == importer + ".types/node_modules/zod" ]) == 1, "zod, declared by the ts_compile dep alone, is staged through " + "the dep's npm_files", diff --git a/ts/BUILD.bazel b/ts/BUILD.bazel index b7083ca8..578ffdeb 100644 --- a/ts/BUILD.bazel +++ b/ts/BUILD.bazel @@ -50,6 +50,14 @@ int_flag( scope = "target", ) +# The type actions (emit, check, declare, lint) read each npm package's type view, the files TypeScript's +# resolution reads, instead of its tree; false stages the trees, as runtime actions always do. +bool_flag( + name = "type_views", + build_setting_default = True, + scope = "target", +) + # Library checking exposes invalid third-party declarations hidden by skipLibCheck. bool_flag( name = "lib_check", diff --git a/ts/private/actions/lint.bzl b/ts/private/actions/lint.bzl index 22c5288d..10262e3d 100644 --- a/ts/private/actions/lint.bzl +++ b/ts/private/actions/lint.bzl @@ -20,6 +20,7 @@ LintConfigInfo = provider( "tool_env": "dict of environment name to FilesToRunProvider: auxiliary executables.", "data": "depset of File: declared config imports, plugins and ignore files.", "importers": "list of string: importer directories declared in data, root last.", + "links": "list of File: the importer links declared in data, which the config loads at run time.", "args": "list of string: linter arguments; {tsconfig} names the action config.", "fail_on_warnings": "bool: --max-warnings=0 is passed.", }, @@ -46,6 +47,7 @@ def _lint_config_impl(ctx): config = ctx.file.config, data = depset(ctx.files.data + links, transitive = stores), importers = importers.keys(), + links = links, args = ctx.attr.args, fail_on_warnings = ctx.attr.fail_on_warnings, )] @@ -117,14 +119,19 @@ lint_config_repo = repository_rule( "configured.", ) -def lint_action(ctx, lint, srcs, tsconfig, inputs, chain, dep_dts, npm_files, importers, overlays, manifests, generated_srcs = [], inherited_importers = []): - """Registers TsLint in the same program layout as tsgo's validation.""" +def lint_action(ctx, lint, srcs, tsconfig, inputs, chain, dep_dts, npm_files, importers, overlays, manifests, generated_srcs = [], inherited_importers = [], views = False): + """Registers TsLint in the same program layout as tsgo's validation. + + With `views`, the program reads type views and each link the config's + data declares is laid over its importer's entry, its tree in place of + the view, so the config's imports run under Node. + """ stamp = ctx.actions.declare_file("{}.tslint".format(ctx.label.name)) config_files = [lint.config] if lint.config else [] own_importers = importers or lint.importers inherited = { directory: True - for directory in inherited_importers + lint.importers + for directory in inherited_importers + ([] if views else lint.importers) if directory not in own_importers } args = program_args( @@ -140,6 +147,8 @@ def lint_action(ctx, lint, srcs, tsconfig, inputs, chain, dep_dts, npm_files, im inherited.keys(), ) args.add_all(depset(config_files, transitive = [lint.data]), map_each = source_path, format_each = "-copy=%s", expand_directories = False) + if views: + args.add_all(lint.links, format_each = "-runtime_link=%s") if tsconfig: args.add(tsconfig, format = "-discover-tsconfig=%s") for name, tool in lint.tool_env.items(): diff --git a/ts/private/actions/tsgo.bzl b/ts/private/actions/tsgo.bzl index df169313..56ff1c27 100644 --- a/ts/private/actions/tsgo.bzl +++ b/ts/private/actions/tsgo.bzl @@ -62,8 +62,14 @@ def _npm_declared_line(link): def _npm_reachable_line(npm_info): return "npm\t{}\t{}\t{}".format(npm_info.package_name, npm_hub_label(npm_info), npm_info.store.tree.path) -def ownership_manifest(ctx, own, direct, owners, npm_declared, npm_reachable): - """`npm_reachable` holds NpmPackageInfo; every closure-sized line is rendered at execution.""" +def _npm_reachable_view_line(npm_info): + return "npm\t{}\t{}\t{}".format(npm_info.package_name, npm_hub_label(npm_info), npm_info.store.view.path) + +def ownership_manifest(ctx, own, direct, owners, npm_declared, npm_reachable, views = False): + """`npm_reachable` holds NpmPackageInfo; every closure-sized line is rendered at execution. + + `views` names each reachable package by its type view in place of its tree. + """ manifest = ctx.actions.declare_file("{}.ownership".format(ctx.label.name)) lines = ctx.actions.args() lines.set_param_file_format("multiline") @@ -72,7 +78,7 @@ def ownership_manifest(ctx, own, direct, owners, npm_declared, npm_reachable): lines.add_all(direct, format_each = "direct\t%s") lines.add_all(owners, map_each = _owner_lines) lines.add_all(npm_declared, map_each = _npm_declared_line) - lines.add_all(npm_reachable, map_each = _npm_reachable_line) + lines.add_all(npm_reachable, map_each = _npm_reachable_view_line if views else _npm_reachable_line) ctx.actions.write(output = manifest, content = lines) return manifest diff --git a/ts/private/node_modules.bzl b/ts/private/node_modules.bzl index beae0ce0..97494e6c 100644 --- a/ts/private/node_modules.bzl +++ b/ts/private/node_modules.bzl @@ -11,7 +11,7 @@ and its `parent`s form (ts/private/rules/ts_compile.bzl). docs/rules/node-modules.md. """ -load("//npm/private:store.bzl", "store_link") +load("//npm/private:store.bzl", "store_link", "store_view_link") load("//tools/launcher:launcher.bzl", "rlocation_path") load( "//ts/private:providers.bzl", @@ -94,6 +94,7 @@ def npm_hoist_links(packages, hoist): links.append(NpmLinkInfo( link = hoist.members[info.package_name], store = info.store, + view_link = hoist.view_members[info.package_name], )) return links @@ -452,6 +453,7 @@ def _node_modules_impl(ctx): links[name] = NpmLinkInfo( link = store_link(ctx, "node_modules", name, info.store), store = info.store, + view_link = store_view_link(ctx, "node_modules", name, info.store), ) packages = npm_closure([dep[NpmPackageInfo] for dep in ctx.attr.deps], []) @@ -555,7 +557,7 @@ def _node_modules_member_impl(ctx): files = files, runfiles = ctx.runfiles(transitive_files = files), ), - NpmLinkInfo(link = link, store = info.store), + NpmLinkInfo(link = link, store = info.store, view_link = store_view_link(ctx, "node_modules", name, info.store)), member[TsInfo], info, ] diff --git a/ts/private/providers.bzl b/ts/private/providers.bzl index 2f98e9ec..8c493305 100644 --- a/ts/private/providers.bzl +++ b/ts/private/providers.bzl @@ -65,6 +65,9 @@ store; a workspace member's hub view forwards the member's. "holds with the trees they enter, and its first-party " + "deps' npm_files. An action stages this and nothing " + "else of the store.", + "npm_view_files": "depset of File: `npm_files` with each store tree's " + + "type view and the views' links in place of the trees " + + "and links, what a type action stages under --//ts:type_views.", "owners": "depset of struct(label, files, declarations, type_inputs, importers) " + "with optional declaration_files, canonical_links, asset_files, runtime_files, runtime_scopes, scope_manifest, replaced_scope and npm_bindings: one " + "record per first-party target in the closure, this one " + @@ -131,6 +134,7 @@ def ts_info( transitive_es_twins = _EMPTY, npm_packages = _EMPTY, npm_files = _EMPTY, + npm_view_files = _EMPTY, label = None, source_files = None, generated_inputs = None): @@ -170,6 +174,7 @@ def ts_info( transitive_es_twins = transitive_es_twins, npm_packages = npm_packages, npm_files = npm_files, + npm_view_files = npm_view_files, owners = owners, ) @@ -329,6 +334,7 @@ on the chain carries it as `NodeModulesInfo.hoist`.""", "the declared symlink alone, with no dependency on the " + "member's tree; a consumer's closure holds the tree " + "through the member's link target.", + "view_members": "dict of string -> File: `members`' twins in the type views' layout.", "member_names": "dict of string -> string: per workspace member " + "of the lockfile, hoisted or not, its directory " + "from the workspace root -> its package name.", @@ -342,6 +348,7 @@ a workspace member beside the member's own TsInfo and NpmPackageInfo.""", fields = { "link": "File: the declared symlink `node_modules/`.", "store": "NpmStoreInfo: the store the link enters.", + "view_link": "File: the link's twin in the type views' layout, into the store's view.", }, ) diff --git a/ts/private/rules/ts_compile.bzl b/ts/private/rules/ts_compile.bzl index 841c1912..7aede141 100644 --- a/ts/private/rules/ts_compile.bzl +++ b/ts/private/rules/ts_compile.bzl @@ -443,6 +443,12 @@ def _resolve_on_chains(ctx, chain, dep, member_links, source_chains): npm_hub_label(dep.info, importer.label.package), )) +def _types_importer(dir): + """An importer's node_modules directory's twin in the type views' layout.""" + if not dir.endswith("/node_modules"): + fail("_types_importer: {} is not a node_modules directory".format(dir)) + return dir + ".types/node_modules" + def _retain_npm_link(ctx, links, link): previous = links.get(link.link.path) if previous != None and previous.store.tree != link.store.tree: @@ -499,6 +505,7 @@ def compile_program( dep_npm_package_sets = [] dep_npm_file_sets = [] + dep_npm_view_sets = [] transitive_js_sets = [] runtime_source_sets = [] transitive_js_map_sets = [] @@ -538,6 +545,9 @@ def compile_program( transitive_data_sets.append(info.transitive_data) transitive_es_twins_sets.append(info.transitive_es_twins) dep_npm_file_sets.append(info.npm_files) + + # A TsInfo built before type views carries none; its program reads the trees. + dep_npm_view_sets.append(getattr(info, "npm_view_files", None)) direct_labels.append(label_text(dep.label)) owner_sets.append(info.owners) if _encloses(dep.label, ctx.label): @@ -592,6 +602,13 @@ def compile_program( [entry.store.transitive for entry in npm_links.values()] + dep_npm_file_sets ), ) + npm_view_files = depset( + [entry.view_link for entry in npm_links.values()], + transitive = ( + [entry.store.view_transitive for entry in npm_links.values()] + + [views for views in dep_npm_view_sets if views != None] + ), + ) own_importers = source_importers.keys() + own_importers dependency_importers = {} dependency_owners = depset(transitive = owner_sets).to_list() @@ -611,6 +628,12 @@ def compile_program( importers = [importer.dir for importer in chain] inherited_importers = dependency_importers.keys() + source_importers.keys() + # Type actions read each package's type view; runtime actions and the editor read the trees. + type_views = ctx.attr._type_views[BuildSettingInfo].value and ctx.attr.type_views and None not in dep_npm_view_sets + type_npm_files = npm_view_files if type_views else npm_files + type_importers = [_types_importer(dir) for dir in importers] if type_views else importers + type_inherited_importers = [_types_importer(dir) for dir in inherited_importers] if type_views else inherited_importers + declared_trees = {selected.link.store.tree: True for selected in selected_npm} npm_reachable = [ info @@ -1225,14 +1248,14 @@ def compile_program( out_base = out_base, tsconfig = tsconfig, chain = tsconfig_chain, - importers = importers, - inherited_importers = inherited_importers, + importers = type_importers, + inherited_importers = type_inherited_importers, overlays = compiler_overlays, manifests = dep_manifests, program_inputs = program_inputs, generated_srcs = generated_srcs, dep_dts = dep_dts_depset, - npm_files = npm_files, + npm_files = type_npm_files, options_file = options_file, scratch = "{}/{}.emit".format(tsconfig.dirname, ctx.label.name), source_map = source_map, @@ -1252,14 +1275,14 @@ def compile_program( out_base = "{}/{}".format(out_base, twins_dir), tsconfig = tsconfig, chain = tsconfig_chain, - importers = importers, - inherited_importers = inherited_importers, + importers = type_importers, + inherited_importers = type_inherited_importers, overlays = compiler_overlays, manifests = dep_manifests, program_inputs = program_inputs, generated_srcs = generated_srcs, dep_dts = dep_dts_depset, - npm_files = npm_files, + npm_files = type_npm_files, options_file = options_file, scratch = "{}/{}.emit".format(tsconfig.dirname, twins_dir), source_map = False, @@ -1273,24 +1296,25 @@ def compile_program( direct = direct_labels, owners = owners, npm_declared = [ - struct(name = selected.name, tree = selected.link.store.tree) + struct(name = selected.name, tree = selected.link.store.view if type_views else selected.link.store.tree) for selected in selected_npm ], npm_reachable = npm_reachable, + views = type_views, ) validation_outputs.append(tsgo_check( ctx, tsgo = tsgo, tsconfig = tsconfig, - importers = importers, - inherited_importers = inherited_importers, + importers = type_importers, + inherited_importers = type_inherited_importers, overlays = compiler_overlays, manifests = dep_manifests, srcs = program_inputs, generated_srcs = generated_srcs, chain = tsconfig_chain, dep_dts = dep_dts_depset, - npm_files = npm_files, + npm_files = type_npm_files, ownership = ownership, checkers = checkers, check = ctx.attr._check[CheckConfigInfo], @@ -1307,14 +1331,14 @@ def compile_program( out_base = out_base, tsconfig = tsconfig, chain = tsconfig_chain, - importers = importers, - inherited_importers = inherited_importers, + importers = type_importers, + inherited_importers = type_inherited_importers, overlays = compiler_overlays, manifests = dep_manifests, program_inputs = program_inputs, generated_srcs = generated_srcs, dep_dts = dep_dts_depset, - npm_files = npm_files, + npm_files = type_npm_files, options_file = options_file, scratch = "{}/{}.declare".format(tsconfig.dirname, ctx.label.name), source_map = False, @@ -1352,11 +1376,12 @@ def compile_program( generated_srcs = generated_srcs, chain = tsconfig_chain, dep_dts = dep_dts_depset, - npm_files = npm_files, - importers = importers, - inherited_importers = inherited_importers, + npm_files = type_npm_files, + importers = type_importers, + inherited_importers = type_inherited_importers, overlays = compiler_overlays, manifests = dep_manifests, + views = type_views, )) direct_runtime_sources = depset(runtime_sources, order = "postorder") @@ -1412,6 +1437,7 @@ def compile_program( order = "postorder", ), npm_files = npm_files, + npm_view_files = npm_view_files, owners = owners, ) @@ -1491,6 +1517,10 @@ TS_COMPILE_ATTRS = { doc = "Standalone asset files staged at package-relative paths in both emit modes. Put JSON module inputs in srcs and package metadata in package_scopes.", allow_files = True, ), + "type_views": attr.bool( + default = True, + doc = "Stage npm packages' type views in this program's type actions. False stages their trees, for a program whose resolution reads a file its views drop; its dependents keep their own choice. `--//ts:type_views=false` sets it false for every program.", + ), "emit": attr.bool( default = False, doc = "Opt in to JavaScript and declaration emission for consumers that require built files. By default, publish TypeScript sources and retain validation.", @@ -1619,6 +1649,7 @@ for all of them but Node16/NodeNext.""", "_source_map": attr.label(default = Label("//ts:source_map")), "_declaration_map": attr.label(default = Label("//ts:declaration_map")), "_lib_check": attr.label(default = Label("//ts:lib_check")), + "_type_views": attr.label(default = Label("//ts:type_views")), "_checkers": attr.label(default = Label("//ts:checkers")), } diff --git a/ts/tools/tsaction/BUILD.bazel b/ts/tools/tsaction/BUILD.bazel index 9504230e..760c726d 100644 --- a/ts/tools/tsaction/BUILD.bazel +++ b/ts/tools/tsaction/BUILD.bazel @@ -16,6 +16,7 @@ go_library( "paths.go", "showconfig.go", "tsgo.go", + "typeview.go", ], importpath = "github.com/mikn/rules_typescript/ts/tools/tsaction", visibility = ["//visibility:private"], @@ -48,6 +49,7 @@ go_test( "paths_test.go", "showconfig_test.go", "tsgo_test.go", + "typeview_test.go", ], data = glob(["testdata/**"]) + [ "//tools/copy_to_workspace", diff --git a/ts/tools/tsaction/main.go b/ts/tools/tsaction/main.go index 9f7bca1d..8b70ffb1 100644 --- a/ts/tools/tsaction/main.go +++ b/ts/tools/tsaction/main.go @@ -26,6 +26,7 @@ const usage = `usage: tsaction stamp -stamp=FILE [-runtime_scope=JSON]... [-- TOOL [ARG...]] tsaction stage -out=DIR SRC DEST [SRC DEST...] tsaction native-view -spec=FILE + tsaction typeview -in=DIR -out=DIR tsaction tar -out=FILE -dir=DIR [-prefix=P] tsaction tsconfig -tsgo=BIN [-tsconfig=FILE] -baseline=FILE -out=FILE -options=FILE -bin_dir=DIR [-jsx=preserve] [-module=KIND] [-types_dep=NAME]... @@ -57,6 +58,8 @@ func main() { err = nativeView(args) case "stage": err = stage(args) + case "typeview": + err = typeView(args) case "tar": err = writeTar(args) case "tsconfig": diff --git a/ts/tools/tsaction/tsgo.go b/ts/tools/tsaction/tsgo.go index 3ca8fbdb..1196b993 100644 --- a/ts/tools/tsaction/tsgo.go +++ b/ts/tools/tsaction/tsgo.go @@ -27,7 +27,7 @@ func runTsgo(args []string) error { absoluteCopyArgs := flags.Bool("absolute-copy-args", false, "pass copied file arguments as absolute paths") verifyCopies := flags.Bool("verify-copies", false, "fail if the tool changes a copied input") discoverConfig := flags.String("discover-tsconfig", "", "generated program config exposed to tools that discover tsconfig.json beside sources") - var sources, copies, importers, inherited, overlays, manifests, toolEnv, runtimeScopes stringList + var sources, copies, importers, inherited, runtimeLinks, overlays, manifests, toolEnv, runtimeScopes stringList var editor actionConfig flags.StringVar(&editor.out, "editor-config", "", "compiler project to project for the editor") flags.StringVar(&editor.baseline, "editor-baseline", "", "compiler baseline options") @@ -47,6 +47,10 @@ func runTsgo(args []string) error { flags.Var(&inherited, "inherit_node_modules", "a dependency's or source's importer node_modules directory outside the chain, "+ "resolving its own links before the chain's (repeatable)") + flags.Var(&runtimeLinks, "runtime_link", + "an importer link a tool loads at run time, laid at its path relative to bin "+ + "over the importers' entry of its name, so a program on type views still "+ + "runs the tool's JavaScript from the tree (repeatable)") flags.Var(&overlays, "overlay", "a generated compiler input or dependency output directory, laid at "+ "its path relative to bin; JavaScript and original source package scopes "+ @@ -90,6 +94,11 @@ func runTsgo(args []string) error { return err } defer removeUndeclared(*root, sources) + for _, link := range runtimeLinks { + if err := placeRuntimeLink(*root, link, importers); err != nil { + return err + } + } // Node resolves config imports from the real file, not its source symlink. for _, file := range copies { @@ -601,7 +610,7 @@ func (a *actionConfig) layOutProgramRoot( if err := os.RemoveAll(root); err != nil { return err } - if err := linkAt(root, execroot, outputTree); err != nil { + if err := linkOutputTree(root, execroot, typeViewHoles(append(append([]string{}, importers...), inherited...))); err != nil { return err } sourceFiles := map[string]string{} @@ -676,6 +685,16 @@ func (a *actionConfig) layOutProgramRoot( if err := os.RemoveAll(link); err != nil { return err } + // On the full layout a source outside every importer's package walks up + // past the program root, which sits in the output tree under the + // target's package, into the chain's node_modules there; on views the + // root importer's twin holds the chain behind its own names. + if i == len(importers)-1 && i > 0 && len(typeViewHoles(importers)) > 0 { + if err := mergeImporters(link, execroot, append([]string{binDir}, importers[:i]...)); err != nil { + return err + } + continue + } if i == 0 && len(importers) > 2 && skipsAncestors(importers) { if err := mergeImporters(link, execroot, importers[:len(importers)-1]); err != nil { return err @@ -794,15 +813,26 @@ func mergeEntries(at, from string, scopes bool) error { } // importerDir is the importer's directory in the exec root, read off its -// node_modules' bin-dir path bazel-out//bin//node_modules. +// node_modules' bin-dir path bazel-out//bin//node_modules, or its +// type views' twin bazel-out//bin//node_modules.types/node_modules. func importerDir(binDir string) string { - dir := filepath.Dir(filepath.FromSlash(binRelative(binDir))) + rel := filepath.ToSlash(binRelative(binDir)) + if rel == typeViewImporter { + return "" + } + if at, ok := strings.CutSuffix(rel, "/"+typeViewImporter); ok { + return filepath.FromSlash(at) + } + dir := filepath.Dir(filepath.FromSlash(rel)) if dir == "." { return "" } return dir } +// typeViewImporter is an importer's twin node_modules in the type views' layout. +const typeViewImporter = "node_modules.types/node_modules" + // An explicit compiler root must keep the File named by its ownership record. func overlayPath(root, rootAbs, from, rel string, st os.FileInfo, sourceFiles map[string]string, replaceManifest bool, editor *editorProjection) error { if editor != nil && editor.authored(rel) { @@ -872,6 +902,73 @@ func overlayPath(root, rootAbs, from, rel string, st os.FileInfo, sourceFiles ma return nil } +// typeViewHoles maps the node_modules path of each importer named by its type +// views' twin to that twin. +func typeViewHoles(importers []string) map[string]string { + holes := map[string]string{} + for _, binDir := range importers { + if full, ok := strings.CutSuffix(filepath.ToSlash(binDir), ".types/node_modules"); ok && strings.HasSuffix(full, "/node_modules") { + holes[full] = binDir + } + } + return holes +} + +// linkOutputTree links the output tree into the program root whole, or, with +// holes, as real directories down to each hole, every other entry linked, and +// each hole linked to its twin. The written tsconfig sits in the output tree: +// TypeScript resolves its types entries walking up from there, and so meets +// the importers' type views where it meets their trees on the full layout. +func linkOutputTree(root, execroot string, holes map[string]string) error { + if len(holes) == 0 { + return linkAt(root, execroot, outputTree) + } + return splitLink(root, execroot, outputTree, holes) +} + +func splitLink(root, execroot, rel string, holes map[string]string) error { + if twin, ok := holes[rel]; ok { + return linkTo(filepath.Join(root, rel), filepath.Join(execroot, twin)) + } + var below []string + for hole := range holes { + if strings.HasPrefix(hole, rel+"/") { + below = append(below, hole) + } + } + if len(below) == 0 { + return linkAt(root, execroot, rel) + } + if err := os.MkdirAll(filepath.Join(root, rel), 0o755); err != nil { + return err + } + children := map[string]bool{} + entries, err := os.ReadDir(filepath.Join(execroot, rel)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return err + } + for _, entry := range entries { + children[entry.Name()] = true + } + for _, hole := range below { + next, _, _ := strings.Cut(hole[len(rel)+1:], "/") + children[next] = true + } + for child := range children { + if err := splitLink(root, execroot, rel+"/"+child, holes); err != nil { + return err + } + } + return nil +} + +func linkTo(at, target string) error { + if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil { + return err + } + return os.Symlink(target, at) +} + // linkAt links the exec root's rel into root at rel, its directories real. func linkAt(root, execroot, rel string) error { at := filepath.Join(root, rel) @@ -880,3 +977,57 @@ func linkAt(root, execroot, rel string) error { } return os.Symlink(filepath.Join(execroot, rel), at) } + +// placeRuntimeLink lays link, an importer link in the output tree, where the +// program root holds its importer: the root importer's at the root's +// node_modules, any other at its bin-relative path. It replaces what the +// importers laid there. Each directory above it that is a link becomes a real +// directory of links to its entries, so nothing is written through into the +// exec root. +func placeRuntimeLink(root, link string, importers []string) error { + execroot, err := os.Getwd() + if err != nil { + return err + } + rel := binRelative(filepath.ToSlash(link)) + if rel == "" || rel == link || !strings.HasPrefix(rel, "node_modules/") && !strings.Contains(rel, "/node_modules/") { + return fmt.Errorf("-runtime_link=%s is not an importer link in the output tree", link) + } + dir, name := "", strings.TrimPrefix(rel, "node_modules/") + if i := strings.Index(rel, "/node_modules/"); !strings.HasPrefix(rel, "node_modules/") && i >= 0 { + dir, name = rel[:i], rel[i+len("/node_modules/"):] + } + if len(importers) > 0 && filepath.ToSlash(importerDir(importers[len(importers)-1])) == dir { + rel = "node_modules/" + name + } + at := root + parts := strings.Split(rel, "/") + for _, part := range parts[:len(parts)-1] { + at = filepath.Join(at, part) + info, err := os.Lstat(at) + switch { + case errors.Is(err, fs.ErrNotExist): + if err := os.Mkdir(at, 0o755); err != nil { + return err + } + case err != nil: + return err + case info.Mode()&fs.ModeSymlink != 0: + target, err := filepath.EvalSymlinks(at) + if err != nil { + return err + } + if err := os.Remove(at); err != nil { + return err + } + if err := mergeEntries(at, target, false); err != nil { + return err + } + } + } + at = filepath.Join(at, parts[len(parts)-1]) + if err := os.RemoveAll(at); err != nil { + return err + } + return os.Symlink(filepath.Join(execroot, filepath.FromSlash(link)), at) +} diff --git a/ts/tools/tsaction/tsgo_test.go b/ts/tools/tsaction/tsgo_test.go index 099f371c..5d0cbed7 100644 --- a/ts/tools/tsaction/tsgo_test.go +++ b/ts/tools/tsaction/tsgo_test.go @@ -802,6 +802,8 @@ func TestBinRelative(t *testing.T) { for _, c := range []struct{ binPath, want, importer string }{ {binDir + "/pkg/sub/node_modules", "pkg/sub/node_modules", "pkg/sub"}, {binDir + "/node_modules", "node_modules", ""}, + {binDir + "/pkg/sub/node_modules.types/node_modules", "pkg/sub/node_modules.types/node_modules", "pkg/sub"}, + {binDir + "/node_modules.types/node_modules", "node_modules.types/node_modules", ""}, {binDir + "/pkg", "pkg", ""}, {binDir, "", ""}, } { diff --git a/ts/tools/tsaction/typeview.go b/ts/tools/tsaction/typeview.go new file mode 100644 index 00000000..cb8430be --- /dev/null +++ b/ts/tools/tsaction/typeview.go @@ -0,0 +1,109 @@ +package main + +import ( + "errors" + "flag" + "io/fs" + "os" + "path/filepath" + "strings" +) + +// typeView copies the files of an npm store tree a type checker reads: +// package.json and other JSON, TypeScript sources, declarations, and +// JavaScript TypeScript tries no declaration in place of, which an untyped +// package's importer resolves to. +func typeView(args []string) error { + flags := flag.NewFlagSet("typeview", flag.ExitOnError) + in := flags.String("in", "", "store tree to read") + out := flags.String("out", "", "directory to write the view to") + if err := flags.Parse(args); err != nil { + return err + } + if *in == "" || *out == "" { + return errors.New("typeview needs -in=DIR and -out=DIR") + } + if err := os.MkdirAll(*out, 0o755); err != nil { + return err + } + return viewDir(*in, *out) +} + +func viewDir(src, dest string) error { + entries, err := os.ReadDir(src) + if err != nil { + return err + } + for _, entry := range entries { + from := filepath.Join(src, entry.Name()) + to := filepath.Join(dest, entry.Name()) + switch { + case entry.Type()&fs.ModeSymlink != 0: + err = viewLink(from, to) + case entry.IsDir(): + err = viewDir(from, to) + case typeChecked(from): + if err = os.MkdirAll(dest, 0o755); err == nil { + err = copyFile(from, to) + } + } + if err != nil { + return err + } + } + return nil +} + +// viewLink keeps a link to a directory as the same relative link, its target +// created in the view, and copies a link to a file the view keeps as that file. +// The store tree's links stay inside its package (copyLink). +func viewLink(from, to string) error { + info, err := os.Stat(from) + if err != nil { + return err + } + if !info.IsDir() && !typeChecked(from) { + return nil + } + if err := os.MkdirAll(filepath.Dir(to), 0o755); err != nil { + return err + } + if !info.IsDir() { + return copyFile(from, to) + } + target, err := os.Readlink(from) + if err != nil { + return err + } + if err := os.MkdirAll(filepath.Join(filepath.Dir(to), target), 0o755); err != nil { + return err + } + return os.Symlink(target, to) +} + +// typeChecked reports whether TypeScript's module resolution can read path: +// a .js or .jsx stands in for its .d.ts, a .mjs for its .d.mts and a .cjs for +// its .d.cts, and no other pair. +func typeChecked(path string) bool { + name := filepath.Base(path) + for _, ext := range []string{".ts", ".tsx", ".mts", ".cts", ".json"} { + if strings.HasSuffix(name, ext) { + return true + } + } + stem := strings.TrimSuffix(path, filepath.Ext(path)) + switch filepath.Ext(name) { + case ".js", ".jsx": + return !exists(stem + ".d.ts") + case ".mjs": + return !exists(stem + ".d.mts") + case ".cjs": + return !exists(stem + ".d.cts") + } + return false +} + +func exists(path string) bool { + _, err := os.Stat(path) + return err == nil +} diff --git a/ts/tools/tsaction/typeview_test.go b/ts/tools/tsaction/typeview_test.go new file mode 100644 index 00000000..3d144408 --- /dev/null +++ b/ts/tools/tsaction/typeview_test.go @@ -0,0 +1,151 @@ +package main + +import ( + "os" + "path/filepath" + "sort" + "strings" + "testing" +) + +func TestTypeViewKeepsWhatResolutionReads(t *testing.T) { + in := t.TempDir() + for _, rel := range []string{ + "package.json", + "index.js", "index.d.ts", "index.js.map", + "esm/index.mjs", "esm/index.d.mts", + "cjs/index.cjs", "cjs/index.d.ts", + "cts/index.cjs", "cts/index.d.cts", + "untyped.js", "untyped.mjs", "untyped.cjs", + "src/a.ts", "src/b.tsx", + "data/locale.json", + "styles.css", "README.md", + "assets/logo.png", + } { + at := filepath.Join(in, rel) + if err := os.MkdirAll(filepath.Dir(at), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(at, []byte(rel), 0o644); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink("src", filepath.Join(in, "linked")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("index.d.ts", filepath.Join(in, "alias.d.ts")); err != nil { + t.Fatal(err) + } + if err := os.Symlink("index.js.map", filepath.Join(in, "alias.js.map")); err != nil { + t.Fatal(err) + } + out := filepath.Join(t.TempDir(), "view") + if err := typeView([]string{"-in=" + in, "-out=" + out}); err != nil { + t.Fatal(err) + } + var got []string + if err := filepath.Walk(out, func(p string, info os.FileInfo, err error) error { + if err != nil || info.IsDir() { + return err + } + rel, _ := filepath.Rel(out, p) + if info.Mode()&os.ModeSymlink != 0 { + target, _ := os.Readlink(p) + rel += " -> " + target + } + got = append(got, filepath.ToSlash(rel)) + return nil + }); err != nil { + t.Fatal(err) + } + sort.Strings(got) + want := []string{ + "alias.d.ts", + "cjs/index.cjs", + "cjs/index.d.ts", + "cts/index.d.cts", + "data/locale.json", + "esm/index.d.mts", + "index.d.ts", + "linked -> src", + "package.json", + "src/a.ts", + "src/b.tsx", + "untyped.cjs", + "untyped.js", + "untyped.mjs", + } + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Errorf("view holds\n%s\nwant\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +func TestRuntimeLinkReplacesTheViewWithoutWritingIntoTheExecRoot(t *testing.T) { + execroot := t.TempDir() + t.Chdir(execroot) + mkdir := func(rel string) { + if err := os.MkdirAll(filepath.Join(execroot, rel), 0o755); err != nil { + t.Fatal(err) + } + } + mkdir(binDir + "/node_modules.types/node_modules/@scope/view") + mkdir(binDir + "/node_modules.types/node_modules/zod") + mkdir(binDir + "/node_modules/.pnpm/tree") + if err := os.Symlink(".pnpm/tree", filepath.Join(execroot, binDir, "node_modules/@scope")); err != nil { + t.Fatal(err) + } + root := filepath.Join(execroot, "program") + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(execroot, binDir, "node_modules.types/node_modules"), filepath.Join(root, "node_modules")); err != nil { + t.Fatal(err) + } + if err := placeRuntimeLink(root, binDir+"/node_modules/@scope", []string{binDir + "/node_modules.types/node_modules"}); err != nil { + t.Fatal(err) + } + if info, err := os.Lstat(filepath.Join(root, "node_modules")); err != nil || info.Mode()&os.ModeSymlink != 0 { + t.Fatalf("the root importer's link is still a link: %v", err) + } + if target, err := os.Readlink(filepath.Join(root, "node_modules/@scope")); err != nil || target != filepath.Join(execroot, binDir, "node_modules/@scope") { + t.Errorf("@scope links to %q (%v), want the tree's link", target, err) + } + if _, err := os.Stat(filepath.Join(root, "node_modules/zod")); err != nil { + t.Errorf("the importer's other entries are gone: %v", err) + } + if _, err := os.Lstat(filepath.Join(execroot, binDir, "node_modules.types/node_modules/@scope/view")); err != nil { + t.Errorf("the exec root's view was changed: %v", err) + } +} + +func TestRuntimeLinkOfANestedLockfileRootLandsAtTheProgramRoot(t *testing.T) { + execroot := t.TempDir() + t.Chdir(execroot) + for _, rel := range []string{ + binDir + "/apps/node_modules.types/node_modules/zod", + binDir + "/apps/node_modules/.pnpm/tree", + } { + if err := os.MkdirAll(filepath.Join(execroot, rel), 0o755); err != nil { + t.Fatal(err) + } + } + if err := os.Symlink(".pnpm/tree", filepath.Join(execroot, binDir, "apps/node_modules/config")); err != nil { + t.Fatal(err) + } + root := filepath.Join(execroot, "program") + if err := os.MkdirAll(root, 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink(filepath.Join(execroot, binDir, "apps/node_modules.types/node_modules"), filepath.Join(root, "node_modules")); err != nil { + t.Fatal(err) + } + if err := placeRuntimeLink(root, binDir+"/apps/node_modules/config", []string{binDir + "/apps/node_modules.types/node_modules"}); err != nil { + t.Fatal(err) + } + if target, err := os.Readlink(filepath.Join(root, "node_modules/config")); err != nil || target != filepath.Join(execroot, binDir, "apps/node_modules/config") { + t.Errorf("the root importer's config link is %q (%v), want it at the program root's node_modules", target, err) + } + if _, err := os.Lstat(filepath.Join(root, "apps/node_modules")); err == nil { + t.Errorf("the link was laid at its bin-relative path, which no walk from the program root reaches") + } +}