Skip to content
Open
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion src/runtime/cli/create_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -846,7 +846,7 @@ impl CreateCommand {
let parsed = match JSON::parse_package_json_utf8_with_opts(
JSON::JSONOptions {
guess_indentation: true,
..JSON::JSONOptions::DEFAULT
..JSON::PACKAGE_JSON_OPTS
},
&source,
log,
Expand Down
24 changes: 13 additions & 11 deletions src/runtime/cli/pm_diff_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,7 @@ fn package_name_in(tree: &Tree) -> Vec<u8> {
fn package_json_name(bytes: &[u8]) -> Option<Vec<u8>> {
let bump = Bump::new();
let src: &[u8] = bump.alloc_slice_copy(bytes);
let json = bun_parsers::json::parse_utf8(
let json = bun_parsers::json::parse_package_json_utf8(
&bun_ast::Source::init_path_string(b"package.json", src),
&mut bun_ast::Log::init(),
&bump,
Expand Down Expand Up @@ -624,7 +624,7 @@ fn read_dir_tree(
let manifests = as_published_by.and_then(|pm| manifests_for(pm, root, &pkg));
let bump = Bump::new();
let src: &[u8] = bump.alloc_slice_copy(&pkg);
if let Ok(json) = bun_parsers::json::parse_utf8(
if let Ok(json) = bun_parsers::json::parse_package_json_utf8(
&bun_ast::Source::init_path_string(b"package.json", src),
&mut bun_ast::Log::init(),
&bump,
Expand Down Expand Up @@ -2248,18 +2248,20 @@ fn install_view(json: &bun_ast::Expr, field: &[u8], bump: &Bump) -> Vec<(Vec<u8>

fn package_json_notes(left: &Tree, right: &Tree, notes: &mut Vec<String>, colors: bool) {
let bump = Bump::new();
let parse = |bytes: &[u8]| {
let source = |bytes: &[u8]| {
let src: &[u8] = bump.alloc_slice_copy(bytes);
bun_parsers::json::parse_utf8(
&bun_ast::Source::init_path_string(b"package.json", src),
&mut bun_ast::Log::init(),
&bump,
)
.ok()
bun_ast::Source::init_path_string(b"package.json", src)
};
let parse_file = |bytes: &[u8]| {
bun_parsers::json::parse_package_json_utf8(&source(bytes), &mut bun_ast::Log::init(), &bump)
.ok()
};
let parse_entry = |bytes: &[u8]| {
bun_parsers::json::parse_utf8(&source(bytes), &mut bun_ast::Log::init(), &bump).ok()
};
let mut side = |tree: &Tree| -> Option<Manifest> {
let file = parse(tree.files.get(b"package.json".as_slice())?)?;
let entry = tree.registry_entry.as_deref().and_then(parse);
let file = parse_file(tree.files.get(b"package.json".as_slice())?)?;
let entry = tree.registry_entry.as_deref().and_then(parse_entry);
let mut overridden = Vec::new();
for field in INSTALL_FIELDS {
let Some(entry) = &entry else { break };
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/cli/pm_trusted_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -606,7 +606,7 @@ impl TrustCommand {

let bump = Bump::new();
// SAFETY: `ctx.log` set by `Command::init`, non-null for the command.
let mut package_json: bun_ast::Expr = match bun_parsers::json::parse_utf8(
let mut package_json: bun_ast::Expr = match bun_parsers::json::parse_package_json_utf8(
Comment thread
robobun marked this conversation as resolved.
Resolved
&package_json_source,
unsafe { ctx.log_mut() },
&bump,
Expand Down
3 changes: 2 additions & 1 deletion src/runtime/cli/pm_view_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,8 @@ pub(crate) fn view(
let str: &[u8] = bump.alloc_slice_copy(&str);
let source = &bun_ast::Source::init_path_string(b"package.json", str);
let mut pkg_log = bun_ast::Log::init();
let Ok(pkg_json) = JSON::parse_utf8(source, &mut pkg_log, &bump) else {
let Ok(pkg_json) = JSON::parse_package_json_utf8(source, &mut pkg_log, &bump)
else {
break 'from_package_json;
};
if let Some(name) = string_of(&pkg_json, &bump, b"name").filter(|n| !n.is_empty()) {
Expand Down
27 changes: 27 additions & 0 deletions test/cli/install/bun-create.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1169,6 +1169,33 @@ it.concurrent("should preserve package.json indentation from the template", asyn
expect(exitCode).toBe(0);
});

// `bun install` reads package.json with comments and trailing commas allowed, so a template may use them.
describe.concurrent.each(["local", "GitHub"])("the package.json of a %s template", kind => {
const fields = `"name": "tpl",\n "version": "1.0.0",\n "bun-create": { "start": "bun run go" }`;

it.each([
["a trailing comma", `{\n ${fields},\n}\n`],
["a comment", `{\n // note\n ${fields}\n}\n`],
])("gets the transforms when it has %s", async (_, manifest) => {
using github = await serveGithub({ "package.json": manifest });
using dir = tempDir("create-package-json-dialect", { "bun-create/tpl/package.json": manifest });
const created = await create(
String(dir),
[kind === "local" ? "tpl" : "dylan-conway/create-test", "dest", "--no-install", "--no-git"],
github.env,
);

expect(created).toEqual({
out: expect.stringContaining("\n cd dest\n bun run go\n"),
err: expect.not.stringContaining("error:"),
exitCode: 0,
});
// Read as JSONC: a rewrite can keep the comment of the template.
const written = await Bun.file(join(String(dir), "dest", "package.json")).text();
expect(Bun.JSONC.parse(written)).toEqual({ name: "dest", version: "1.0.0" });
});
});

// Windows copies from and to absolute paths, so a home directory like C:\Users\José is part of both.
it.concurrent.each([
["josé", "dest"],
Expand Down
175 changes: 175 additions & 0 deletions test/cli/install/package-json-comments.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
Comment thread
robobun marked this conversation as resolved.
Resolved
import { exists } from "fs/promises";
import { bunEnv, bunExe, tempDir } from "harness";
import { join } from "node:path";

// `bun install` reads package.json with comments and trailing commas allowed. Every command below reads a
// package.json too, so it has to take the file that `bun install` takes.
// `bun create` reads the package.json of a template: bun-create.test.ts has those cases.
const dialects = [
["a trailing comma", (pkg: object) => JSON.stringify(pkg, null, 2).replace(/\n}$/, ",\n}\n")],
["a comment", (pkg: object) => JSON.stringify(pkg, null, 2).replace(/^{/, "{\n // note") + "\n"],
] as const;

const tarball = (files: Record<string, string>) => new Bun.Archive(files, { compress: "gzip" }).bytes();
// A command that writes package.json back can keep the comments or drop them. Both are read here.
const readManifest = async (path: string) => Bun.JSONC.parse(await Bun.file(path).text());

// A registry that has every package name at 1.0.0 and 2.0.0 (latest).
let registry: ReturnType<typeof Bun.serve>;
beforeAll(() => {
registry = Bun.serve({
port: 0,
async fetch(req) {
const [name, , file] = decodeURIComponent(new URL(req.url).pathname).slice(1).split("/");
if (file === undefined) {
const versions: Record<string, object> = {};
for (const version of ["1.0.0", "2.0.0"]) {
const dist = { tarball: `${registry.url.origin}/${name}/-/${name}-${version}.tgz` };
versions[version] = { name, version, dist };
}
return Response.json({ name, "dist-tags": { latest: "2.0.0" }, versions });
}
const version = file.slice(name.length + 1, -".tgz".length);
return new Response(
await tarball({
"package/package.json": JSON.stringify({ name, version }),
"package/index.js": `module.exports = "${version}";\n`,
}),
);
},
});
});
afterAll(() => registry?.stop(true));

async function run(cwd: string, args: string[], env: Record<string, string> = {}) {
await using proc = Bun.spawn({
cmd: [bunExe(), ...args],
cwd,
env: { ...bunEnv, NPM_CONFIG_REGISTRY: registry.url.origin, BUN_CONFIG_REGISTRY: registry.url.origin, ...env },
stdin: "ignore",
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([proc.stdout.text(), proc.stderr.text(), proc.exited]);
return { stdout, stderr, exitCode };
}

describe.each(dialects)("a package.json with %s", (_, write) => {
describe.concurrent("bun pm trust", () => {
const cache = (root: string) => ({ BUN_INSTALL_CACHE_DIR: join(root, ".cache") });
const ran = (root: string) => exists(join(root, "node_modules", "q", "ran.txt"));

// `q` has a postinstall script. `bun install` blocks it until `q` is trusted.
async function installUntrusted(root: string) {
const q = { name: "q", version: "1.0.0", scripts: { postinstall: "echo ran > ran.txt" } };
await Bun.write(join(root, "q.tgz"), await tarball({ "package/package.json": JSON.stringify(q) }));
expect(await run(root, ["install"], cache(root))).toMatchObject({
stderr: expect.not.stringContaining("error:"),
exitCode: 0,
});
expect(await ran(root)).toBeFalse();
}

const trusted = {
stdout: expect.stringContaining("1 script ran across 1 package"),
stderr: expect.not.stringContaining("error:"),
exitCode: 0,
};

async function expectRecorded(root: string, manifest: object) {
expect(await ran(root)).toBeTrue();
expect(await readManifest(join(root, "package.json"))).toEqual({ ...manifest, trustedDependencies: ["q"] });
expect(await Bun.file(join(root, "bun.lock")).text()).toContain(`"trustedDependencies": [\n "q",\n ],`);
}

test("runs the script and records the trust", async () => {
const manifest = { name: "app", dependencies: { q: "file:./q.tgz" } };
using dir = tempDir("package-json-comments-trust", { "package.json": write(manifest) });
const root = String(dir);
await installUntrusted(root);

expect(await run(root, ["pm", "trust", "q"], cache(root))).toEqual(trusted);
await expectRecorded(root, manifest);
});

test("--all from a workspace member records the trust in the workspace root", async () => {
const manifest = { name: "app", workspaces: ["packages/*"], dependencies: { q: "file:./q.tgz" } };
using dir = tempDir("package-json-comments-trust-all", {
"package.json": write(manifest),
"packages/member/package.json": JSON.stringify({ name: "member", version: "1.0.0" }),
});
const root = String(dir);
await installUntrusted(root);

const member = join(root, "packages", "member");
expect(await run(member, ["pm", "trust", "--all"], cache(root))).toEqual(trusted);
await expectRecorded(root, manifest);
});
});

describe.concurrent("bun pm diff", () => {
test("the notes report a new install script", async () => {
using dir = tempDir("package-json-comments-notes", {});
const before = { name: "diffme", version: "1.0.0" };
const after = { name: "diffme", version: "2.0.0", scripts: { postinstall: "node setup.js" } };
await Bun.write(join(String(dir), "a.tgz"), await tarball({ "package/package.json": JSON.stringify(before) }));
await Bun.write(join(String(dir), "b.tgz"), await tarball({ "package/package.json": write(after) }));

const { stdout, stderr, exitCode } = await run(String(dir), ["pm", "diff", "./a.tgz", "./b.tgz", "--json"]);
expect(stderr).toBe("");
expect(JSON.parse(stdout).notes).toEqual(["postinstall script added: node setup.js"]);
expect(exitCode).toBe(0);
});

test("a folder is read as `bun pm pack` would publish it", async () => {
using dir = tempDir("package-json-comments-folder", {
"a/package.json": JSON.stringify({ name: "p", version: "1.0.0", files: ["index.js"] }),
"a/index.js": "module.exports = 1;\n",
"b/package.json": write({ name: "p", version: "1.0.1", files: ["index.js"] }),
"b/index.js": "module.exports = 2;\n",
"b/secret.txt": "not in `files`\n",
});

const { stdout, stderr, exitCode } = await run(String(dir), ["pm", "diff", "./a", "./b", "--name-only"]);
expect(stderr).toBe("");
expect(stdout.split("\n").filter(line => /^[AMD] /.test(line))).toEqual(["M index.js", "M package.json"]);
expect(exitCode).toBe(0);
});

test("a folder then a bare version: the registry side takes the package name of the folder", async () => {
using dir = tempDir("package-json-comments-name", {
"pkg/package.json": write({ name: "diffme", version: "3.0.0" }),
});

const { stdout, stderr, exitCode } = await run(String(dir), ["pm", "diff", "./pkg", "1.0.0", "--name-only"]);
expect(stderr).toBe("");
expect(stdout.split("\n")[0]).toBe("./pkg → diffme@1.0.0");
expect(exitCode).toBe(0);
});

test("no arguments inside the package folder: what is published → this folder", async () => {
using dir = tempDir("package-json-comments-cwd", {
"package.json": write({ name: "diffme", version: "3.0.0" }),
});

const { stdout, stderr, exitCode } = await run(String(dir), ["pm", "diff", "--name-only"]);
expect(stderr).toBe("");
expect(stdout.split("\n")[0]).toBe("diffme@2.0.0 → .");
expect(exitCode).toBe(0);
});
});

describe.concurrent("bun info, bun pm view", () => {
test.each(["info", "pm view"])("bun %s with no name looks up the name in package.json", async command => {
using dir = tempDir("package-json-comments-info", {
"package.json": write({ name: "named-in-package-json", version: "1.0.0" }),
});

const { stdout, stderr, exitCode } = await run(String(dir), [...command.split(" "), "--json"]);
expect(stderr).toBe("");
expect(JSON.parse(stdout).name).toBe("named-in-package-json");
expect(exitCode).toBe(0);
});
});
});
Loading