Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 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
60 changes: 15 additions & 45 deletions src/runtime/webcore/Blob.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1371,12 +1371,8 @@
let slice = content_type_str.slice();
if is_valid_blob_type(slice) {
self.content_type_was_set.set(true);
self.content_type.set(
match global_this.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
},
);
self.content_type
.set(BlobContentType::from_lowercased(slice));
}
}
} else if !options_object.is_empty_or_undefined_or_null() {
Expand Down Expand Up @@ -1791,12 +1787,8 @@
let slice = content_type_str.slice();
if is_valid_blob_type(slice) {
self.content_type_was_set.set(true);
self.content_type.set(
match global_this.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
},
);
self.content_type
.set(BlobContentType::from_lowercased(slice));
}
}

Expand Down Expand Up @@ -2016,17 +2008,10 @@
blob.offset.set(offset);
blob.size.set(len);

let content_type_was_allocated = content_type.is_owned() && !content_type.is_empty();
// infer the content type if it was not specified
if content_type.is_empty()
&& matches!(self.content_type.get(), BlobContentType::Static(s) if !s.is_empty())
{
blob.content_type.set(self.content_type.get().clone());
} else {
blob.content_type.set(content_type);
}
blob.content_type_was_set
.set(self.content_type_was_set.get() || content_type_was_allocated);
// File API: a slice()'s type is the caller-supplied contentType (or "" if
// omitted/invalid); it never inherits the parent blob's type.
blob.content_type_was_set.set(!content_type.is_empty());
Comment thread
robobun marked this conversation as resolved.
Resolved
blob.content_type.set(content_type);

Check warning on line 2014 in src/runtime/webcore/Blob.rs

View check run for this annotation

Claude / Claude Code Review

Response(typedBlob.slice()).blob().type regresses to text/plain;charset=utf-8

Nit: this flips `content_type_was_set` from `true` to `false` for a typeless slice of a *typed* in-memory parent, which newly trips the pre-existing `Body.rs:2173` heuristic — so `(await new Response(new Blob(["x"], {type: "a/b"}).slice(0, 1)).blob()).type` now returns `"text/plain;charset=utf-8"` where Bun-before-PR and Node both return `""`. The root cause is the `!content_type_was_set && store.is_some()` fallback in `Body.rs` (the #19603 family, explicitly out of scope here), but worth flaggi
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved
Comment thread
robobun marked this conversation as resolved.
Resolved

let ptr = Blob::new(blob);
// SAFETY: `ptr` just came from `heap::alloc` in `Blob::new`. Explicit
Expand Down Expand Up @@ -2101,10 +2086,7 @@
if !is_valid_blob_type(slice) {
break 'inner;
}
content_type = match global_this.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
};
content_type = BlobContentType::from_lowercased(slice);

Check notice on line 2089 in src/runtime/webcore/Blob.rs

View check run for this annotation

Claude / Claude Code Review

Zero-size parent's slice(_, _, contentType) discards the type (pre-existing, same class)

Pre-existing, same class: `get_slice()` early-returns `Blob::init_empty()` when `self.size == 0` (Blob.rs:2030) *before* reading the `contentType` argument, so `new Blob([]).slice(0, 0, "text/plain").type === ""` instead of `"text/plain"` — the File API spec and Node return the caller's type regardless of parent size. Adding `new Blob([]).slice(0, 0, input).type` to this PR's own `test.each` at blob.test.ts:126 would fail. Consider processing the `contentType` arg before the size==0 check, or ro
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
Expand Down Expand Up @@ -2457,12 +2439,8 @@
break 'inner;
}
blob.content_type_was_set.set(true);
blob.content_type.set(
match global_this.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
},
);
blob.content_type
.set(BlobContentType::from_lowercased(slice));
}
}
}
Expand Down Expand Up @@ -5680,12 +5658,8 @@
break 'inner;
}
blob.content_type_was_set.set(true);
blob.content_type.set(
match global_this.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
},
);
blob.content_type
.set(BlobContentType::from_lowercased(slice));
}
}
}
Expand Down Expand Up @@ -5767,12 +5741,8 @@
break 'inner;
}
blob.content_type_was_set.set(true);
blob.content_type.set(
match global_object.bun_vm().as_mut().mime_type(slice) {
Some(mime) => BlobContentType::from(mime),
None => BlobContentType::from_lowercased(slice),
},
);
blob.content_type
.set(BlobContentType::from_lowercased(slice));
}
}
}
Expand Down
14 changes: 3 additions & 11 deletions src/runtime/webcore/S3File.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,12 +75,10 @@ where
)?;

formatter.print_comma::<W, ENABLE_ANSI_COLORS>(writer)?;
if offset > 0 {
writer.write_str("\n")?;
}
}

if offset > 0 {
writer.write_str("\n")?;
let mut formatter = formatter.indented();
formatter.write_indent(writer)?;

Expand Down Expand Up @@ -399,10 +397,7 @@ pub(crate) fn construct_s3_file_with_s3_credentials_and_options(
}
blob.content_type_was_set.set(true);
blob.content_type
.set(match global.bun_vm().as_mut().mime_type(slice) {
Some(mime) => blob::BlobContentType::from(mime),
None => blob::BlobContentType::from_lowercased(slice),
});
.set(blob::BlobContentType::from_lowercased(slice));
}
}
}
Expand Down Expand Up @@ -446,10 +441,7 @@ pub(crate) fn construct_s3_file_with_s3_credentials(
}
blob.content_type_was_set.set(true);
blob.content_type
.set(match global.bun_vm().as_mut().mime_type(slice) {
Some(mime) => blob::BlobContentType::from(mime),
None => blob::BlobContentType::from_lowercased(slice),
});
.set(blob::BlobContentType::from_lowercased(slice));
Comment thread
robobun marked this conversation as resolved.
Resolved
}
}
}
Expand Down
10 changes: 6 additions & 4 deletions src/runtime/webcore/headers_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,23 @@
use crate::webcore::Blob;
use crate::webcore::blob::Any as AnyBlob;

/// `Some(ct)` only when the body has a *user-set* content-type.
/// `Some(ct)` only when the body has a non-empty user-set content-type.
#[inline]
pub(crate) fn any_blob_content_type(b: &AnyBlob) -> Option<&[u8]> {
if b.has_content_type_from_user() {
Some(b.content_type())
let ct = b.content_type();
(!ct.is_empty()).then_some(ct)
} else {
None
}
}

/// `Some(ct)` only when the body has a *user-set* content-type.
/// `Some(ct)` only when the body has a non-empty user-set content-type.
#[inline]
pub(crate) fn blob_content_type(b: &Blob) -> Option<&[u8]> {
if b.has_content_type_from_user() {
Some(b.content_type_slice())
let ct = b.content_type_slice();
(!ct.is_empty()).then_some(ct)

Check warning on line 25 in src/runtime/webcore/headers_ref.rs

View check run for this annotation

Claude / Claude Code Review

Stale doc comment on any_blob_content_type_opt

Nit: the doc comment on `any_blob_content_type_opt` (line 31) still says "*user-set* content-type" while its two siblings above were updated to "non-empty user-set content-type". Since it delegates via `b.and_then(any_blob_content_type)`, its behavior also changed to filter empty — the comment should be updated to match.
Comment thread
robobun marked this conversation as resolved.
Resolved
} else {
None
}
Comment thread
robobun marked this conversation as resolved.
Resolved
Expand Down
10 changes: 3 additions & 7 deletions test/js/bun/http/bun-serve-static.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,11 +208,7 @@ describe("static route Content-Type", () => {
// change the Content-Type the next registration of the same Response produces.
test.each([
["string body", () => new Response("hello"), "text/plain;charset=utf-8"],
[
"typed Blob body",
() => new Response(new Blob(["<h1>hi</h1>"], { type: "text/html" })),
"text/html;charset=utf-8",
],
["typed Blob body", () => new Response(new Blob(["<h1>hi</h1>"], { type: "text/html" })), "text/html"],
["explicit header", () => new Response("hello", { headers: { "Content-Type": "text/foo" } }), "text/foo"],
["Response.json", () => Response.json({ a: 1 }), "application/json;charset=utf-8"],
["Uint8Array body", () => new Response(new Uint8Array([1, 2, 3])), null],
Expand Down Expand Up @@ -252,8 +248,8 @@ describe("static route Content-Type", () => {
untouched: await contentTypeOf(server, "/untouched"),
touched: await contentTypeOf(server, "/touched"),
}).toEqual({
untouched: "text/html;charset=utf-8",
touched: "text/html;charset=utf-8",
untouched: "text/html",
touched: "text/html",
});
});

Expand Down
8 changes: 2 additions & 6 deletions test/js/bun/s3/s3.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -165,13 +165,9 @@ describe.concurrent.skipIf(!r2Credentials.endpoint && !isCI)("Virtual Hosted-Sty
);
}
{
const file = client
.file("filename.txt", {
type: "text/plain",
})
.slice(10);
const file = client.file("filename.txt").slice(10, "text/plain");
expect(Bun.inspect(file)).toBe(
'S3Ref ("bucket/filename.txt") {\n type: "text/plain;charset=utf-8",\n offset: 10,\n endpoint: "bucket.test.r2.cloudflarestorage.com",\n region: "auto",\n accessKeyId: "[REDACTED]",\n secretAccessKey: "[REDACTED]",\n partSize: 5242880,\n queueSize: 5,\n retry: 3\n}',
'S3Ref ("bucket/filename.txt") {\n type: "text/plain",\n offset: 10,\n endpoint: "bucket.test.r2.cloudflarestorage.com",\n region: "auto",\n accessKeyId: "[REDACTED]",\n secretAccessKey: "[REDACTED]",\n partSize: 5242880,\n queueSize: 5,\n retry: 3\n}',
);
}
});
Expand Down
12 changes: 6 additions & 6 deletions test/js/bun/util/inspect.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -619,23 +619,23 @@ describe("console.logging class displays names and extends", async () => {

it("console.log on a Blob shows name", () => {
const blob = new Blob(["foo"], { type: "text/plain" });
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n type: "text/plain;charset=utf-8"\n}');
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n type: "text/plain"\n}');
blob.name = "bar";
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n name: "bar",\n type: "text/plain;charset=utf-8"\n}');
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n name: "bar",\n type: "text/plain"\n}');
blob.name = "foobar";
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n name: "foobar",\n type: "text/plain;charset=utf-8"\n}');
expect(Bun.inspect(blob)).toBe('Blob (3 bytes) {\n name: "foobar",\n type: "text/plain"\n}');

const file = new File(["foo"], "bar.txt", { type: "text/plain" });
expect(Bun.inspect(file)).toBe(
`File (3 bytes) {\n name: "bar.txt",\n type: "text/plain;charset=utf-8",\n lastModified: ${file.lastModified}\n}`,
`File (3 bytes) {\n name: "bar.txt",\n type: "text/plain",\n lastModified: ${file.lastModified}\n}`,
);
file.name = "foobar";
expect(Bun.inspect(file)).toBe(
`File (3 bytes) {\n name: "foobar",\n type: "text/plain;charset=utf-8",\n lastModified: ${file.lastModified}\n}`,
`File (3 bytes) {\n name: "foobar",\n type: "text/plain",\n lastModified: ${file.lastModified}\n}`,
);
file.name = "";
expect(Bun.inspect(file)).toBe(
`File (3 bytes) {\n name: "",\n type: "text/plain;charset=utf-8",\n lastModified: ${file.lastModified}\n}`,
`File (3 bytes) {\n name: "",\n type: "text/plain",\n lastModified: ${file.lastModified}\n}`,
);
});

Expand Down
81 changes: 81 additions & 0 deletions test/js/web/fetch/blob.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,87 @@ test("new Blob", () => {
expect(blob.type).toBe("");
});

describe("Blob type", () => {
// https://w3c.github.io/FileAPI/#dom-blob-type
// An explicit user-supplied `type` must be returned verbatim (lowercased),
// without Bun appending `;charset=utf-8` for recognised MIME types.
test.each([
["text/plain", "text/plain"],
["application/json", "application/json"],
["text/html", "text/html"],
["text/css", "text/css"],
["text/javascript", "text/javascript"],
["Text/PLAIN", "text/plain"],
["text/plain;charset=utf-8", "text/plain;charset=utf-8"],
["application/octet-stream", "application/octet-stream"],
["a/b", "a/b"],
["", ""],
])("new Blob/File/slice type %j -> %j", (input, expected) => {
expect(new Blob([], { type: input }).type).toBe(expected);
expect(new Blob(["x"], { type: input }).type).toBe(expected);
expect(new File([], "f", { type: input }).type).toBe(expected);
expect(new File(["x"], "f", { type: input }).type).toBe(expected);
expect(new Blob(["x"]).slice(0, 1, input).type).toBe(expected);
});

// https://w3c.github.io/FileAPI/#slice-method-algo
// A slice() with no contentType, "", or an invalid contentType has type "";
// it must not inherit the parent's type (regardless of whether the parent's
// type happens to be in Bun's MIME table).
test.each(["text/plain", "application/json", "a/b", "x-weird/y-type"])(
"slice() does not inherit parent type %j",
parentType => {
const parent = new Blob(["x"], { type: parentType });
expect(parent.slice(0, 1).type).toBe("");
expect(parent.slice(0, 1, "").type).toBe("");
expect(parent.slice(0, 1, "x/\u00e9").type).toBe("");
expect(parent.slice(0, 1, "\u1234").type).toBe("");
// parent is not mutated
expect(parent.type).toBe(parentType);
},
);

test("Bun.file() explicit type is not canonicalized", async () => {
expect(Bun.file("x", { type: "text/plain" }).type).toBe("text/plain");
expect(Bun.file("x", { type: "application/json" }).type).toBe("application/json");
// extension-sniffed default is still Bun's canonical form
expect(Bun.file("x.txt").type).toBe("text/plain;charset=utf-8");

// .write({type}) must not canonicalize either
using dir = tempDir("blob-type-write", { "f": "" });
const f = Bun.file(path.join(String(dir), "f"));
await f.write("hello", { type: "text/plain" });
expect(f.type).toBe("text/plain");
});

test("typeless slice body omits the Content-Type header", async () => {
using dir = tempDir("blob-type-slice-ct", { "f.txt": "hello world" });
await using server = Bun.serve({
port: 0,
fetch: req =>
new Response(
JSON.stringify({ ct: req.headers.get("content-type"), hasCt: req.headers.has("content-type") }),
),
});
const post = (body: BodyInit) => fetch(server.url, { method: "POST", body }).then(r => r.json());

// A typeless slice's type is "", so per Fetch "extract a body" the header
// is omitted, never sent with an empty value (this was already latently
// broken for the non-table-MIME case before this change).
expect(await post(Bun.file(path.join(String(dir), "f.txt")).slice(0, 5))).toEqual({ ct: null, hasCt: false });
expect(await post(Bun.file(path.join(String(dir), "f.txt"), { type: "custom/x" }).slice(0, 5))).toEqual({
ct: null,
hasCt: false,
});
expect(await post(new Blob(["hello"], { type: "text/plain" }).slice(0, 3))).toEqual({ ct: null, hasCt: false });
// control: the unsliced file still carries its extension-sniffed type
expect(await post(Bun.file(path.join(String(dir), "f.txt")))).toEqual({
ct: "text/plain;charset=utf-8",
hasCt: true,
});
});
});

test("new Blob stringifies non-Blob object parts in order", async () => {
const url = new URL("https://example.com/path");
expect(await new Blob([url]).text()).toBe("https://example.com/path");
Expand Down
2 changes: 1 addition & 1 deletion test/js/web/html/FormData-multipart-serialization.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ describe("multipart serialization (new Response(formData))", () => {
`Content-Type: application/octet-stream\r\n\r\nnamed-bytes\r\n`,
`--${boundary}\r\n`,
`Content-Disposition: form-data; name="typed-file"; filename="weird%22file%0D%0Aname.html"\r\n`,
`Content-Type: text/html;charset=utf-8\r\n\r\n<p>hi</p>\r\n`,
`Content-Type: text/html\r\n\r\n<p>hi</p>\r\n`,
Comment thread
robobun marked this conversation as resolved.
Resolved
`--${boundary}--\r\n`,
].join(""),
);
Expand Down
Loading
Loading