Lightpanda: the headless browser designed for AI and automation
webapi: improve various WPT fetch apis
Karl Seguinb633dc4b169f
diff --git a/src/browser/Frame.zig b/src/browser/Frame.zigindex c168ca8ad..cde586b4d 100644--- a/src/browser/Frame.zig+++ b/src/browser/Frame.zig@@ -1643,7 +1643,9 @@ fn frameDataCallback(transfer: *HttpClient.Transfer, data: []const u8) !void {// to sniff the content typevar mime: Mime = blk: {if (transfer.contentType()) |ct| {- break :blk try Mime.parse(ct);+ // A Content-Type we can't parse must not fail the navigation;+ // browsers render the page anyway, so fall back to sniffing.+ break :blk Mime.parseLenient(ct) catch Mime.sniff(data);}break :blk Mime.sniff(data);} orelse .unknown;diff --git a/src/browser/Mime.zig b/src/browser/Mime.zigindex 1e64fa338..bab257c44 100644--- a/src/browser/Mime.zig+++ b/src/browser/Mime.zig@@ -204,6 +204,30 @@ pub fn parse(input: []const u8) !Mime {return mime;}+/// Try to parse a header which may contain several comma-joined values+/// (happens when a server and proxy both set the Content-Type).+pub fn parseLenient(input: []const u8) !Mime {+ var in_quotes = false;+ var last_comma: ?usize = null;+ var i: usize = 0;+ while (i < input.len) : (i += 1) {+ switch (input[i]) {+ '"' => in_quotes = !in_quotes,+ '\\' => if (in_quotes) {+ i += 1;+ },+ ',' => if (in_quotes == false) {+ last_comma = i;+ },+ else => {},+ }+ }++ // last value wins+ const comma = last_comma orelse return parse(input);+ return parse(input[comma + 1 ..]) catch parse(input);+}+/// Prescan the first 1024 bytes of an HTML document for a charset declaration./// Looks for `<meta charset="X">` and `<meta http-equiv="Content-Type" content="...;charset=X">`./// Returns the charset value or null if none found.@@ -851,6 +875,26 @@ test "Mime: invalid" {}}+test "Mime: parseLenient takes the last comma-joined value" {+ {+ const m = try parseLenient("text/plain; charset=gbk, text/html; charset=windows-1254");+ try testing.expectEqual(.text_html, std.meta.activeTag(m.content_type));+ try testing.expectString("windows-1254", m.charset[0..m.charset_len]);+ }+ {+ const m = try parseLenient("text/html, text/html");+ try testing.expectEqual(.text_html, std.meta.activeTag(m.content_type));+ }+ {+ // A comma inside a quoted parameter value is not a separator.+ const m = try parseLenient("text/html;x=\",text/plain\";charset=gbk");+ try testing.expectEqual(.text_html, std.meta.activeTag(m.content_type));+ try testing.expectString("gbk", m.charset[0..m.charset_len]);+ }+ try testing.expectError(error.Invalid, parseLenient("text, html"));+ try testing.expectError(error.Invalid, parseLenient("garbage"));+}+test "Mime: malformed parameters are ignored" {// These should all parse successfully as text/html with malformed params ignoreddiff --git a/src/browser/js/Context.zig b/src/browser/js/Context.zigindex 340537b54..a99a5e69d 100644--- a/src/browser/js/Context.zig+++ b/src/browser/js/Context.zig@@ -1292,3 +1292,9 @@ const UnknownPropertyStat = struct {count: usize,first_stack: []const u8,};++// see Local.typeError+pub fn typeError(self: *const Context, message: []const u8) error{TypeError} {+ self.env.error_message = message;+ return error.TypeError;+}diff --git a/src/browser/js/Local.zig b/src/browser/js/Local.zigindex db78a211c..e17aed979 100644--- a/src/browser/js/Local.zig+++ b/src/browser/js/Local.zig@@ -782,6 +782,10 @@ fn jsValueToStruct(self: *const Local, comptime T: type, js_val: js.Value) !?T {const arr = (try jsValueToTypedArray(ValueType, js_val)) orelse return null;return .{ .values = arr };},+ js.BufferSource => {+ const bytes = (try jsValueToArrayBufferSlice(u8, true, js_val)) orelse return null;+ return .{ .bytes = bytes };+ },js.Value => js_val,js.Value.Global => return try js_val.persist(),js.Object => {@@ -891,7 +895,13 @@ pub fn assertDictionaryFieldOrder(comptime T: type) void {}fn jsValueToTypedArray(comptime T: type, js_val: js.Value) !?[]T {- var force_u8 = false;+ return jsValueToArrayBufferSlice(T, false, js_val);+}++// With `any_view`, every ArrayBufferView is accepted as a byte slice regardless+// of its element type+fn jsValueToArrayBufferSlice(comptime T: type, any_view: bool, js_val: js.Value) !?[]T {+ var force_u8 = any_view;var array_buffer: ?*const v8.ArrayBuffer = null;var byte_len: usize = undefined;var byte_offset: usize = undefined;@@ -1517,8 +1527,7 @@ pub fn stackTrace(self: *const Local) !?[]const u8 {// When caller catches the error.TypeError, it'll look into env.error_message// for the message.pub fn typeError(self: *const Local, message: []const u8) error{TypeError} {- self.ctx.env.error_message = message;- return error.TypeError;+ return self.ctx.typeError(message);}// == Promise Helpers ==diff --git a/src/browser/js/js.zig b/src/browser/js/js.zigindex b6d5c2983..97163beae 100644--- a/src/browser/js/js.zig+++ b/src/browser/js/js.zig@@ -172,6 +172,11 @@ pub const ArrayBuffer = struct {}};+// An ArrayBuffer or any typed array kind or a, exposed as its raw bytes.+pub const BufferSource = struct {+ bytes: []const u8,+};+pub const ArrayType = enum(u8) {int8,uint8,diff --git a/src/browser/tests/net/headers.html b/src/browser/tests/net/headers.htmlindex e51f061e9..91cf341ec 100644--- a/src/browser/tests/net/headers.html+++ b/src/browser/tests/net/headers.html@@ -49,12 +49,10 @@headers.append('ACCEPT', 'text/html');headers.append('accept', 'text/plain');- // Verify all values are present using iteration+ // Iteration combines a name's values into one entry.const values = Array.from(headers.values());- testing.expectEqual(3, values.length);- testing.expectEqual('application/json', values[0]);- testing.expectEqual('text/html', values[1]);- testing.expectEqual('text/plain', values[2]);+ testing.expectEqual(1, values.length);+ testing.expectEqual('application/json, text/html, text/plain', values[0]);}{@@ -132,11 +130,11 @@testing.expectEqual("Bearer abc", headers.get("Authorization"));testing.expectEqual("value123", headers.get("X-CUSTOM-HEADER"));- // Verify keys are normalized+ // Verify keys are normalized (and iterated in sorted order)const keys = Array.from(headers.keys());testing.expectEqual(3, keys.length);- testing.expectEqual("content-type", keys[0]);- testing.expectEqual("authorization", keys[1]);+ testing.expectEqual("authorization", keys[0]);+ testing.expectEqual("content-type", keys[1]);testing.expectEqual("x-custom-header", keys[2]);}@@ -148,14 +146,12 @@["Content-Type", "text/plain"]]);+ // Iteration combines a name's values; get() sees the same thing.const entries = Array.from(headers.entries());- testing.expectEqual(3, entries.length);-- // All Accept headers should be present- const acceptValues = entries.filter(e => e[0] === 'accept').map(e => e[1]);- testing.expectEqual(2, acceptValues.length);- testing.expectEqual("application/json", acceptValues[0]);- testing.expectEqual("text/html", acceptValues[1]);+ testing.expectEqual(2, entries.length);+ testing.expectEqual("accept", entries[0][0]);+ testing.expectEqual("application/json, text/html", entries[0][1]);+ testing.expectEqual("application/json, text/html", headers.get("accept"));}</script>@@ -230,8 +226,8 @@const keys = Array.from(copy.keys());testing.expectEqual(2, keys.length);- testing.expectEqual("content-type", keys[0]);- testing.expectEqual("authorization", keys[1]);+ testing.expectEqual("authorization", keys[0]);+ testing.expectEqual("content-type", keys[1]);}</script>@@ -243,31 +239,68 @@headers.set('Authorization', 'Bearer token123');headers.set('X-Custom', 'test-value');- // Test keys()+ // Iteration is in sorted name order, not insertion order.const keys = Array.from(headers.keys());testing.expectEqual(3, keys.length);- testing.expectEqual('content-type', keys[0]);- testing.expectEqual('authorization', keys[1]);+ testing.expectEqual('authorization', keys[0]);+ testing.expectEqual('content-type', keys[1]);testing.expectEqual('x-custom', keys[2]);// Test values()const values = Array.from(headers.values());testing.expectEqual(3, values.length);- testing.expectEqual('application/json', values[0]);- testing.expectEqual('Bearer token123', values[1]);+ testing.expectEqual('Bearer token123', values[0]);+ testing.expectEqual('application/json', values[1]);testing.expectEqual('test-value', values[2]);// Test entries()const entries = Array.from(headers.entries());testing.expectEqual(3, entries.length);- testing.expectEqual('content-type', entries[0][0]);- testing.expectEqual('application/json', entries[0][1]);- testing.expectEqual('authorization', entries[1][0]);- testing.expectEqual('Bearer token123', entries[1][1]);+ testing.expectEqual('authorization', entries[0][0]);+ testing.expectEqual('Bearer token123', entries[0][1]);+ testing.expectEqual('content-type', entries[1][0]);+ testing.expectEqual('application/json', entries[1][1]);testing.expectEqual('x-custom', entries[2][0]);testing.expectEqual('test-value', entries[2][1]);}+// Headers is iterable: for..of, spread and Object.fromEntries all go+// through Symbol.iterator, not entries().+{+ const headers = new Headers({ 'X-B': '2', 'X-A': '1' });+ testing.expectEqual('function', typeof headers[Symbol.iterator]);++ const spread = [...headers];+ testing.expectEqual(2, spread.length);+ testing.expectEqual('x-a', spread[0][0]);+ testing.expectEqual('1', spread[0][1]);++ const collected = [];+ for (const [name, value] of headers) {+ collected.push(name + '=' + value);+ }+ testing.expectEqual('x-a=1,x-b=2', collected.join(','));++ // set-cookie is never combined and keeps its order; a name's other values are.+ headers.append('Set-Cookie', 'a=1');+ headers.append('set-cookie', 'b=2');+ headers.append('x-a', '3');+ testing.expectEqual('set-cookie=a=1,set-cookie=b=2,x-a=1, 3,x-b=2', [...headers].map(e => e.join('=')).join(','));++ // append/set validate names and normalize values like the constructor.+ headers.set('X-Trim', ' v ');+ testing.expectEqual('v', headers.get('x-trim'));+ let threw = 0;+ try { headers.append('Bad Name', 'x'); } catch (e) { threw += e instanceof TypeError; }+ try { headers.set('X-Ok', 'a\nb'); } catch (e) { threw += e instanceof TypeError; }+ try { headers.get(''); } catch (e) { threw += e instanceof TypeError; }+ testing.expectEqual(3, threw);++ const obj = Object.fromEntries(headers);+ testing.expectEqual('1, 3', obj['x-a']);+ testing.expectEqual('2', new Map(headers).get('x-b'));+}+// Test forEach(){const headers = new Headers();@@ -281,10 +314,10 @@});testing.expectEqual(2, collected.length);- testing.expectEqual('content-type', collected[0][0]);- testing.expectEqual('application/json', collected[0][1]);- testing.expectEqual('authorization', collected[1][0]);- testing.expectEqual('Bearer token123', collected[1][1]);+ testing.expectEqual('authorization', collected[0][0]);+ testing.expectEqual('Bearer token123', collected[0][1]);+ testing.expectEqual('content-type', collected[1][0]);+ testing.expectEqual('application/json', collected[1][1]);}// Test forEach with thisArg@@ -314,10 +347,9 @@}});- testing.expectEqual(3, values.length);- testing.expectEqual('application/json', values[0]);- testing.expectEqual('text/html', values[1]);- testing.expectEqual('text/plain', values[2]);+ // forEach sees the combined value, like iteration.+ testing.expectEqual(1, values.length);+ testing.expectEqual('application/json, text/html, text/plain', values[0]);}</script>diff --git a/src/browser/tests/net/request.html b/src/browser/tests/net/request.htmlindex 0f78a259e..974180f6a 100644--- a/src/browser/tests/net/request.html+++ b/src/browser/tests/net/request.html@@ -259,6 +259,26 @@}</script>+<script id=buffer_source_bodies type=module>+ const state = await testing.async();++ // Every ArrayBufferView is a BufferSource, viewed as its raw bytes.+ const int8 = await new Request('https://example.com', { method: 'POST', body: new Int8Array([-1, 2]) }).bytes();+ const float32 = await new Request('https://example.com', { method: 'POST', body: new Float32Array([1]) }).bytes();+ const buf = new ArrayBuffer(4);+ new DataView(buf).setUint32(0, 0x41424344);+ const view = await new Request('https://example.com', { method: 'POST', body: new DataView(buf, 1, 2) }).text();++ state.resolve();+ await state.done(() => {+ testing.expectEqual(2, int8.length);+ testing.expectEqual(255, int8[0]);+ testing.expectEqual(2, int8[1]);+ testing.expectEqual(4, float32.length);+ testing.expectEqual('BC', view);+ });+</script>+<script id=form_data type=module>const state = await testing.async();diff --git a/src/browser/tests/net/response.html b/src/browser/tests/net/response.htmlindex fc01dccd1..63f3f9353 100644--- a/src/browser/tests/net/response.html+++ b/src/browser/tests/net/response.html@@ -283,6 +283,42 @@});</script>+<script id=stream_consumers type=module>+ const state = await testing.async();++ const streamOf = (...parts) => new ReadableStream({+ start(controller) {+ for (const part of parts) controller.enqueue(part);+ controller.close();+ }+ });++ const text = await new Response(streamOf(new Uint8Array([104, 105]), new Uint8Array([33]))).text();+ const json = await new Response(streamOf(new TextEncoder().encode('{"a":[1,2]}'))).json();+ const bytes = await new Response(streamOf(new Uint8Array([1, 2]))).bytes();+ const blob = await new Response(streamOf(new Uint8Array([120])), { headers: { 'content-type': 'text/x-y' } }).blob();+ const blobText = await blob.text();+ const fd = await new Response(streamOf(new TextEncoder().encode('a=1&b=2')), { headers: { 'content-type': 'application/x-www-form-urlencoded' } }).formData();++ let badJson = null;+ try { await new Response(streamOf(new Uint8Array([123]))).json(); } catch (e) { badJson = e; }+ let noFormData = null;+ try { await new Response(streamOf(new Uint8Array([120]))).formData(); } catch (e) { noFormData = e; }++ state.resolve();+ await state.done(() => {+ testing.expectEqual('hi!', text);+ testing.expectEqual(2, json.a[1]);+ testing.expectEqual(true, bytes instanceof Uint8Array);+ testing.expectEqual(2, bytes[1]);+ testing.expectEqual('text/x-y', blob.type);+ testing.expectEqual('x', blobText);+ testing.expectEqual('2', fd.get('b'));+ testing.expectEqual(true, badJson instanceof SyntaxError);+ testing.expectEqual(true, noFormData instanceof TypeError);+ });+</script>+<script id=body_used type=module>const state = await testing.async();diff --git a/src/browser/tests/worker/api-worker.js b/src/browser/tests/worker/api-worker.jsindex 803b8ace1..3561c604d 100644--- a/src/browser/tests/worker/api-worker.js+++ b/src/browser/tests/worker/api-worker.js@@ -26,8 +26,10 @@statusText: 'Created',headers: { 'content-type': 'text/plain' },});+ // Clone before consuming: a disturbed body can't be cloned.+ const response_clone = response.clone();const response_body_text = await response.text();- const response_clone_text = await response.clone().text();+ const response_clone_text = await response_clone.text();// AbortController + AbortSignal dispatch (exercises the inline-else dispatch path)const controller = new AbortController();diff --git a/src/browser/webapi/net/Headers.zig b/src/browser/webapi/net/Headers.zigindex d136cf9d3..6d52e8904 100644--- a/src/browser/webapi/net/Headers.zig+++ b/src/browser/webapi/net/Headers.zig@@ -8,9 +8,19 @@ const KeyValueList = @import("../KeyValueList.zig");const log = lp.log;const Execution = js.Execution;+const Allocator = std.mem.Allocator;const Headers = @This();+pub fn registerTypes() []const type {+ return &.{+ Headers,+ KeyIterator,+ ValueIterator,+ EntryIterator,+ };+}+_list: KeyValueList,_guard: Guard = .none,@@ -85,16 +95,17 @@ fn checkGuard(self: *const Headers, name: []const u8) !Mutation {}pub fn append(self: *Headers, name: []const u8, value: []const u8, exec: *const Execution) !void {- const normalized_name = normalizeHeaderName(name, exec.buf);+ const normalized_name = try validateAndNormalizeName(name, exec);+ const normalized_value = try normalizeValue(value, exec);const mutation = try self.checkGuard(normalized_name);if (mutation == .ignore) {return;}- try self._list.append(exec.arena, normalized_name, value);+ try self._list.append(exec.arena, normalized_name, normalized_value);}pub fn delete(self: *Headers, name: []const u8, exec: *const Execution) !void {- const normalized_name = normalizeHeaderName(name, exec.buf);+ const normalized_name = try validateAndNormalizeName(name, exec);const mutation = try self.checkGuard(normalized_name);if (mutation == .ignore) {return;@@ -103,7 +114,7 @@ pub fn delete(self: *Headers, name: []const u8, exec: *const Execution) !void {}pub fn get(self: *const Headers, name: []const u8, exec: *const Execution) !?[]const u8 {- const normalized_name = normalizeHeaderName(name, exec.buf);+ const normalized_name = try validateAndNormalizeName(name, exec);const all_values = try self._list.getAll(exec.local_arena, normalized_name);if (all_values.len == 0) {@@ -119,13 +130,14 @@ pub fn getSetCookie(self: *const Headers, exec: *const Execution) ![]const []conreturn self._list.getAll(exec.local_arena, "set-cookie");}-pub fn has(self: *const Headers, name: []const u8, exec: *const Execution) bool {- const normalized_name = normalizeHeaderName(name, exec.buf);+pub fn has(self: *const Headers, name: []const u8, exec: *const Execution) !bool {+ const normalized_name = try validateAndNormalizeName(name, exec);return self._list.has(normalized_name, null);}-pub fn set(self: *Headers, name: []const u8, value: []const u8, exec: *const Execution) !void {- const normalized_name = normalizeHeaderName(name, exec.buf);+pub fn set(self: *Headers, name: []const u8, value_: []const u8, exec: *const Execution) !void {+ const normalized_name = try validateAndNormalizeName(name, exec);+ const value = try normalizeValue(value_, exec);const mutation = try self.checkGuard(normalized_name);if (mutation == .ignore) {return;@@ -133,29 +145,87 @@ pub fn set(self: *Headers, name: []const u8, value: []const u8, exec: *const Exetry self._list.set(exec.arena, normalized_name, value);}-pub fn keys(self: *Headers, exec: *const js.Execution) !*KeyValueList.KeyIterator {- return KeyValueList.KeyIterator.init(.{ .list = self, .kv = &self._list }, exec);+pub fn keys(self: *Headers, exec: *const js.Execution) !*KeyIterator {+ return KeyIterator.init(.{ .headers = self }, exec);}-pub fn values(self: *Headers, exec: *const js.Execution) !*KeyValueList.ValueIterator {- return KeyValueList.ValueIterator.init(.{ .list = self, .kv = &self._list }, exec);+pub fn values(self: *Headers, exec: *const js.Execution) !*ValueIterator {+ return ValueIterator.init(.{ .headers = self }, exec);}-pub fn entries(self: *Headers, exec: *const js.Execution) !*KeyValueList.EntryIterator {- return KeyValueList.EntryIterator.init(.{ .list = self, .kv = &self._list }, exec);+pub fn entries(self: *Headers, exec: *const js.Execution) !*EntryIterator {+ return EntryIterator.init(.{ .headers = self }, exec);}-pub fn forEach(self: *Headers, cb_: js.Function, js_this_: ?js.Object) !void {+pub fn forEach(self: *Headers, cb_: js.Function, js_this_: ?js.Object, exec: *const Execution) !void {const cb = if (js_this_) |js_this| try cb_.withThis(js_this) else cb_;- for (self._list._entries.items) |entry| {+ var it = Iterator{ .headers = self };+ while (try it.next(exec)) |entry| {var caught: js.TryCatch.Caught = .{};- cb.tryCall(void, .{ entry.value.str(), entry.name.str(), self }, &caught) catch {+ cb.tryCall(void, .{ entry.@"1", entry.@"0", self }, &caught) catch {log.debug(.js, "forEach callback", .{ .caught = caught, .source = "headers" });};}}+// This is pretty brutal, but we need to sortAndCombine on each iteration in order+// to pick up any mutations. I'd be tempted to add a _generation: u32 to avoid+// needlessly doing this but (a) headers tend to be small and (b) not iterated+// that much..PLUS, we'd have to persist the view, and what memory would own that?+pub const Iterator = struct {+ index: u32 = 0,+ headers: *Headers,++ pub const Entry = struct { []const u8, []const u8 };++ pub fn next(self: *Iterator, exec: *const Execution) !?Iterator.Entry {+ const view = try self.headers.sortAndCombine(exec.local_arena);+ const index = self.index;+ if (index >= view.len) {+ return null;+ }+ self.index = index + 1;+ return view[index];+ }+};++fn sortAndCombine(self: *const Headers, arena: Allocator) ![]Iterator.Entry {+ var out: std.ArrayList(Iterator.Entry) = try .initCapacity(arena, self._list._entries.items.len);+ for (self._list._entries.items) |*entry| {+ if (entry.name.eql(comptime .wrap("set-cookie")) == false) {+ // everything except set-cookie is concatenated together+ if (findEntry(out.items, entry.name)) |existing| {+ existing.@"1" = try std.mem.concat(arena, u8, &.{ existing.@"1", ", ", entry.value.str() });+ continue;+ }+ }+ out.appendAssumeCapacity(.{ entry.name.str(), entry.value.str() });+ }++ std.sort.insertion(Iterator.Entry, out.items, {}, struct {+ fn compare(_: void, a: Iterator.Entry, b: Iterator.Entry) bool {+ return std.mem.order(u8, a.@"0", b.@"0") == .lt;+ }+ }.compare);++ return out.items;+}++fn findEntry(view: []Iterator.Entry, name: lp.String) ?*Iterator.Entry {+ for (view) |*entry| {+ if (name.eqlSlice(entry.@"0")) {+ return entry;+ }+ }+ return null;+}++const GenericIterator = @import("../collections/iterator.zig").Entry;+pub const KeyIterator = GenericIterator(Iterator, "0");+pub const ValueIterator = GenericIterator(Iterator, "1");+pub const EntryIterator = GenericIterator(Iterator, null);+const HttpClient = @import("../../../network/HttpClient.zig");pub fn populateRequestHeaders(self: *Headers, transfer: *HttpClient.Transfer) !void {for (self._list._entries.items) |entry| {@@ -163,6 +233,13 @@ pub fn populateRequestHeaders(self: *Headers, transfer: *HttpClient.Transfer) !v}}+fn validateAndNormalizeName(name: []const u8, exec: *const Execution) ![]const u8 {+ if (Mime.isHttpToken(name) == false) {+ return exec.js.typeError("Invalid header name");+ }+ return normalizeHeaderName(name, exec.buf);+}+fn normalizeHeaderName(name: []const u8, buf: []u8) []const u8 {if (name.len > buf.len) {return name;@@ -170,6 +247,14 @@ fn normalizeHeaderName(name: []const u8, buf: []u8) []const u8 {return std.ascii.lowerString(buf, name);}+fn normalizeValue(value: []const u8, exec: *const Execution) ![]const u8 {+ const trimmed = std.mem.trim(u8, value, &Mime.HTTP_WHITESPACE);+ if (Mime.isHttpHeaderValue(trimmed) == false) {+ return exec.js.typeError("Invalid header value");+ }+ return trimmed;+}+/// Validate names and normalize/validate values for a script-provided header/// init, trimming values in place. The trim is allocation-free (see/// `String.trim`), so an untrimmed value keeps its original storage.@@ -207,6 +292,7 @@ pub const JsApi = struct {pub const keys = bridge.function(Headers.keys, .{});pub const values = bridge.function(Headers.values, .{});pub const entries = bridge.function(Headers.entries, .{});+ pub const symbol_iterator = bridge.iterator(Headers.entries, .{});pub const forEach = bridge.function(Headers.forEach, .{});};diff --git a/src/browser/webapi/net/Request.zig b/src/browser/webapi/net/Request.zigindex bd674546b..6447add9e 100644--- a/src/browser/webapi/net/Request.zig+++ b/src/browser/webapi/net/Request.zig@@ -26,7 +26,6 @@ const URL = @import("../URL.zig");const Page = @import("../../Page.zig");const Blob = @import("../Blob.zig");const AbortSignal = @import("../AbortSignal.zig");-const ContentTypeIterator = @import("../../Mime.zig").ContentTypeIterator;const Headers = @import("Headers.zig");const FormData = @import("FormData.zig");@@ -138,7 +137,7 @@ pub fn init(input: Input, opts_: ?InitOpts, exec: *const Execution) !*Request {// the user has not already set one via the headers init dict.if (extracted.content_type) |ct| {const hs = headers orelse try Headers.init(null, exec);- if (!hs.has("content-type", exec)) {+ if (try hs.has("content-type", exec) == false) {try hs.append("content-type", ct, exec);}headers = hs;@@ -313,41 +312,14 @@ pub fn formData(self: *Request, exec: *const Execution) !js.Promise {const local = exec.js.local.?;try self.consume(local);- // Per Fetch, a null body acts as an empty byte sequence.- const body = self._body orelse "";-const headers = try self.getHeaders(exec);- const content_type = try headers.get("content-type", exec) orelse {- return local.typeError("Failed to parse body as FormData");+ const content_type = try headers.get("content-type", exec);+ // Per Fetch, a null body acts as an empty byte sequence.+ const form_data = body_init.parseFormData(self._body orelse "", content_type, exec) catch |err| switch (err) {+ error.OutOfMemory => return err,+ error.TypeError => return local.typeError("Failed to parse body as FormData"),};- var it = ContentTypeIterator.init(content_type);- const essence = it.essence;-- // [RFC7578]- // Parse bytes, using the value of the `boundary` parameter from mimeType,- // per the rules set forth in Returning Values from Forms: multipart/form-data.- if (std.ascii.eqlIgnoreCase(essence, "multipart/form-data")) {- const boundary = it.findBoundary();- if (boundary.len == 0) {- return local.typeError("Failed to parse body as FormData");- }-- const form_data = FormData.initFromMultipart(body, boundary, exec) catch |err| switch (err) {- error.OutOfMemory => return err,- else => return local.typeError("Failed to parse body as FormData"),- };- return local.resolvePromise(form_data);- }-- if (std.ascii.eqlIgnoreCase(essence, "application/x-www-form-urlencoded")) {- const form_data = FormData.initFromUrlEncoded(body, exec) catch |err| switch (err) {- error.OutOfMemory => return err,- else => return local.typeError("Failed to parse body as FormData"),- };- return local.resolvePromise(form_data);- }-- return local.typeError("Failed to parse body as FormData");+ return local.resolvePromise(form_data);}pub fn clone(self: *const Request, exec: *const Execution) !*Request {diff --git a/src/browser/webapi/net/Response.zig b/src/browser/webapi/net/Response.zigindex 50d3f4a09..b4d76644b 100644--- a/src/browser/webapi/net/Response.zig+++ b/src/browser/webapi/net/Response.zig@@ -31,8 +31,6 @@ const FormData = @import("FormData.zig");const Headers = @import("Headers.zig");const body_init = @import("body_init.zig");-const ContentTypeIterator = @import("../../Mime.zig").ContentTypeIterator;-const Execution = js.Execution;const Allocator = std.mem.Allocator;@@ -58,6 +56,7 @@ _url: [:0]const u8,_is_redirected: bool,_http_transfer: ?*Transfer = null,_body_used: bool = false,+_body_stream: ?*ReadableStream = null,const Body = union(enum) {empty,@@ -117,7 +116,7 @@ fn initWithArena(arena: *lp.Arena, body_: ?BodyInit, opts_: ?InitOpts, exec: *coconst headers = try Headers.initGuarded(opts.headers, .response, exec);if (content_type) |ct| {- if (!headers.has("content-type", exec)) {+ if (try headers.has("content-type", exec) == false) {try headers.append("content-type", ct, exec);}}@@ -207,7 +206,7 @@ pub fn createJson(data: js.Value, opts_: ?InitOpts, exec: *const Execution) !*Reconst status_text = if (opts.statusText) |st| try arena.dupe(u8, st) else "";const headers = try Headers.initGuarded(opts.headers, .response, exec);- if (!headers.has("content-type", exec)) {+ if (try headers.has("content-type", exec) == false) {try headers.append("content-type", "application/json", exec);}@@ -271,16 +270,33 @@ pub fn getBody(self: *Response, exec: *const Execution) !?*ReadableStream {.empty => null,.stream => |stream| stream,.bytes => |body| {- if (body.len == 0) {- const stream = try ReadableStream.init(null, null, exec);- try stream._controller.close();+ if (self._body_stream) |stream| {return stream;}- return ReadableStream.initWithData(body, exec);+ const stream = blk: {+ if (body.len == 0) {+ const stream = try ReadableStream.init(null, null, exec);+ try stream._controller.close();+ break :blk stream;+ }+ break :blk try ReadableStream.initWithData(body, exec);+ };+ self._body_stream = stream;+ if (self._body_used) {+ try lockStream(stream, exec);+ }+ return stream;},};}+// A consumed body's stream stays locked and disturbed (Fetch §6.4 never+// releases the reader it read with).+fn lockStream(stream: *ReadableStream, exec: *const Execution) !void {+ _ = try stream.getReader(exec);+ stream._disturbed = true;+}+pub fn isOK(self: *const Response) bool {return self._status >= 200 and self._status <= 299;}@@ -288,72 +304,124 @@ pub fn isOK(self: *const Response) bool {pub fn getBodyUsed(self: *const Response) bool {return switch (self._body) {.empty => false,- else => self._body_used,+ .stream => |stream| stream._disturbed,+ .bytes => self._body_used,};}-// Marks a present body consumed; a TypeError if it already was.-fn consume(self: *Response, local: *const js.Local) !void {- switch (self._body) {+// A TypeError if the body is disturbed or its stream is locked (Fetch §6.4).+fn checkUnusable(self: *const Response, local: *const js.Local) !void {+ const stream = switch (self._body) {.empty => return,- else => {},- }- if (self._body_used) {- return local.typeError("Body has already been read");+ .stream => |stream| stream,+ .bytes => self._body_stream orelse {+ if (self._body_used) {+ return local.typeError("Body has already been read");+ }+ return;+ },+ };+ if (stream._disturbed or stream.getLocked()) {+ return local.typeError("Body is disturbed or locked");}- self._body_used = true;}-pub fn getText(self: *Response, exec: *const Execution) !js.Promise {+// Marks a present body consumed.+fn consume(self: *Response, exec: *const Execution) !void {const local = exec.js.local.?;- try self.consume(local);+ try self.checkUnusable(local);+ self._body_used = true;+ if (self._body == .bytes) {+ if (self._body_stream) |stream| {+ try lockStream(stream, exec);+ }+ }+}- const body = switch (self._body) {- .bytes => |b| body_init.stripUtf8Bom(b),- .empty => "",- .stream => return local.typeError("Cannot read text from stream body"),- };- return local.resolvePromise(body);+pub fn getText(self: *Response, exec: *const Execution) !js.Promise {+ return self.consumeAs(.text, exec);}pub fn getJson(self: *Response, exec: *const Execution) !js.Promise {- const local = exec.js.local.?;- try self.consume(local);-- const body = switch (self._body) {- .bytes => |b| body_init.stripUtf8Bom(b),- .empty => "",- .stream => return local.typeError("Cannot read JSON from stream body"),- };- const value = local.parseJSON(body) catch {- return local.rejectPromise(.{ .syntax_error = "failed to parse" });- };- return local.resolvePromise(try value.persist());+ return self.consumeAs(.json, exec);}pub fn arrayBuffer(self: *Response, exec: *const Execution) !js.Promise {+ return self.consumeAs(.array_buffer, exec);+}++pub fn blob(self: *Response, exec: *const Execution) !js.Promise {+ return self.consumeAs(.blob, exec);+}++pub fn bytes(self: *Response, exec: *const Execution) !js.Promise {+ return self.consumeAs(.bytes, exec);+}++pub fn formData(self: *Response, exec: *const Execution) !js.Promise {+ return self.consumeAs(.form_data, exec);+}++const Package = enum { array_buffer, bytes, text, json, blob, form_data };++// a byte body is packaged right away, a stream body once it has been drained.+fn consumeAs(self: *Response, kind: Package, exec: *const Execution) !js.Promise {const local = exec.js.local.?;- try self.consume(local);+ try self.consume(exec);- return switch (self._body) {- .bytes => |body| local.resolvePromise(js.ArrayBuffer{ .values = body }),- .empty => local.resolvePromise(js.ArrayBuffer{ .values = "" }),- .stream => |stream| StreamConsumer.start(stream, exec),+ const content_type = try self._headers.get("content-type", exec);+ switch (self._body) {+ .stream => |stream| return StreamConsumer.start(stream, kind, content_type, exec),+ .bytes, .empty => {},+ }++ var resolver = local.createPromiseResolver();+ const body = switch (self._body) {+ .bytes => |b| b,+ else => "",};+ try package(kind, body, content_type, resolver, exec);+ return resolver.promise();+}++// settles `resolver` with `body` as `kind`.+fn package(kind: Package, body: []const u8, content_type: ?[]const u8, resolver: js.PromiseResolver, exec: *const Execution) !void {+ switch (kind) {+ .array_buffer => resolver.resolve("arrayBuffer", js.ArrayBuffer{ .values = body }),+ .bytes => resolver.resolve("bytes", js.TypedArray(u8){ .values = body }),+ .text => resolver.resolve("text", body_init.stripUtf8Bom(body)),+ .json => {+ const local = exec.js.local.?;+ const value = local.parseJSON(body_init.stripUtf8Bom(body)) catch {+ return resolver.rejectError("json", .{ .syntax_error = "failed to parse" });+ };+ resolver.resolve("json", value);+ },+ .blob => resolver.resolve("blob", try Blob.initFromBytes(body, content_type orelse "", exec)),+ .form_data => {+ const form_data = body_init.parseFormData(body, content_type, exec) catch |err| switch (err) {+ error.OutOfMemory => return err,+ error.TypeError => return resolver.rejectError("formData", .{ .type_error = "Failed to parse body as FormData" }),+ };+ resolver.resolve("formData", form_data);+ },+ }}-/// Async consumer for reading all data from a ReadableStream+// Drains a stream body chunk by chunk, then packages the concatenation.const StreamConsumer = struct {const ReadableStreamDefaultReader = @import("../streams/ReadableStreamDefaultReader.zig");execution: *const Execution,+ kind: Package,+ content_type: ?[]const u8,total_len: usize,arena: Allocator,reader: *ReadableStreamDefaultReader,chunks: std.ArrayList([]const u8),resolver: js.PromiseResolver.Global,- fn start(stream: *ReadableStream, exec: *const Execution) !js.Promise {+ fn start(stream: *ReadableStream, kind: Package, content_type: ?[]const u8, exec: *const Execution) !js.Promise {const local = exec.js.local.?;var resolver = local.createPromiseResolver();const promise = resolver.promise();@@ -363,6 +431,8 @@ const StreamConsumer = struct {const state = try exec.arena.create(StreamConsumer);state.* = .{.execution = exec,+ .kind = kind,+ .content_type = if (content_type) |ct| try exec.arena.dupe(u8, ct) else null,.reader = reader,.chunks = .empty,.total_len = 0,@@ -386,52 +456,35 @@ const StreamConsumer = struct {};}- const ReadData = struct {- done: bool,- value: js.Value,- };-- fn onReadFulfilled(self: *StreamConsumer, data_: ?ReadData) void {+ fn onReadFulfilled(self: *StreamConsumer, result: js.Value) void {const local = self.execution.js.local.?;-- const data = data_ orelse {- return self.finish(local, null);- };-- self._onReadFulfilled(data) catch {+ self._onReadFulfilled(result) catch {self.finish(local, null);};}- fn _onReadFulfilled(self: *StreamConsumer, data: ReadData) !void {+ fn _onReadFulfilled(self: *StreamConsumer, result: js.Value) !void {const exec = self.execution;const local = exec.js.local.?;- if (data.done) {- // Stream is finished, concatenate all chunks and resolve- self.reader.releaseLock();- const result = try self.concatenateChunks(exec.call_arena);- local.toLocal(self.resolver).resolve("arrayBuffer complete", js.ArrayBuffer{ .values = result });- return;+ if (result.isObject() == false) {+ return self.finish(local, "Read result is not an object");}+ const obj = result.toObject();- // Collect the chunk data- const value = data.value;- if (!value.isUndefined()) {- // Try to get bytes from the value (could be Uint8Array or string)- if (value.isTypedArray() or value.isArrayBufferView() or value.isArrayBuffer()) {- if (local.jsValueToZig([]u8, value)) |typed_data| {- const chunk_copy = try self.arena.dupe(u8, typed_data);- try self.chunks.append(self.arena, chunk_copy);- self.total_len += chunk_copy.len;- } else |_| {}- } else if (value.isString()) |str| {- const slice = try str.toSlice();- const chunk_copy = try self.arena.dupe(u8, slice);- try self.chunks.append(self.arena, chunk_copy);- self.total_len += chunk_copy.len;- }+ if ((try obj.get("done")).toBool()) {+ const body = try self.concatenateChunks(exec.call_arena);+ return package(self.kind, body, self.content_type, local.toLocal(self.resolver), exec);}++ const value = try obj.get("value");+ if (value.isUint8Array() == false) {+ // A chunk that is not a Uint8Array is a TypeError.+ return self.finish(local, "Response body chunk is not a Uint8Array");+ }+ const chunk_copy = try self.arena.dupe(u8, try local.jsValueToZig([]u8, value));+ try self.chunks.append(self.arena, chunk_copy);+ self.total_len += chunk_copy.len;try self.pumpRead();}@@ -451,77 +504,12 @@ const StreamConsumer = struct {fn finish(self: *StreamConsumer, local: *const js.Local, err: ?[]const u8) void {self.reader.releaseLock();- local.toLocal(self.resolver).rejectError("arrayBuffer error", .{ .type_error = err orelse "Failed to read stream" });+ local.toLocal(self.resolver).rejectError("stream body", .{ .type_error = err orelse "Failed to read stream" });}};-pub fn blob(self: *Response, exec: *const Execution) !js.Promise {- const local = exec.js.local.?;- try self.consume(local);- const body = switch (self._body) {- .bytes => |b| b,- .empty => "",- .stream => return local.typeError("Cannot read blob from stream body"),- };- const content_type = try self._headers.get("content-type", exec) orelse "";- const b = try Blob.initFromBytes(body, content_type, exec);- return local.resolvePromise(b);-}--pub fn bytes(self: *Response, exec: *const Execution) !js.Promise {- const local = exec.js.local.?;- try self.consume(local);- const body = switch (self._body) {- .bytes => |b| b,- .empty => "",- .stream => return local.typeError("Cannot read bytes from stream body"),- };- return local.resolvePromise(js.TypedArray(u8){ .values = body });-}--pub fn formData(self: *Response, exec: *const Execution) !js.Promise {- const local = exec.js.local.?;- try self.consume(local);- const body = switch (self._body) {- .bytes => |b| b,- .empty => "",- .stream => return local.typeError("Cannot read FormData from stream body"),- };-- const content_type = try self._headers.get("content-type", exec) orelse {- return local.typeError("Failed to parse body as FormData");- };- var it = ContentTypeIterator.init(content_type);- const essence = it.essence;-- // [RFC7578]- // Parse bytes, using the value of the `boundary` parameter from mimeType,- // per the rules set forth in Returning Values from Forms: multipart/form-data.- if (std.ascii.eqlIgnoreCase(essence, "multipart/form-data")) {- const boundary = it.findBoundary();- if (boundary.len == 0) {- return local.typeError("Failed to parse body as FormData");- }-- const form_data = FormData.initFromMultipart(body, boundary, exec) catch |err| switch (err) {- error.OutOfMemory => return err,- else => return local.typeError("Failed to parse body as FormData"),- };- return local.resolvePromise(form_data);- }-- if (std.ascii.eqlIgnoreCase(essence, "application/x-www-form-urlencoded")) {- const form_data = FormData.initFromUrlEncoded(body, exec) catch |err| switch (err) {- error.OutOfMemory => return err,- else => return local.typeError("Failed to parse body as FormData"),- };- return local.resolvePromise(form_data);- }-- return local.typeError("Failed to parse body as FormData");-}-pub fn clone(self: *const Response, exec: *const Execution) !*Response {+ try self.checkUnusable(exec.js.local.?);const session = exec.session;const body_len = switch (self._body) {.bytes => |b| b.len,diff --git a/src/browser/webapi/net/XMLHttpRequest.zig b/src/browser/webapi/net/XMLHttpRequest.zigindex 329b6f64f..239a9dff7 100644--- a/src/browser/webapi/net/XMLHttpRequest.zig+++ b/src/browser/webapi/net/XMLHttpRequest.zig@@ -254,7 +254,29 @@ pub fn setRequestHeader(self: *XMLHttpRequest, name: []const u8, value: []constif (self._ready_state != .opened) {return error.InvalidStateError;}- return self._request_headers.append(name, value, exec);++ if (isByteString(name) == false or isByteString(value) == false) {+ // A code point above U+00FF is a TypeError, ...+ return error.TypeError;+ }+ return self._request_headers.append(name, value, exec) catch |err| switch (err) {+ error.TypeError => {+ // ... but a valid "string" is a SyntaxError if it isn't a valid+ // header name or value+ return error.SyntaxError;+ },+ else => err,+ };+}++fn isByteString(s: []const u8) bool {+ var it = std.unicode.Utf8View.initUnchecked(s).iterator();+ while (it.nextCodepoint()) |cp| {+ if (cp > 0xFF) {+ return false;+ }+ }+ return true;}// https://xhr.spec.whatwg.org/#the-overridemimetype()-method@@ -294,7 +316,7 @@ pub fn send(self: *XMLHttpRequest, body_: ?BodyInit, exec_: *const Execution) !v// applies if the author hasn't already set one via// setRequestHeader.if (extracted.content_type) |ct| {- if (!self._request_headers.has("content-type", exec_)) {+ if (try self._request_headers.has("content-type", exec_) == false) {try self._request_headers.append("content-type", ct, exec_);}}diff --git a/src/browser/webapi/net/body_init.zig b/src/browser/webapi/net/body_init.zigindex 99579ac41..aba2d58d6 100644--- a/src/browser/webapi/net/body_init.zig+++ b/src/browser/webapi/net/body_init.zig@@ -32,13 +32,15 @@ const std = @import("std");const lp = @import("lightpanda");const js = @import("../../js/js.zig");+const ContentTypeIterator = @import("../../Mime.zig").ContentTypeIterator;const Blob = @import("../Blob.zig");+const ReadableStream = @import("../streams/ReadableStream.zig");const FormData = @import("FormData.zig");const URLSearchParams = @import("URLSearchParams.zig");-const ReadableStream = @import("../streams/ReadableStream.zig");+const Execution = js.Execution;const Allocator = std.mem.Allocator;pub const BodyInit = union(enum) {@@ -46,14 +48,14 @@ pub const BodyInit = union(enum) {form_data: *FormData,url_search_params: *URLSearchParams,stream: *ReadableStream,- buffer: js.TypedArray(u8),+ buffer: js.BufferSource,bytes: []const u8, // must be last, js.Bridge will map anything to a string// How much a call to `extract` will dupe. Used for ArenaPool size selection.pub fn sizeHint(self: BodyInit) ?usize {return switch (self) {.bytes => |b| b.len,- .buffer => |b| b.values.len,+ .buffer => |b| b.bytes.len,.blob => |b| b._slice.len + b._mime.len,.form_data, .url_search_params, .stream => null,};@@ -105,10 +107,9 @@ pub const BodyInit = union(enum) {};},.buffer => |b| {- // Buffer sources carry no default Content-Type (Fetch §6.5).return .{- .bytes = try arena.dupe(u8, b.values),- .content_type = null,+ .bytes = try arena.dupe(u8, b.bytes),+ .content_type = null, // Buffer sources carry no default Content-Type};},.stream => |stream| {@@ -132,6 +133,33 @@ pub const Extracted = struct {content_type: ?[]const u8,};+pub fn parseFormData(body: []const u8, content_type_: ?[]const u8, exec: *const Execution) error{ OutOfMemory, TypeError }!*FormData {+ const content_type = content_type_ orelse return error.TypeError;+ var it = ContentTypeIterator.init(content_type);+ const essence = it.essence;++ if (std.ascii.eqlIgnoreCase(essence, "multipart/form-data")) {+ // Parse bytes, using the value of the `boundary` parameter from mimeType+ const boundary = it.findBoundary();+ if (boundary.len == 0) {+ return error.TypeError;+ }+ return FormData.initFromMultipart(body, boundary, exec) catch |err| switch (err) {+ error.OutOfMemory => return error.OutOfMemory,+ else => return error.TypeError,+ };+ }++ if (std.ascii.eqlIgnoreCase(essence, "application/x-www-form-urlencoded")) {+ return FormData.initFromUrlEncoded(body, exec) catch |err| switch (err) {+ error.OutOfMemory => return error.OutOfMemory,+ else => return error.TypeError,+ };+ }++ return error.TypeError;+}+// "UTF-8 decode" (Encoding §4.2) strips a leading BOM; consuming a body as// text/json must use it, while arrayBuffer/blob/bytes keep the raw bytes.pub fn stripUtf8Bom(bytes: []const u8) []const u8 {@@ -188,7 +216,7 @@ test "BodyInit: FormData emits multipart with random boundary" {}test "BodyInit: buffer source has no default Content-Type" {- const r = try (BodyInit{ .buffer = .{ .values = "hello" } }).extract(testing.arena_allocator);+ const r = try (BodyInit{ .buffer = .{ .bytes = "hello" } }).extract(testing.arena_allocator);try testing.expectString("hello", r.bytes);try testing.expectEqual(true, r.content_type == null);}diff --git a/src/browser/webapi/streams/ReadableStream.zig b/src/browser/webapi/streams/ReadableStream.zigindex 9b094bc62..bcfe0ba24 100644--- a/src/browser/webapi/streams/ReadableStream.zig+++ b/src/browser/webapi/streams/ReadableStream.zig@@ -53,6 +53,7 @@ _pulling: bool = false,_pull_again: bool = false,_cancel: ?Cancel = null,_collected: bool = false,+_disturbed: bool = false, // once cancelled, cannot be consumed againconst UnderlyingSource = struct {cancel: ?js.Function.Global = null,@@ -122,7 +123,7 @@ pub fn initWithText(text: []const u8, exec: *const Execution) !*ReadableStream {pub fn getReader(self: *ReadableStream, exec: *const Execution) !*ReadableStreamDefaultReader {if (self.getLocked()) {- return error.ReaderLocked;+ return exec.js.typeError("ReadableStream is locked");}const reader = try ReadableStreamDefaultReader.init(self, exec);@@ -244,6 +245,7 @@ fn shouldCallPull(self: *const ReadableStream) bool {pub fn cancel(self: *ReadableStream, reason: ?[]const u8, exec: *const Execution) !js.Promise {const local = exec.js.local.?;+ self._disturbed = true;if (self._state != .readable) {if (self._cancel) |c| {@@ -301,7 +303,7 @@ const PipeTransform = struct {pub fn pipeThrough(self: *ReadableStream, transform: PipeTransform, exec: *const Execution) !*ReadableStream {if (self.getLocked()) {- return error.ReaderLocked;+ return exec.js.typeError("ReadableStream is locked");}// Start async piping from this stream to the writable sidediff --git a/src/browser/webapi/streams/ReadableStreamDefaultReader.zig b/src/browser/webapi/streams/ReadableStreamDefaultReader.zigindex 929e9d91b..e232a3e15 100644--- a/src/browser/webapi/streams/ReadableStreamDefaultReader.zig+++ b/src/browser/webapi/streams/ReadableStreamDefaultReader.zig@@ -61,6 +61,7 @@ pub fn read(self: *ReadableStreamDefaultReader, exec: *const Execution) !js.Promconst stream = self._stream orelse {return local.rejectPromise(.{ .type_error = "Reader has been released" });};+ stream._disturbed = true;if (stream._state == .errored) {//const err = stream._stored_error orelse "Stream errored";diff --git a/src/network/HttpClient.zig b/src/network/HttpClient.zigindex f63e44c9f..2ff673156 100644--- a/src/network/HttpClient.zig+++ b/src/network/HttpClient.zig@@ -3214,7 +3214,9 @@ pub const Transfer = struct {.redirect_count = self._redirect_count,};- if (conn.getResponseHeader("content-type", 0)) |ct| {+ if (conn.getResponseHeader("content-type", 0)) |first| {+ // last one wins+ const ct = if (first.amount < 2) first else conn.getResponseHeader("content-type", first.amount - 1) orelse first;var hdr = &self.res.header.?;const value = ct.value;const len = @min(value.len, http.ResponseHead.MAX_CONTENT_TYPE_LEN);