Skip to content

Commit

Permalink
Fix browser clients in workers (#1715)
Browse files Browse the repository at this point in the history
  • Loading branch information
simolus3 authored Feb 13, 2025
1 parent e28f9f5 commit 900da9f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 21 deletions.
4 changes: 3 additions & 1 deletion pkgs/http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,10 @@

* Fixed default encoding for application/json without a charset
to use utf8 instead of latin1, ensuring proper JSON decoding.
* Avoid references to `window` in `BrowserClient`, restoring support for web
workers and NodeJS.

## 1.3.0-wip
## 1.3.0

* Fixed unintended HTML tags in doc comments.
* Switched `BrowserClient` to use Fetch API instead of `XMLHttpRequest`.
Expand Down
44 changes: 24 additions & 20 deletions pkgs/http/lib/src/browser_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,9 @@ import 'package:web/web.dart'
AbortController,
HeadersInit,
ReadableStreamDefaultReader,
RequestInfo,
RequestInit,
Response,
window;
Response;

import 'base_client.dart';
import 'base_request.dart';
Expand All @@ -30,6 +30,12 @@ BaseClient createClient() {
return BrowserClient();
}

@JS('fetch')
external JSPromise<Response> _fetch(
RequestInfo input, [
RequestInit init,
]);

/// A `package:web`-based HTTP client that runs in the browser and is backed by
/// [`window.fetch`](https://fetch.spec.whatwg.org/).
///
Expand Down Expand Up @@ -63,24 +69,22 @@ class BrowserClient extends BaseClient {

final bodyBytes = await request.finalize().toBytes();
try {
final response = await window
.fetch(
'${request.url}'.toJS,
RequestInit(
method: request.method,
body: bodyBytes.isNotEmpty ? bodyBytes.toJS : null,
credentials: withCredentials ? 'include' : 'same-origin',
headers: {
if (request.contentLength case final contentLength?)
'content-length': contentLength,
for (var header in request.headers.entries)
header.key: header.value,
}.jsify()! as HeadersInit,
signal: _abortController.signal,
redirect: request.followRedirects ? 'follow' : 'error',
),
)
.toDart;
final response = await _fetch(
'${request.url}'.toJS,
RequestInit(
method: request.method,
body: bodyBytes.isNotEmpty ? bodyBytes.toJS : null,
credentials: withCredentials ? 'include' : 'same-origin',
headers: {
if (request.contentLength case final contentLength?)
'content-length': contentLength,
for (var header in request.headers.entries)
header.key: header.value,
}.jsify()! as HeadersInit,
signal: _abortController.signal,
redirect: request.followRedirects ? 'follow' : 'error',
),
).toDart;

final contentLengthHeader = response.headers.get('content-length');

Expand Down

0 comments on commit 900da9f

Please sign in to comment.