diff --git a/changelog.d/412.md b/changelog.d/412.md new file mode 100644 index 000000000..9d1dcb86e --- /dev/null +++ b/changelog.d/412.md @@ -0,0 +1,5 @@ +--- +section: fixes +--- + +- **Built-in extractors read a JSON manifest with a byte order mark as Node does** (#412). `typescript-public-api` no longer fails on a repository holding a `package.json` that starts with a UTF-8 byte order mark (such as vite's `playground/resolve/utf8-bom-package`), and it now parses only the manifests of the packages it extracts, so an unrelated fixture's invalid `package.json` no longer fails the extraction. `workspace-dependencies` ignores a byte order mark in `package-lock.json`, `bun.lock` and `pnpm-workspace.yaml` too, and `projections explore` proposes a TypeScript package whose manifest or tsconfig starts with one. The extractor SDK exports `without_bom` for JSON read without `read_json`. diff --git a/docs/reference/extractor-sdk.md b/docs/reference/extractor-sdk.md index 26ea1f51d..50fec8d44 100644 --- a/docs/reference/extractor-sdk.md +++ b/docs/reference/extractor-sdk.md @@ -425,6 +425,17 @@ pub fn within(scope: &[String], relative: &str) -> bool Whether `relative` is `scope` or inside it. +### `without_bom` + +```rust +pub fn without_bom(text: &str) -> &str +``` + +`text` without a leading UTF-8 byte order mark, which RFC 8259 lets a JSON +parser ignore and some editors write. `read_json` and +`crate::Context::read_json` drop it already; use this for JSON (a lockfile, +a package manifest) read another way. + ## Types ### `Access` diff --git a/packages/cli/src/explore/typescript.rs b/packages/cli/src/explore/typescript.rs index e4ba07c1a..8525d0106 100644 --- a/packages/cli/src/explore/typescript.rs +++ b/packages/cli/src/explore/typescript.rs @@ -6,6 +6,7 @@ //! extractor's one proposal, marked as needing configuration. Each says when the repository's own TypeScript, which //! the extractor uses, isn't installed or is TypeScript 7's native compiler without the compiler API. +use projections_extractor_sdk::without_bom; use serde_json::{Value, json}; use std::collections::BTreeSet; use std::path::Path; @@ -43,8 +44,8 @@ pub(super) fn candidates( .into_iter() .filter_map(|manifest| { let directory = manifest.strip_suffix("package.json").unwrap_or_default().trim_end_matches('/'); - let text = std::fs::read(project.join(manifest)).ok()?; - let value: Value = serde_json::from_slice(&text).ok()?; + let text = json_text(&project.join(manifest))?; + let value: Value = serde_json::from_str(&text).ok()?; if ["exports", "types", "typings"].iter().all(|field| value.get(*field).is_none()) { return None; } @@ -52,13 +53,13 @@ pub(super) fn candidates( if value["private"] == true && !value["name"].as_str().is_some_and(|name| depended.contains(name)) { return None; } - let (exports, skipped) = entries::exports(&text, directory); + let (exports, skipped) = entries::exports(text.as_bytes(), directory); let package = Package { directory, manifest: &value, exports: &exports, skipped, - tables: versions::Tables::of(&text), + tables: versions::Tables::of(text.as_bytes()), version: version(&project, directory), }; let plan = plan(&project, files, &listed, &package)?; @@ -109,7 +110,7 @@ pub(super) fn candidates( fn workspace_dependencies(project: &Path, manifests: &[&String]) -> BTreeSet { let read: Vec = manifests .iter() - .filter_map(|manifest| serde_json::from_slice::(&std::fs::read(project.join(manifest)).ok()?).ok()) + .filter_map(|manifest| serde_json::from_str::(&json_text(&project.join(manifest))?).ok()) .collect(); let names: BTreeSet<&str> = read.iter().filter_map(|value| value["name"].as_str()).collect(); read.iter() @@ -140,6 +141,12 @@ fn unique(seen: &mut std::collections::BTreeSet, name: String, directory } } +/// The text of the JSON file (a package manifest, a tsconfig) at `path`, as Node and the TypeScript compiler read it: +/// without a leading byte order mark. `None` when it can't be read as UTF-8. +fn json_text(path: &Path) -> Option { + std::fs::read_to_string(path).ok().map(|text| without_bom(&text).to_owned()) +} + fn adopted<'a>(authored: &[&'a Value]) -> Option<&'a str> { authored .iter() @@ -166,8 +173,8 @@ fn package(project: &Path, directory: &str, package: &str) -> Option { .join(directory) .ancestors() .take_while(|ancestor| ancestor.starts_with(project)) - .find_map(|ancestor| std::fs::read(ancestor.join("node_modules").join(package).join("package.json")).ok()) - .map(|bytes| serde_json::from_slice(&bytes).unwrap_or(Value::Null)) + .find_map(|ancestor| json_text(&ancestor.join("node_modules").join(package).join("package.json"))) + .map(|text| serde_json::from_str(&text).unwrap_or(Value::Null)) } /// Why the extractor can't run yet in `directory` (project-relative): the repository's own `typescript` isn't installed @@ -230,7 +237,7 @@ fn install_command(project: &Path, directory: &str) -> &'static str { }); let declared = || { ancestors.iter().find_map(|ancestor| { - let manifest: Value = serde_json::from_slice(&std::fs::read(ancestor.join("package.json")).ok()?).ok()?; + let manifest: Value = serde_json::from_str(&json_text(&ancestor.join("package.json"))?).ok()?; let name = manifest["packageManager"].as_str()?.split('@').next()?; ["bun", "pnpm", "yarn", "npm"] .into_iter() @@ -347,6 +354,22 @@ mod tests { candidates(root, &descriptor, files, &[], "**/tsconfig.json", 1) } + #[test] + fn manifests_and_tsconfigs_with_a_byte_order_mark_read_as_node_reads_them() { + let (root, files) = repository(&[ + ( + "packages/sdk/package.json", + "\u{feff}{\"name\": \"@acme/sdk\", \"exports\": {\".\": \"./src/index.ts\"}}", + ), + ("packages/sdk/tsconfig.json", "\u{feff}{\"include\": [\"src\"]}"), + ("packages/sdk/src/index.ts", "export const sdk = 1;"), + ]); + let found = proposals(root.path(), &files); + assert_eq!(found.len(), 1, "{found:?}"); + assert_eq!(found[0]["id"], "typescript-public-api-sdk"); + assert_eq!(found[0]["definition"]["inputs"], json!({"tsconfig": "packages/sdk/tsconfig.json"})); + } + #[test] fn the_tsconfig_that_includes_the_entry_points_is_chosen() { let options = r#""compilerOptions": {"strict": true}"#; diff --git a/packages/cli/src/explore/typescript/tsconfig.rs b/packages/cli/src/explore/typescript/tsconfig.rs index 69b690116..8b5f5aa4b 100644 --- a/packages/cli/src/explore/typescript/tsconfig.rs +++ b/packages/cli/src/explore/typescript/tsconfig.rs @@ -99,7 +99,7 @@ impl Tsconfig { } fn read_at(project: &Path, path: &str, depth: usize) -> Option { - let value = jsonc(&std::fs::read_to_string(project.join(path)).ok()?)?; + let value = jsonc(&super::json_text(&project.join(path))?)?; let directory = parent(path); let resolve = |items: Vec| items.iter().filter_map(|item| join(directory, item)).collect::>(); let mut config = Self::default(); diff --git a/packages/extractors/sdk/src/lib.rs b/packages/extractors/sdk/src/lib.rs index db08ee4cf..77364c1f3 100644 --- a/packages/extractors/sdk/src/lib.rs +++ b/packages/extractors/sdk/src/lib.rs @@ -20,7 +20,7 @@ pub use entry::{main, serve}; pub use generation::{Basis, Generations, MAX_BASIS_PART_BYTES, MAX_BASIS_PARTS, basis_digest, sha256}; pub use paths::{ Scratch, basename, canonical, glob, globs, parent, path, project_path, read_file, read_json, read_source, relative_path, - repository_files, repository_path, slashed, windows_reason, + repository_files, repository_path, slashed, windows_reason, without_bom, }; pub use process::{Failure, MAX_STDERR, MAX_STDOUT, Output, spawn}; pub use source::{FileEntry, within}; diff --git a/packages/extractors/sdk/src/paths.rs b/packages/extractors/sdk/src/paths.rs index dcb628f81..9aba35748 100644 --- a/packages/extractors/sdk/src/paths.rs +++ b/packages/extractors/sdk/src/paths.rs @@ -199,8 +199,10 @@ pub fn read_json(root: &Path, relative: &str) -> Result { } /// `text` without a leading UTF-8 byte order mark, which RFC 8259 lets a JSON -/// parser ignore and some editors write. -pub(crate) fn without_bom(text: &str) -> &str { +/// parser ignore and some editors write. [`read_json`] and +/// [`crate::Context::read_json`] drop it already; use this for JSON (a lockfile, +/// a package manifest) read another way. +pub fn without_bom(text: &str) -> &str { text.strip_prefix('\u{feff}').unwrap_or(text) } diff --git a/packages/extractors/typescript-support/src/json/parse.ts b/packages/extractors/typescript-support/src/json/parse.ts index eb20da948..398b5ff50 100644 --- a/packages/extractors/typescript-support/src/json/parse.ts +++ b/packages/extractors/typescript-support/src/json/parse.ts @@ -1,3 +1,6 @@ +/** `text` without a leading UTF-8 byte order mark, which Node, npm and the TypeScript compiler ignore in JSON files. */ +export const withoutBom = (text: string): string => (text.startsWith('\uFEFF') ? text.slice(1) : text) + // The worker request must not erase duplicate keys before validation. export function parseJson(source: string): unknown { let cursor = 0 diff --git a/packages/extractors/typescript-support/src/shared.ts b/packages/extractors/typescript-support/src/shared.ts index 7a9ae9fd2..eeb072baa 100644 --- a/packages/extractors/typescript-support/src/shared.ts +++ b/packages/extractors/typescript-support/src/shared.ts @@ -1,6 +1,6 @@ import {lstat, readFile, realpath} from 'node:fs/promises' import path from 'node:path' -import {parseJson} from './json/parse.js' +import {parseJson, withoutBom} from './json/parse.js' import type {ExtractorRequest, Entity, Relationship, Extraction, Json, DomainSchema} from './types.js' import type {Toolchain} from './toolchain.js' import type {WorkerExtractorId} from './ids.js' @@ -84,7 +84,7 @@ export async function readSource(context: ExtractorContext, relative: string): P export async function readJson(context: ExtractorContext, relative: string): Promise { try { - return parseJson(await readSource(context, relative)) + return parseJson(withoutBom(await readSource(context, relative))) } catch (error) { throw new Error(`Cannot read JSON input ${relative}: ${error instanceof Error ? error.message : String(error)}`, {cause: error}) } diff --git a/packages/extractors/typescript-support/src/toolchain.ts b/packages/extractors/typescript-support/src/toolchain.ts index 4cde5a6e3..bdc667da3 100644 --- a/packages/extractors/typescript-support/src/toolchain.ts +++ b/packages/extractors/typescript-support/src/toolchain.ts @@ -2,6 +2,7 @@ import {existsSync, readFileSync, realpathSync, statSync} from 'node:fs' import {createRequire} from 'node:module' import path from 'node:path' import type * as TypeScript from 'typescript' +import {withoutBom} from './json/parse.js' /** * The examined repository's own Node packages. Revisions are materialized without @@ -59,7 +60,7 @@ export function resolvePackage(toolchain: Toolchain, start: string, name: string `Install ${name} in the repository itself; Projections never uses global or ancestor installations.`, ) } - const parsed = JSON.parse(readFileSync(real, 'utf8')) as {name?: unknown; version?: unknown} + const parsed = JSON.parse(withoutBom(readFileSync(real, 'utf8'))) as {name?: unknown; version?: unknown} if (parsed.name !== name || typeof parsed.version !== 'string') throw new Error(`Invalid installed ${name} package manifest: ${real}`) return {name, version: parsed.version, directory: path.dirname(real)} } diff --git a/packages/extractors/typescript-support/src/typescript/files.ts b/packages/extractors/typescript-support/src/typescript/files.ts index bb445014d..d120e97c6 100644 --- a/packages/extractors/typescript-support/src/typescript/files.ts +++ b/packages/extractors/typescript-support/src/typescript/files.ts @@ -1,6 +1,7 @@ import path from 'node:path' import {lstat, readdir, readFile} from 'node:fs/promises' import {containedIn, containedPath, type ExtractorContext} from '../shared.js' +import {withoutBom} from '../json/parse.js' import {absent, code, slash} from './model.js' /** @@ -109,7 +110,8 @@ export class SourceFiles { return false } if (stat.size > 32 * 1024 * 1024) throw new Error(`Input must be a regular file under 32 MiB: ${code(relative)}`) - const text = this.texts.get(key) ?? (await readFile(read, 'utf8')) + // The compiler's own `sys.readFile` drops a byte order mark too, so manifests and sources read as `tsc` reads them. + const text = this.texts.get(key) ?? withoutBom(await readFile(read, 'utf8')) this.texts.set(file, text) if (key !== file) { this.aliases.set(file, key) diff --git a/packages/extractors/typescript-support/src/typescript/packages.ts b/packages/extractors/typescript-support/src/typescript/packages.ts index 33777da98..0ddab810e 100644 --- a/packages/extractors/typescript-support/src/typescript/packages.ts +++ b/packages/extractors/typescript-support/src/typescript/packages.ts @@ -7,35 +7,51 @@ import type {SourceFiles} from './files.js' const deepestFirst = (a: Package, b: Package): number => b.directory.length - a.directory.length || compareIds(a.name, b.name) -/** Every loaded repository package manifest, deepest first. */ -function manifests(files: SourceFiles): Package[] { +/** A loaded repository package manifest, not yet parsed. */ +interface Manifest { + file: string + directory: string + text: string +} + +/** + * Every loaded repository package manifest, deepest first. Owning a file takes only the manifest's directory, so + * none is parsed here: an unrelated fixture's manifest that isn't JSON can't fail the extraction of another package. + */ +function manifests(files: SourceFiles): Manifest[] { const {root, texts, aliases} = files - const candidates: Package[] = [] + const found: Manifest[] = [] for (const [file, text] of texts) { if (path.basename(file) !== 'package.json' || aliases.has(file) || file.includes(`${path.sep}node_modules${path.sep}`)) continue - let manifest: Record - try { - manifest = record(JSON.parse(text), slash(path.relative(root, file))) - } catch (error) { - throw new Error(`Invalid package manifest ${code(slash(path.relative(root, file)))}: ${String(error)}`, {cause: error}) - } - const directory = slash(path.relative(root, path.dirname(file))) - const name = typeof manifest.name === 'string' && manifest.name.trim() ? manifest.name : directory || '(root)' - candidates.push({name, directory, manifest}) + found.push({file, directory: slash(path.relative(root, path.dirname(file))), text}) + } + return found.toSorted((a, b) => b.directory.length - a.directory.length || compareIds(a.directory, b.directory)) +} + +/** The package an API package's manifest declares; a manifest that isn't a JSON object fails the extraction. */ +function parse(files: SourceFiles, {file, directory, text}: Manifest): Package { + const relative = slash(path.relative(files.root, file)) + let manifest: Record + try { + manifest = record(JSON.parse(text), relative) + } catch (error) { + throw new Error(`Invalid package manifest ${code(relative)}: ${String(error)}`, {cause: error}) } - return candidates.toSorted(deepestFirst) + const name = typeof manifest.name === 'string' && manifest.name.trim() ? manifest.name : directory || '(root)' + return {name, directory, manifest} } /** * The API packages are those owning the selected program's root files (the * tsconfig's files or the entry points), not every manifest in the tree: a * monorepo's unrelated packages and fixtures neither contribute exports nor - * need unique names. Without entry points, a package's own tsconfig selects - * only that package, even when it includes another's sources. + * need unique names, and only the API packages' manifests are parsed. Without + * entry points, a package's own tsconfig selects only that package, even when + * it includes another's sources. */ export function apiPackages(files: SourceFiles, programs: ts.Program[], entryFiles: string[], configs: string[]): Package[] { const candidates = manifests(files) - const ownerOf = (relative: string): Package | undefined => + const ownerOf = (relative: string): Manifest | undefined => candidates.find(item => !item.directory || relative === item.directory || relative.startsWith(`${item.directory}/`)) const configured = configs.map(config => ownerOf(slash(path.dirname(path.normalize(config))))) const only = !entryFiles.length && configured.length && configured.every(pkg => pkg?.directory) ? new Set(configured) : undefined @@ -47,10 +63,12 @@ export function apiPackages(files: SourceFiles, programs: ts.Program[], entryFil const owners = [...rootFiles].map(file => ownerOf(slash(path.relative(files.root, file)))) const selected = only && owners.some(pkg => pkg && only.has(pkg)) ? only : undefined const packages: Package[] = [] + const parsed = new Set() for (const file of [...rootFiles].toSorted()) { - const relative = slash(path.relative(files.root, file)) - const pkg = ownerOf(relative) - if (pkg && !packages.includes(pkg) && (!selected || selected.has(pkg))) { + const owner = ownerOf(slash(path.relative(files.root, file))) + if (owner && !parsed.has(owner) && (!selected || selected.has(owner))) { + parsed.add(owner) + const pkg = parse(files, owner) if (packages.some(other => other.name === pkg.name)) { throw new Error(`Duplicate package name ${code(pkg.name)}; package identities must be unique`) } diff --git a/packages/extractors/typescript-support/test/collectors-typescript.test.ts b/packages/extractors/typescript-support/test/collectors-typescript.test.ts index c6b5023d3..83a1db7b2 100644 --- a/packages/extractors/typescript-support/test/collectors-typescript.test.ts +++ b/packages/extractors/typescript-support/test/collectors-typescript.test.ts @@ -852,6 +852,30 @@ test('run on a checkout, installed packages and tagged build caches are not prog ['value'], ) }) +test('a byte order mark before a manifest is ignored, and only the API packages’ manifests are parsed', async t => { + const bom = '\uFEFF' + const context = await fixture( + t, + { + 'package.json': bom + JSON.stringify({name: '@example/app', types: './index.ts'}), + 'tsconfig.json': bom + JSON.stringify({compilerOptions: {strict: true, types: [], noEmit: true}, files: ['index.ts']}), + 'index.ts': 'export const value = 1', + // Unrelated fixtures (as in vite's playground): one with a byte order mark, one that isn't JSON. + 'playground/utf8-bom-package/package.json': bom + JSON.stringify({name: '@example/utf8-bom-package', main: './index.js'}), + 'fixtures/broken/package.json': '{"name": "broken",', + }, + 'typescript-public-api', + {tsconfig: 'tsconfig.json'}, + ) + const state = await collectTypeScript(context) + assert.deepEqual( + state.entities.map(node => [node.label, node.data?.package]), + [['value', '@example/app']], + ) + // The API package's own manifest must still be JSON. + await writeFile(path.join(context.input.repository.root, 'package.json'), '{"name": "@example/app",') + await assert.rejects(collectTypeScript(context), /Invalid package manifest \x60package\.json\x60/u) +}) test('a monorepo: workspace symlinks are followed and only the selected packages need unique names', async t => { const context = await fixture( t, diff --git a/packages/extractors/workspace-dependencies/src/lib.rs b/packages/extractors/workspace-dependencies/src/lib.rs index 9c462b412..d8e650495 100644 --- a/packages/extractors/workspace-dependencies/src/lib.rs +++ b/packages/extractors/workspace-dependencies/src/lib.rs @@ -11,7 +11,7 @@ mod workspace; use anyhow::{Context as _, Result}; use lockfile::Lockfile; pub use manager::Manager; -use projections_extractor_sdk::{Context, Descriptor, Trust, extraction, input, object, repository_path}; +use projections_extractor_sdk::{Context, Descriptor, Trust, extraction, input, object, repository_path, without_bom}; use serde_json::{Value, json}; use std::collections::{BTreeMap, BTreeSet}; use workspace::{Package, Workspace}; @@ -64,7 +64,8 @@ pub fn collect(cx: &Context) -> Result { let read_text = |name: &str| -> Result> { let file = format!("{base}{name}"); if present.contains(file.as_str()) { - Ok(Some(cx.read_source(&file)?)) + // Lockfiles and pnpm-workspace.yaml read as their package managers read them: a byte order mark is ignored. + Ok(Some(without_bom(&cx.read_source(&file)?).to_owned())) } else { Ok(None) } diff --git a/packages/extractors/workspace-dependencies/tests/managers.rs b/packages/extractors/workspace-dependencies/tests/managers.rs index de9d704ff..c3522f55b 100644 --- a/packages/extractors/workspace-dependencies/tests/managers.rs +++ b/packages/extractors/workspace-dependencies/tests/managers.rs @@ -507,3 +507,40 @@ fn a_manifest_with_a_byte_order_mark_reads_as_node_reads_it() { let extraction = extract(&scratch.0, json!({})).unwrap(); assert_eq!(entity(&extraction, "workspace:a")["label"], "a"); } + +#[test] +fn lockfiles_and_workspace_files_with_a_byte_order_mark_read_as_their_managers_read_them() { + const BOM: &str = "\u{feff}"; + let npm = Scratch::new( + "bom-npm", + &[ + ( + "package.json", + &format!(r#"{BOM}{{"name":"x","dependencies":{{"is-number":"^7.0.0"}}}}"#), + ), + ( + "package-lock.json", + &format!(r#"{BOM}{{"lockfileVersion":3,"packages":{{"":{{"name":"x"}},"node_modules/is-number":{{"version":"7.0.0"}}}}}}"#), + ), + ], + ); + let extraction = extract(&npm.0, json!({})).unwrap(); + assert_eq!(entity(&extraction, "package:is-number")["data"]["version"], "7.0.0"); + // A fixture package like vite's `playground/resolve/utf8-bom-package`, a member through pnpm-workspace.yaml. + let pnpm = Scratch::new( + "bom-pnpm", + &[ + ("package.json", r#"{"name":"x","packageManager":"pnpm@10.0.0"}"#), + ("pnpm-workspace.yaml", &format!("{BOM}packages:\n - playground/**\n")), + ( + "playground/resolve/utf8-bom-package/package.json", + &format!(r#"{BOM}{{"name":"@vitejs/test-utf8-bom-package"}}"#), + ), + ], + ); + let extraction = extract(&pnpm.0, json!({})).unwrap(); + assert_eq!( + entity(&extraction, "workspace:@vitejs/test-utf8-bom-package")["data"]["path"], + "playground/resolve/utf8-bom-package" + ); +}