feat: port the client to MyGo native UI (0.3.0)

Switch from Asuka to MyGo, keeping the API client and the feature set:

- servers: saved servers, passwordless and password login, proxy,
  self-signed certificates, per-server device tokens (Keystore), connect
  form, instance list sheet with switch/disconnect
- sessions: virtualized list, search, new session, rename/archive/delete,
  running indicator, event stream keeps it live
- chat: pushed window with system back bar, streaming Markdown via
  ui/markdown, reasoning and tool rows with image previews, footer menu
  (read aloud via a Kotlin TTS plugin, copy, fork), user message menu
  (copy, revert, fork), context usage ring and detail sheet, attachments
  (photos/files via the document picker), permissions
- release builds allow plain http:// LAN servers (Go's net/http dials
  directly, no cleartext manifest needed)
- a local fork of MyGo (third_party/mygo) lowers the Android host's
  minSdk to 24 (Android 7.0); Go 1.27.4 via mise

Version 0.3.0.
This commit is contained in:
OpenChamber committed 2026-11-18 13:22:59 +08:00
1 parent 2fb4a8ea79
commit 6c0ee61750
2538 files changed
+675779 -4792

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 MyGo contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+41
View File
@@ -0,0 +1,41 @@
# @mygo-plugins/fetch
A `fetch` for [MyGo](https://github.com/egoist/mygo) apps that makes HTTP
requests from Go: not subject to CORS, free to set any header (Origin,
Cookie, User-Agent, ...), with the standard options and a standard
`Response` whose body streams as Go reads it.
Use the plugin in Go:
```go
import "github.com/egoist/mygo/plugins/fetch"
mygo.Use(fetch.Plugin) // or fetch.New(fetch.Options{Client: ..., Allow: ...})
```
and fetch in the frontend:
```ts
import { fetch } from "@mygo-plugins/fetch";
const ctrl = new AbortController();
const res = await fetch("https://api.example.com/items", {
headers: { authorization: `Bearer ${token}` },
signal: ctrl.signal, // aborting cancels the request in Go
});
const items = await res.json();
```
- Aborting the signal, canceling the body, navigating away or closing the
window cancels the request in Go.
- `redirect: "manual"` returns the redirect response itself, with its
`Location`, instead of an opaque response.
- `mode`, `credentials`, `cache` and the like do not apply; cookies are those
of the Go side's `http.Client` (give it a `Jar` to keep them).
- Every response header is readable but `Set-Cookie` and `Set-Cookie2`,
which are filtered before the response reaches the page.
- URLs that are not http or https (the app's own pages, `data:`, `blob:`) go
to the webview's `fetch`.
[The documentation](https://github.com/egoist/mygo/blob/main/docs/plugins/fetch.md)
covers streaming, errors and the options of the Go side.
+178
View File
@@ -0,0 +1,178 @@
// Package fetch is the fetch plugin of MyGo: pages make HTTP requests from
// Go with the fetch of its JavaScript package, @mygo-plugins/fetch, which
// takes and returns the standard Request options and Response. Requests
// made this way are not subject to CORS, may set any header (Origin,
// Cookie, User-Agent, ...) and read every response header but Set-Cookie
// and Set-Cookie2, which are filtered before sending the response to pages.
//
// mygo.Use(fetch.Plugin)
//
// and in the frontend:
//
// import { fetch } from "@mygo-plugins/fetch";
//
// const res = await fetch("https://api.example.com/items", {
// headers: { authorization: `Bearer ${token}` },
// });
// const items = await res.json();
//
// The response body streams to the page as Go reads it, and aborting the
// request's signal cancels it in Go. URLs that are not http or https, such
// as the app's own pages, go to the webview's fetch.
package fetch
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"strings"
"github.com/egoist/mygo"
"github.com/egoist/mygo/netproxy"
)
// Options configure the plugin.
type Options struct {
// Client makes the requests; nil means a client of
// netproxy.Transport(), which follows the system's proxy settings. Its
// CheckRedirect limits the redirects followed when the request's
// redirect mode is "follow".
Client *http.Client
// Allow, when not nil, decides whether pages may make a request; a
// request it refuses rejects with an error.
Allow func(r *http.Request) bool
}
// Plugin is the plugin with the default options.
var Plugin = New(Options{})
// New returns the plugin with options.
func New(opts Options) mygo.Plugin {
if opts.Client == nil {
opts.Client = &http.Client{Transport: netproxy.Transport()}
}
return mygo.Plugin{Name: "fetch", Service: &service{opts}}
}
type service struct{ opts Options }
// request is what the page asks for.
type request struct {
URL string `json:"url"`
Method string `json:"method"`
Headers [][2]string `json:"headers"`
Body []byte `json:"body"`
Redirect string `json:"redirect"`
}
// part is the response: its head first, then chunks of its body.
type part struct {
Status int `json:"status,omitzero"`
StatusText string `json:"statusText,omitzero"`
URL string `json:"url,omitzero"`
Redirected bool `json:"redirected,omitzero"`
Headers [][2]string `json:"headers,omitzero"`
Chunk []byte `json:"chunk,omitzero"`
}
// Fetch makes the request and streams the response to the page.
func (s *service) Fetch(ctx context.Context, req request, parts *mygo.Channel[part]) error {
return s.fetch(ctx, req, parts.Send)
}
// chunkSize is the most body bytes a part holds.
const chunkSize = 64 << 10
func (s *service) fetch(ctx context.Context, req request, send func(part) error) error {
r, err := http.NewRequestWithContext(ctx, req.Method, req.URL, nil)
if err != nil {
return err
}
if r.URL.Scheme != "http" && r.URL.Scheme != "https" {
return fmt.Errorf("unsupported URL scheme %q", r.URL.Scheme)
}
if req.Body != nil {
r.Body = io.NopCloser(bytes.NewReader(req.Body))
r.ContentLength = int64(len(req.Body))
body := req.Body
r.GetBody = func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(body)), nil }
}
for _, h := range req.Headers {
switch http.CanonicalHeaderKey(h[0]) {
case "Host":
r.Host = h[1]
case "Content-Length": // the body's
default:
r.Header.Add(h[0], h[1])
}
}
if s.opts.Allow != nil && !s.opts.Allow(r) {
return fmt.Errorf("the app does not allow requests to %s", r.URL.Redacted())
}
client := *s.opts.Client
redirected := false
check := client.CheckRedirect
client.CheckRedirect = func(next *http.Request, via []*http.Request) error {
switch req.Redirect {
case "manual":
return http.ErrUseLastResponse
case "error":
return errors.New("redirected with redirect mode \"error\"")
}
if check != nil {
if err := check(next, via); err != nil {
return err
}
} else if len(via) >= 20 { // as browsers
return errors.New("too many redirects")
}
redirected = true
return nil
}
res, err := client.Do(r)
if err != nil {
return err
}
defer res.Body.Close()
head := part{
Status: res.StatusCode,
StatusText: strings.TrimSpace(strings.TrimPrefix(res.Status, fmt.Sprint(res.StatusCode))),
URL: res.Request.URL.String(),
Redirected: redirected,
Headers: [][2]string{},
}
for k, vs := range res.Header {
k = strings.ToLower(k)
if k == "set-cookie" || k == "set-cookie2" {
continue
}
for _, v := range vs {
head.Headers = append(head.Headers, [2]string{k, v})
}
}
if err := send(head); err != nil {
return err
}
buf := make([]byte, chunkSize)
for {
// What arrived goes out at once, for streamed responses.
n, err := res.Body.Read(buf)
if n > 0 {
// Send encodes the chunk before returning, so buf can be reused.
if err := send(part{Chunk: buf[:n]}); err != nil {
return err
}
}
if err == io.EOF {
return nil
}
if err != nil {
return err
}
}
}
+186
View File
@@ -0,0 +1,186 @@
package fetch
import (
"context"
"io"
"net/http"
"net/http/cookiejar"
"net/http/httptest"
"strings"
"testing"
)
func run(t *testing.T, s *service, req request) ([]part, error) {
t.Helper()
var parts []part
err := s.fetch(context.Background(), req, func(p part) error {
p.Chunk = append([]byte(nil), p.Chunk...)
parts = append(parts, p)
return nil
})
return parts, err
}
func header(p part, name string) string {
for _, h := range p.Headers {
if h[0] == name {
return h[1]
}
}
return ""
}
func body(parts []part) string {
var b strings.Builder
for _, p := range parts[1:] {
b.Write(p.Chunk)
}
return b.String()
}
func TestFetch(t *testing.T) {
mux := http.NewServeMux()
mux.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
w.Header().Add("X-Multi", "a")
w.Header().Add("X-Multi", "b")
w.Header().Set("X-Origin", r.Header.Get("Origin"))
w.Header().Set("X-Host", r.Host)
w.WriteHeader(http.StatusCreated)
io.WriteString(w, r.Method+" "+string(b))
})
mux.HandleFunc("/big", func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, strings.Repeat("x", 3*chunkSize/2))
})
mux.HandleFunc("/redirect", func(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/echo", http.StatusFound)
})
srv := httptest.NewServer(mux)
defer srv.Close()
s := New(Options{}).Service.(*service)
parts, err := run(t, s, request{
URL: srv.URL + "/echo",
Method: "POST",
Headers: [][2]string{{"origin", "https://example.com"}, {"host", "api.test"}, {"content-length", "999"}},
Body: []byte("hi"),
})
if err != nil {
t.Fatal(err)
}
head := parts[0]
if head.Status != 201 || head.StatusText != "Created" || head.Redirected {
t.Errorf("head = %+v", head)
}
if header(head, "x-origin") != "https://example.com" || header(head, "x-host") != "api.test" {
t.Errorf("request headers were not sent: %v", head.Headers)
}
n := 0
for _, h := range head.Headers {
if h[0] == "x-multi" {
n++
}
}
if n != 2 {
t.Errorf("repeated header sent %d times: %v", n, head.Headers)
}
if got := body(parts); got != "POST hi" {
t.Errorf("body = %q", got)
}
parts, err = run(t, s, request{URL: srv.URL + "/big", Method: "GET"})
if err != nil || len(parts) < 3 || len(body(parts)) != 3*chunkSize/2 {
t.Errorf("big body: %d parts, %v", len(parts), err)
}
for _, p := range parts[1:] {
if len(p.Chunk) > chunkSize {
t.Errorf("chunk of %d bytes", len(p.Chunk))
}
}
parts, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET"})
if err != nil || parts[0].Status != 201 || !parts[0].Redirected || parts[0].URL != srv.URL+"/echo" {
t.Errorf("followed redirect: %+v, %v", parts, err)
}
parts, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET", Redirect: "manual"})
if err != nil || parts[0].Status != 302 || header(parts[0], "location") != "/echo" {
t.Errorf("manual redirect: %+v, %v", parts, err)
}
if _, err = run(t, s, request{URL: srv.URL + "/redirect", Method: "GET", Redirect: "error"}); err == nil {
t.Error("redirect mode error followed a redirect")
}
if _, err = run(t, s, request{URL: "file:///etc/passwd", Method: "GET"}); err == nil {
t.Error("fetched a file URL")
}
deny := New(Options{Allow: func(r *http.Request) bool { return r.URL.Path != "/echo" }}).Service.(*service)
if _, err = run(t, deny, request{URL: srv.URL + "/echo", Method: "GET"}); err == nil || !strings.Contains(err.Error(), "does not allow") {
t.Errorf("Allow: %v", err)
}
}
func TestFetchFiltersCookieHeaders(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Set-Cookie", "session=secret; HttpOnly; Path=/")
w.Header().Add("Set-Cookie", "other=value; Path=/")
w.Header().Set("Set-Cookie2", "legacy=secret")
w.Header().Set("X-Visible", "yes")
}))
defer srv.Close()
jar, err := cookiejar.New(nil)
if err != nil {
t.Fatal(err)
}
client := srv.Client()
client.Jar = jar
s := New(Options{Client: client}).Service.(*service)
parts, err := run(t, s, request{URL: srv.URL, Method: "GET"})
if err != nil {
t.Fatal(err)
}
for _, h := range parts[0].Headers {
if strings.EqualFold(h[0], "Set-Cookie") || strings.EqualFold(h[0], "Set-Cookie2") {
t.Errorf("cookie header sent to the page: %v", h)
}
}
if header(parts[0], "x-visible") != "yes" {
t.Error("ordinary response header was filtered")
}
r, err := http.NewRequest("GET", srv.URL, nil)
if err != nil {
t.Fatal(err)
}
if cookies := jar.Cookies(r.URL); len(cookies) != 2 {
t.Errorf("Go cookie jar = %v; want both cookies retained", cookies)
}
}
func TestFetchStops(t *testing.T) {
release := make(chan struct{})
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "first")
w.(http.Flusher).Flush()
select {
case <-release:
case <-r.Context().Done():
}
}))
defer srv.Close()
defer close(release)
s := New(Options{}).Service.(*service)
// A streamed body arrives as it is written, and the request stops
// when the page stops taking it.
var got []string
stop := io.ErrClosedPipe
err := s.fetch(context.Background(), request{URL: srv.URL, Method: "GET"}, func(p part) error {
if p.Chunk != nil {
got = append(got, string(p.Chunk))
return stop
}
return nil
})
if err != stop || len(got) != 1 || got[0] != "first" {
t.Errorf("got %q, %v", got, err)
}
}
+41
View File
@@ -0,0 +1,41 @@
{
"name": "@mygo-plugins/fetch",
"version": "0.10.0",
"description": "A fetch that makes HTTP requests from Go, for MyGo desktop apps",
"keywords": [
"mygo",
"desktop",
"webview",
"go",
"fetch"
],
"repository": {
"type": "git",
"url": "git+https://github.com/egoist/mygo.git",
"directory": "plugins/fetch"
},
"license": "MIT",
"type": "module",
"sideEffects": false,
"exports": {
".": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
}
},
"types": "./dist/index.d.ts",
"files": [
"dist",
"README.md"
],
"scripts": {
"build": "bun run ../build.ts",
"test": "bun test"
},
"peerDependencies": {
"mygo-runtime": "^0.10.0"
},
"devDependencies": {
"mygo-runtime": "^0.10.0"
}
}
+311
View File
@@ -0,0 +1,311 @@
import { afterEach, expect, test } from "bun:test";
import { b64, fakeGo, tick, type GoCall } from "../../fake-go";
import { fetch } from "./index";
let go: ReturnType<typeof fakeGo> | undefined;
afterEach(() => go?.uninstall());
interface Req {
url: string;
method: string;
headers: [string, string][];
body: string | null;
redirect: string;
}
const head = (status = 200, headers: [string, string][] = []) => ({
status,
statusText: "OK",
url: "https://example.com/final",
redirected: true,
headers,
});
test("sends the request and streams the response", async () => {
let got: Req | undefined;
go = fakeGo({
"plugin:fetch.Fetch": (c: GoCall) => {
got = c.args[0] as Req;
c.send(1, head(201, [["content-type", "application/json"], ["x-a", "1"]]));
c.send(1, { chunk: b64('{"a":') });
c.send(1, { chunk: b64("1}") });
},
});
const res = await fetch(new URL("https://example.com/items"), {
method: "post",
headers: { origin: "https://app.test", "x-token": "t" },
body: new URLSearchParams({ q: "go" }),
});
expect(got).toMatchObject({ url: "https://example.com/items", method: "POST", redirect: "follow" });
expect(Object.fromEntries(got!.headers)).toEqual({
origin: "https://app.test",
"x-token": "t",
"content-type": "application/x-www-form-urlencoded;charset=UTF-8",
});
expect(Buffer.from(got!.body!, "base64").toString()).toBe("q=go");
expect(res).toBeInstanceOf(Response);
expect(res.status).toBe(201);
expect(res.url).toBe("https://example.com/final");
expect(res.redirected).toBe(true);
expect(res.headers.get("x-a")).toBe("1");
expect(await res.json()).toEqual({ a: 1 });
});
test("takes a Request", async () => {
let got: Req | undefined;
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
got = c.args[0] as Req;
c.send(1, head(204));
},
});
const res = await fetch(new Request("https://example.com/x", { method: "PUT", body: "hi", redirect: "manual" }));
expect(got).toMatchObject({ method: "PUT", redirect: "manual", body: b64("hi") });
expect(res.status).toBe(204);
expect(res.body).toBeNull();
});
test("clones preserve response metadata and independently readable bodies", async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, head(201, [["content-type", "text/plain"], ["x-test", "clone"]]));
c.send(1, { chunk: b64("first ") });
c.send(1, { chunk: b64("second") });
},
});
const res = await fetch("https://example.com/start");
const copy = res.clone();
const another = copy.clone();
for (const response of [res, copy, another]) {
expect(response).toBeInstanceOf(Response);
expect(response.url).toBe("https://example.com/final");
expect(response.redirected).toBe(true);
expect(response.status).toBe(201);
expect(response.statusText).toBe("OK");
expect(response.headers.get("x-test")).toBe("clone");
expect(response.bodyUsed).toBe(false);
}
expect(await Promise.all([res.text(), copy.text(), another.text()])).toEqual([
"first second", "first second", "first second",
]);
expect(go.calls).toHaveLength(1);
});
for (const status of [101, 204]) {
test(`clones preserve metadata of a bodyless ${status} response`, async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, { status, statusText: "", url: "https://example.com/final", redirected: true });
},
});
const res = await fetch("https://example.com/start");
const copy = res.clone().clone();
expect(copy.status).toBe(status);
expect(copy.url).toBe(res.url);
expect(copy.redirected).toBe(true);
expect(copy.body).toBeNull();
});
}
test("cloning still rejects a locked or consumed body", async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, head());
c.send(1, { chunk: b64("body") });
},
});
const res = await fetch("https://example.com/start");
const copy = res.clone();
const reader = copy.body!.getReader();
expect(() => copy.clone()).toThrow(TypeError);
reader.releaseLock();
expect(await copy.text()).toBe("body");
expect(() => copy.clone()).toThrow(TypeError);
expect(await res.text()).toBe("body");
expect(() => res.clone()).toThrow(TypeError);
});
test("rejects URL credentials before calling Go", async () => {
go = fakeGo({ "plugin:fetch.Fetch": (c) => c.send(1, head(204)) });
for (const url of [
"https://user:password@example.com/",
"http://user@example.com/",
"https://:password@example.com/",
]) {
for (const input of [url, new URL(url)]) {
await expect(fetch(input)).rejects.toThrow(TypeError);
expect(go.calls).toEqual([]);
}
}
});
test("allows an empty URL userinfo and explicit authorization", async () => {
let got: Req | undefined;
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
got = c.args[0] as Req;
c.send(1, head(204));
},
});
await fetch("https://:@example.com/", { headers: { authorization: "Basic dXNlcjpwYXNzd29yZA==" } });
expect(got?.url).toBe("https://example.com/");
expect(got?.headers).toContainEqual(["authorization", "Basic dXNlcjpwYXNzd29yZA=="]);
});
test("inherits a Request body when init.body is null or omitted", async () => {
let got: Req | undefined;
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
got = c.args[0] as Req;
c.send(1, head(204));
},
});
for (const body of [undefined, null, "replacement", ""]) {
const req = new Request("https://example.com/x", { method: "POST", body: "original" });
await fetch(req, { body });
expect(got?.body).toBe(b64(body ?? "original"));
}
});
test("an explicit null signal stops inheriting the Request signal", async () => {
go = fakeGo({ "plugin:fetch.Fetch": (c) => c.send(1, head(204)) });
const signal = AbortSignal.abort(new Error("original request aborted"));
const req = new Request("https://example.com/x", { signal });
expect(await fetch(req, { signal: undefined }).catch((err) => err)).toBe(signal.reason);
expect((await fetch(req, { signal: null })).status).toBe(204);
expect(go.calls).toHaveLength(1);
});
test("rejects when Go fails", async () => {
go = fakeGo({
"plugin:fetch.Fetch": () => {
throw new Error("dial tcp: connection refused");
},
});
const err = await fetch("https://example.com").catch((e) => e);
expect(err).toBeInstanceOf(TypeError);
expect(err.message).toBe("fetch failed: dial tcp: connection refused");
});
test("explains a missing Go side", async () => {
go = fakeGo({});
const err = await fetch("https://example.com").catch((e) => e);
expect(err.message).toBe("fetch failed: method plugin:fetch.Fetch is not bound");
go.uninstall();
go = fakeGo({
"plugin:fetch.Fetch": () => {
throw new Error("the fetch plugin is not used: call mygo.Use with it before App.Run");
},
});
expect((await fetch("https://example.com").catch((e) => e)).message).toContain("mygo.Use(fetch.Plugin)");
});
test("errors the body when Go fails while streaming", async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, head());
c.send(1, { chunk: b64("par") });
throw new Error("unexpected EOF");
},
});
const res = await fetch("https://example.com");
expect((await res.text().catch((e) => e)).message).toBe("fetch failed: unexpected EOF");
});
test("aborts", async () => {
let stopped = false;
const streaming = (c: GoCall) =>
new Promise<void>((resolve) => {
c.send(1, head());
c.send(1, { chunk: b64("first") });
c.signal.addEventListener("abort", () => {
stopped = true;
resolve();
});
});
go = fakeGo({ "plugin:fetch.Fetch": streaming });
const ctrl = new AbortController();
const res = await fetch("https://example.com", { signal: ctrl.signal });
const reader = res.body!.getReader();
expect(new TextDecoder().decode((await reader.read()).value)).toBe("first");
ctrl.abort();
expect((await reader.read().catch((e) => e)).name).toBe("AbortError");
await tick();
expect(stopped).toBe(true);
// Before the response.
go.uninstall();
go = fakeGo({ "plugin:fetch.Fetch": (c) => new Promise<void>((r) => c.signal.addEventListener("abort", () => r())) });
const early = new AbortController();
const p = fetch("https://example.com", { signal: early.signal });
await tick();
early.abort();
expect((await p.catch((e) => e)).name).toBe("AbortError");
expect((await fetch("https://example.com", { signal: AbortSignal.abort() }).catch((e) => e)).name).toBe("AbortError");
// Canceling the body stops Go too.
go.uninstall();
stopped = false;
go = fakeGo({ "plugin:fetch.Fetch": streaming });
await (await fetch("https://example.com")).body!.cancel();
await tick();
expect(stopped).toBe(true);
});
test("leaves other schemes to the webview", async () => {
go = fakeGo({});
const res = await fetch("data:text/plain,hello");
expect(await res.text()).toBe("hello");
expect(go.calls).toEqual([]);
});
test("refuses a GET body", async () => {
go = fakeGo({});
expect(fetch("https://example.com", { body: "x" })).rejects.toThrow(TypeError);
});
test("does not send a JSON POST aborted before its body is ready", async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, head());
},
});
const ctrl = new AbortController();
const pending = fetch("https://example.com/items", {
method: "POST",
body: JSON.stringify({ name: "Ada" }),
signal: ctrl.signal,
});
ctrl.abort();
const result = await pending.then(() => "sent", (error: unknown) => error);
expect(result).toBe(ctrl.signal.reason);
expect(go.calls).toEqual([]);
});
for (const source of ["init", "Request"] as const) {
test(`does not send a request aborted while reading its ${source} body`, async () => {
go = fakeGo({
"plugin:fetch.Fetch": (c) => {
c.send(1, head());
},
});
let finish!: () => void;
const body = new ReadableStream<Uint8Array>({
start(controller) {
controller.enqueue(new TextEncoder().encode("upload"));
finish = () => controller.close();
},
});
const ctrl = new AbortController();
const reason = new Error("Upload canceled");
const pending = source === "init"
? fetch("https://example.com/upload", { method: "POST", body, signal: ctrl.signal })
: fetch(new Request("https://example.com/upload", { method: "POST", body, signal: ctrl.signal }));
ctrl.abort(reason);
finish();
const result = await pending.then(() => "sent", (error: unknown) => error);
expect(result).toBe(reason);
expect(go.calls).toEqual([]);
});
}
+206
View File
@@ -0,0 +1,206 @@
/**
* The fetch plugin of MyGo: a `fetch` that makes HTTP requests from Go,
* free of CORS and of the webview's restrictions on headers. It takes the
* standard options and returns a standard `Response`, whose body streams as
* Go reads it. The Go side must use the plugin:
*
* ```go
* mygo.Use(fetch.Plugin) // github.com/egoist/mygo/plugins/fetch
* ```
*
* ```ts
* import { fetch } from "@mygo-plugins/fetch";
*
* const res = await fetch("https://api.example.com/items", {
* headers: { authorization: `Bearer ${token}` },
* });
* const items = await res.json();
* ```
*
* URLs that are not http or https, such as the app's own pages, `data:` and
* `blob:` URLs, go to the webview's `fetch`.
*
* @module
*/
import { Channel, call, isCallError } from "mygo-runtime";
/** What Go streams back: the response's head, then chunks of its body. */
interface Part {
status?: number;
statusText?: string;
url?: string;
redirected?: boolean;
headers?: [string, string][];
/** Base64. */
chunk?: string;
}
/** Statuses whose responses have no body. */
const NULL_BODY = new Set([101, 103, 204, 205, 304]);
/** Methods whose names are normalized to upper case, as `fetch` does. */
const NORMALIZED = new Set(["DELETE", "GET", "HEAD", "OPTIONS", "POST", "PUT"]);
/**
* Makes an HTTP request from Go, with the options and result of the
* standard `fetch`. `mode`, `credentials`, `cache` and the like have no
* meaning there and are ignored; cookies are those of the Go side's
* `http.Client`. Response headers are all there but `Set-Cookie` and `Set-Cookie2`.
*/
export async function fetch(input: RequestInfo | URL, init: RequestInit = {}): Promise<Response> {
const req = typeof Request !== "undefined" && input instanceof Request ? input : null;
const base = typeof location !== "undefined" ? location.href : undefined;
const url = new URL(req ? req.url : input instanceof URL ? input.href : String(input), base);
if (url.protocol !== "http:" && url.protocol !== "https:") return globalThis.fetch(input, init);
if (url.username || url.password) throw new TypeError("fetch: URL must not include credentials");
const signal = init.signal === undefined ? req?.signal ?? null : init.signal;
signal?.throwIfAborted();
let method = init.method ?? req?.method ?? "GET";
if (NORMALIZED.has(method.toUpperCase())) method = method.toUpperCase();
// Plain Headers keep the names a Request would drop, such as Origin.
const headers = new Headers(init.headers ?? req?.headers);
let body: Uint8Array | null = null;
if (init.body != null) {
const r = new Response(init.body);
const type = r.headers.get("content-type");
if (type && !headers.has("content-type")) headers.set("content-type", type);
body = new Uint8Array(await r.arrayBuffer());
} else if (req?.body) {
body = new Uint8Array(await req.arrayBuffer());
}
// Reading the body yields: it may have been aborted before Go sees it.
signal?.throwIfAborted();
if (body && (method === "GET" || method === "HEAD")) {
throw new TypeError(`fetch: a ${method} request cannot have a body`);
}
const parts = new Channel<Part>();
const done = call<void>("plugin:fetch.Fetch", {
url: url.href,
method,
headers: [...headers],
body: body && toBase64(body),
redirect: init.redirect ?? req?.redirect ?? "follow",
}, parts);
// Rejections are taken where they matter; this one must not go unhandled.
const failed = done.then(
() => null,
(err: unknown) => failure(err),
);
const it = parts[Symbol.asyncIterator]();
let stream: ReadableStreamDefaultController<Uint8Array> | undefined;
let rejectHead: ((reason: unknown) => void) | undefined;
const onAbort = () => {
parts.close();
try {
stream?.error(signal!.reason);
} catch {}
rejectHead?.(signal!.reason);
};
signal?.addEventListener("abort", onAbort, { once: true });
const cleanup = () => signal?.removeEventListener("abort", onAbort);
let head: Part;
try {
const first = await new Promise<IteratorResult<Part>>((resolve, reject) => {
rejectHead = reject;
it.next().then(resolve, reject);
});
rejectHead = undefined;
if (first.done) throw (await failed) ?? new TypeError("fetch failed: no response");
head = first.value;
} catch (err) {
cleanup();
parts.close();
throw err;
}
const status = head.status ?? 200;
const nullBody = NULL_BODY.has(status) || method === "HEAD";
const readable = nullBody
? null
: new ReadableStream<Uint8Array>(
{
start(controller) {
stream = controller;
},
async pull(controller) {
const next = await it.next();
if (signal?.aborted) return;
if (!next.done) {
if (next.value.chunk) controller.enqueue(fromBase64(next.value.chunk));
return;
}
cleanup();
const err = await failed;
if (err) controller.error(err);
else controller.close();
},
cancel() {
cleanup();
parts.close();
},
},
{ highWaterMark: 0 },
);
if (nullBody) {
parts.close();
cleanup();
}
// Response takes statuses from 200 to 599 only.
const valid = status >= 200 && status <= 599;
const res = new Response(readable, {
status: valid ? status : 200,
statusText: head.statusText ?? "",
headers: head.headers ?? [],
});
return withMetadata(res, head.url ?? url.href, head.redirected ?? false, status);
}
export default fetch;
/** Native clones copy internal response data, not the properties we add. */
function withMetadata(res: Response, url: string, redirected: boolean, status: number): Response {
// Capture the native method before installing the wrapper to avoid recursion.
const clone = res.clone;
const own = (name: string, value: unknown) => Object.defineProperty(res, name, { value, enumerable: true });
own("url", url);
own("redirected", redirected);
if (res.status !== status) own("status", status);
Object.defineProperty(res, "clone", {
value(this: Response): Response {
return withMetadata(clone.call(this), this.url, this.redirected, this.status);
},
});
return res;
}
/** The error a failed request rejects with. */
function failure(err: unknown): Error {
if (!isCallError(err)) return err instanceof Error ? err : new TypeError(String(err));
if (err.message.includes("plugin is not used")) {
return new Error("@mygo-plugins/fetch: the Go side does not use the plugin: call mygo.Use(fetch.Plugin) before App.Run");
}
return new TypeError(`fetch failed: ${err.message}`, { cause: err });
}
function toBase64(bytes: Uint8Array): string {
const native = (bytes as { toBase64?: () => string }).toBase64;
if (native) return native.call(bytes);
let s = "";
for (let i = 0; i < bytes.length; i += 0x8000) {
s += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000) as unknown as number[]);
}
return btoa(s);
}
function fromBase64(s: string): Uint8Array {
const native = (Uint8Array as { fromBase64?: (s: string) => Uint8Array }).fromBase64;
if (native) return native(s);
const bin = atob(s);
const bytes = new Uint8Array(bin.length);
for (let i = 0; i < bin.length; i++) bytes[i] = bin.charCodeAt(i);
return bytes;
}
+6
View File
@@ -0,0 +1,6 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": { "outDir": "dist", "rootDir": "src" },
"include": ["src"],
"exclude": ["src/**/*.test.ts"]
}