Skip to content

Build your personal knowledge base with Trilium Notes

refactor(standalone): extract iOS request interceptors into a module

Elian Doranbb514e1e0db0
diff --git a/apps/standalone/src/ios-interceptors.spec.ts b/apps/standalone/src/ios-interceptors.spec.ts
new file mode 100644
index 0000000000..105a127e42
--- /dev/null
+++ b/apps/standalone/src/ios-interceptors.spec.ts
@@ -0,0 +1,447 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { installIosInterceptors, setupFetchInterceptor, setupImageInterceptor, setupXhrInterceptor } from "./ios-interceptors.js";
+
+const mocks = vi.hoisted(() => ({
+ localFetch: vi.fn(),
+ isLocalApiRequest: vi.fn()
+}));
+
+vi.mock("./local-bridge.js", () => ({
+ localFetch: (req: Request) => mocks.localFetch(req),
+ isLocalApiRequest: (url: URL) => mocks.isLocalApiRequest(url)
+}));
+
+/** Same-origin URL against the happy-dom base (http://localhost:3000 by default). */
+function localUrl(path: string) {
+ return new URL(path, location.href).href;
+}
+
+function makeResponse(body: BodyInit | null, init: ResponseInit = {}) {
+ return new Response(body, { status: 200, statusText: "OK", ...init });
+}
+
+const originalFetch = window.fetch;
+const OriginalXHR = window.XMLHttpRequest;
+
+// setupImageInterceptor installs a permanent MutationObserver on
+// document.documentElement. Across tests those observers would pile up and each
+// react to the same DOM mutations, so capture every observer and disconnect it
+// after the test that created it.
+let observers: MutationObserver[] = [];
+let RealMutationObserver: typeof MutationObserver;
+
+beforeEach(() => {
+ mocks.localFetch.mockReset();
+ mocks.isLocalApiRequest.mockReset();
+ // By default, treat anything under /api/ as a local API request.
+ mocks.isLocalApiRequest.mockImplementation((url: URL) => url.pathname.startsWith("/api/"));
+ mocks.localFetch.mockResolvedValue(makeResponse("{}"));
+ document.body.innerHTML = "";
+ vi.spyOn(console, "warn").mockImplementation(() => {});
+
+ observers = [];
+ RealMutationObserver = window.MutationObserver;
+ window.MutationObserver = class extends RealMutationObserver {
+ constructor(callback: MutationCallback) {
+ super(callback);
+ observers.push(this);
+ }
+ };
+});
+
+afterEach(() => {
+ observers.forEach((o) => o.disconnect());
+ window.MutationObserver = RealMutationObserver;
+ window.fetch = originalFetch;
+ window.XMLHttpRequest = OriginalXHR;
+ vi.restoreAllMocks();
+});
+
+describe("installIosInterceptors", () => {
+ it("installs the fetch, XHR, and image interceptors together", () => {
+ const original = window.fetch;
+ installIosInterceptors();
+ // fetch was replaced
+ expect(window.fetch).not.toBe(original);
+ // XHR was replaced with a subclass
+ expect(window.XMLHttpRequest).not.toBe(OriginalXHR);
+ });
+});
+
+describe("setupFetchInterceptor", () => {
+ let passthrough: ReturnType<typeof vi.fn>;
+
+ beforeEach(() => {
+ passthrough = vi.fn().mockResolvedValue(makeResponse("passthrough"));
+ window.fetch = passthrough as unknown as typeof window.fetch;
+ setupFetchInterceptor();
+ });
+
+ it("routes a local API string URL through localFetch", async () => {
+ const resp = makeResponse("local");
+ mocks.localFetch.mockResolvedValue(resp);
+ const result = await window.fetch("/api/notes");
+ expect(result).toBe(resp);
+ expect(passthrough).not.toHaveBeenCalled();
+ const [req] = mocks.localFetch.mock.calls[0];
+ expect(req).toBeInstanceOf(Request);
+ expect(req.url).toBe(localUrl("/api/notes"));
+ });
+
+ it("routes a URL object input through localFetch", async () => {
+ await window.fetch(new URL(localUrl("/api/tree")));
+ expect(mocks.localFetch).toHaveBeenCalledOnce();
+ expect(passthrough).not.toHaveBeenCalled();
+ });
+
+ it("routes a Request object input through localFetch", async () => {
+ await window.fetch(new Request(localUrl("/api/search")));
+ expect(mocks.localFetch).toHaveBeenCalledOnce();
+ });
+
+ it("passes a same-origin non-API request straight to the original fetch", async () => {
+ const result = await window.fetch("/not-api/page");
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ expect(passthrough).toHaveBeenCalledOnce();
+ expect(await result.text()).toBe("passthrough");
+ });
+
+ it("passes a cross-origin request straight to the original fetch", async () => {
+ await window.fetch("https://example.com/api/notes");
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ expect(passthrough).toHaveBeenCalledOnce();
+ });
+});
+
+describe("setupImageInterceptor", () => {
+ /** Wait until the image's src has been rewritten to a blob: URL. */
+ async function waitForBlobSrc(img: HTMLImageElement) {
+ await vi.waitFor(() => expect(img.getAttribute("src")).toMatch(/^blob:/));
+ }
+
+ beforeEach(() => {
+ // Deterministic blob URL so assertions don't depend on the environment.
+ vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:fake-url");
+ });
+
+ it("swaps an <img> already in the document pointing at a local API path", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("img-bytes"));
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/1");
+ document.body.appendChild(img);
+
+ setupImageInterceptor();
+
+ await waitForBlobSrc(img);
+ expect(mocks.localFetch).toHaveBeenCalledOnce();
+ });
+
+ it("swaps an <img> appended after setup (childList observer)", async () => {
+ setupImageInterceptor();
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/2");
+ document.body.appendChild(img);
+ await waitForBlobSrc(img);
+ });
+
+ it("swaps <img> nested inside an appended container (querySelectorAll path)", async () => {
+ setupImageInterceptor();
+ const container = document.createElement("div");
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/3");
+ container.appendChild(img);
+ document.body.appendChild(container);
+ await waitForBlobSrc(img);
+ });
+
+ it("swaps when the src attribute of an existing image changes to a local API path", async () => {
+ const img = document.createElement("img");
+ img.setAttribute("src", "https://example.com/remote.png");
+ document.body.appendChild(img);
+ setupImageInterceptor();
+
+ img.setAttribute("src", "/api/images/4");
+ await waitForBlobSrc(img);
+ });
+
+ it("ignores blob:, data:, empty, and non-API sources", async () => {
+ for (const src of ["", "data:image/png;base64,AAAA", "blob:existing", "/other/x.png"]) {
+ const img = document.createElement("img");
+ if (src) img.setAttribute("src", src);
+ document.body.appendChild(img);
+ }
+ setupImageInterceptor();
+ // Give the async swap a chance to (not) run.
+ await new Promise((r) => setTimeout(r, 20));
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ });
+
+ it("treats an unparseable src as non-matching without throwing", async () => {
+ const img = document.createElement("img");
+ img.setAttribute("src", "https://exa mple.com/api/x");
+ document.body.appendChild(img);
+ setupImageInterceptor();
+ await new Promise((r) => setTimeout(r, 20));
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ });
+
+ it("leaves the src untouched and allows a retry when the fetch is not ok", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("nope", { status: 404, statusText: "Not Found" }));
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/5");
+ document.body.appendChild(img);
+ setupImageInterceptor();
+
+ await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledOnce());
+ expect(img.getAttribute("src")).toBe("/api/images/5");
+
+ // Because the dedup entry was cleared, the same src can be retried. Bounce
+ // through a non-API src so the attribute genuinely changes value (happy-dom
+ // only fires a mutation on a real change) before returning to the API path.
+ mocks.localFetch.mockResolvedValue(makeResponse("ok-now"));
+ img.setAttribute("src", "/not-api/placeholder.png");
+ img.setAttribute("src", "/api/images/5");
+ await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledTimes(2));
+ });
+
+ it("logs a warning and clears dedup when the fetch throws", async () => {
+ mocks.localFetch.mockRejectedValue(new Error("boom"));
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/6");
+ document.body.appendChild(img);
+ setupImageInterceptor();
+
+ await vi.waitFor(() => expect(console.warn).toHaveBeenCalled());
+ expect(img.getAttribute("src")).toBe("/api/images/6");
+ });
+
+ it("does not re-fetch when the same src is processed twice (dedup)", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("bytes"));
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/7");
+ document.body.appendChild(img);
+ setupImageInterceptor();
+
+ // First pass swaps to the (mocked) blob URL.
+ await waitForBlobSrc(img);
+ expect(mocks.localFetch).toHaveBeenCalledOnce();
+
+ // Point the same element back at the already-processed API path. The
+ // attribute genuinely changes (blob: → /api/…), so the observer fires,
+ // but the dedup WeakMap short-circuits before a second fetch.
+ img.setAttribute("src", "/api/images/7");
+ await new Promise((r) => setTimeout(r, 20));
+ expect(mocks.localFetch).toHaveBeenCalledOnce();
+ });
+
+ it("ignores src mutations on non-image elements", async () => {
+ const span = document.createElement("span");
+ span.setAttribute("src", "/api/images/a");
+ document.body.appendChild(span);
+ setupImageInterceptor();
+
+ span.setAttribute("src", "/api/images/b"); // attributes record whose target is not an <img>
+ await new Promise((r) => setTimeout(r, 20));
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ });
+
+ it("ignores appended non-element nodes", async () => {
+ setupImageInterceptor();
+ document.body.appendChild(document.createComment("comment"));
+ document.body.appendChild(document.createTextNode("text"));
+ await new Promise((r) => setTimeout(r, 20));
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ });
+
+ it("defers observation until DOMContentLoaded when documentElement is not ready", async () => {
+ const realDocEl = document.documentElement;
+ let docEl: HTMLElement | null = null;
+ Object.defineProperty(document, "documentElement", { configurable: true, get: () => docEl });
+
+ setupImageInterceptor(); // documentElement null → registers a DOMContentLoaded listener
+
+ docEl = realDocEl; // restore before the deferred start() observes it
+ const img = document.createElement("img");
+ img.setAttribute("src", "/api/images/8");
+ document.body.appendChild(img);
+ document.dispatchEvent(new Event("DOMContentLoaded"));
+
+ await vi.waitFor(() => expect(mocks.localFetch).toHaveBeenCalledOnce());
+ Object.defineProperty(document, "documentElement", { configurable: true, value: realDocEl });
+ });
+});
+
+describe("setupXhrInterceptor", () => {
+ function openXhr(method: string, url: string) {
+ setupXhrInterceptor();
+ const xhr = new window.XMLHttpRequest();
+ xhr.open(method, url);
+ return xhr;
+ }
+
+ /** Resolve once the intercepted request finishes (load or error). */
+ function done(xhr: XMLHttpRequest) {
+ return new Promise<void>((resolve) => xhr.addEventListener("loadend", () => resolve()));
+ }
+
+ it("routes an intercepted GET through localFetch and exposes the response", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("hello", { headers: { "content-type": "text/plain", "x-foo": "bar" } }));
+ const xhr = openXhr("GET", "/api/notes");
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+
+ expect(xhr.readyState).toBe(4);
+ expect(xhr.status).toBe(200);
+ expect(xhr.statusText).toBe("OK");
+ expect(xhr.responseText).toBe("hello");
+ expect(xhr.response).toBe("hello");
+ expect(xhr.responseURL).toBe(localUrl("/api/notes"));
+ expect(xhr.getResponseHeader("x-foo")).toBe("bar");
+ expect(xhr.getAllResponseHeaders()).toContain("x-foo: bar");
+ });
+
+ it("accepts a URL object as the open() target", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("ok"));
+ setupXhrInterceptor();
+ const xhr = new window.XMLHttpRequest();
+ xhr.open("GET", new URL(localUrl("/api/thing")));
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(xhr.responseURL).toBe(localUrl("/api/thing"));
+ });
+
+ it("parses a JSON responseType", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse(JSON.stringify({ ok: true })));
+ const xhr = openXhr("GET", "/api/tree");
+ xhr.responseType = "json";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(xhr.response).toEqual({ ok: true });
+ });
+
+ it("yields null for an invalid JSON responseType body", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("not json"));
+ const xhr = openXhr("GET", "/api/tree");
+ xhr.responseType = "json";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(xhr.response).toBeNull();
+ });
+
+ it("returns an ArrayBuffer for the arraybuffer responseType", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("abc"));
+ const xhr = openXhr("GET", "/api/blob");
+ xhr.responseType = "arraybuffer";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(xhr.response).toBeInstanceOf(ArrayBuffer);
+ expect(new TextDecoder().decode(xhr.response as ArrayBuffer)).toBe("abc");
+ });
+
+ it("returns a typed Blob for the blob responseType", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("xyz", { headers: { "content-type": "image/png" } }));
+ const xhr = openXhr("GET", "/api/image");
+ xhr.responseType = "blob";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(xhr.response).toBeInstanceOf(Blob);
+ expect((xhr.response as Blob).type).toBe("image/png");
+ });
+
+ it("defaults the Blob type to empty when no content-type is present", async () => {
+ // A null body carries no content-type header (a string body would make
+ // happy-dom synthesize "text/plain"), exercising the `?? ""` fallback.
+ mocks.localFetch.mockResolvedValue(makeResponse(null));
+ const xhr = openXhr("GET", "/api/image");
+ xhr.responseType = "blob";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect((xhr.response as Blob).type).toBe("");
+ });
+
+ it("throws when responseText is read for a non-text responseType", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("{}"));
+ const xhr = openXhr("GET", "/api/tree");
+ xhr.responseType = "json";
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+ expect(() => xhr.responseText).toThrow(/responseText is only available/);
+ });
+
+ it("forwards a request body for a POST and reads the intercept responseType", async () => {
+ mocks.localFetch.mockResolvedValue(makeResponse("created", { status: 201, statusText: "Created" }));
+ const xhr = openXhr("POST", "/api/notes");
+ xhr.setRequestHeader("content-type", "application/json");
+ expect(xhr.responseType).toBe(""); // intercept getter returns the stored value
+ const finished = done(xhr);
+ xhr.send(JSON.stringify({ title: "n" }));
+ await finished;
+
+ expect(xhr.status).toBe(201);
+ const [req] = mocks.localFetch.mock.calls[0];
+ expect(req.method).toBe("POST");
+ expect(await req.text()).toBe(JSON.stringify({ title: "n" }));
+ expect(req.headers.get("content-type")).toBe("application/json");
+ });
+
+ it("dispatches an error when the local fetch fails", async () => {
+ mocks.localFetch.mockRejectedValue(new Error("worker down"));
+ const xhr = openXhr("GET", "/api/notes");
+ const onError = vi.fn();
+ xhr.addEventListener("error", onError);
+ const finished = done(xhr);
+ xhr.send();
+ await finished;
+
+ expect(xhr.status).toBe(0);
+ expect(xhr.readyState).toBe(4);
+ expect(onError).toHaveBeenCalledOnce();
+ });
+
+ it("does not intercept a non-local request and delegates to the native XHR", () => {
+ mocks.isLocalApiRequest.mockReturnValue(false);
+ const openSpy = vi.spyOn(OriginalXHR.prototype, "open").mockImplementation(() => {});
+ const headerSpy = vi.spyOn(OriginalXHR.prototype, "setRequestHeader").mockImplementation(() => {});
+ const sendSpy = vi.spyOn(OriginalXHR.prototype, "send").mockImplementation(() => {});
+
+ setupXhrInterceptor();
+ const xhr = new window.XMLHttpRequest();
+ xhr.open("GET", "https://example.com/api/notes");
+ xhr.setRequestHeader("x-a", "b");
+ xhr.send();
+
+ expect(openSpy).toHaveBeenCalledOnce();
+ expect(headerSpy).toHaveBeenCalledWith("x-a", "b");
+ expect(sendSpy).toHaveBeenCalledOnce();
+ expect(mocks.localFetch).not.toHaveBeenCalled();
+ });
+
+ it("delegates responseType get/set to the native XHR when not intercepting", () => {
+ mocks.isLocalApiRequest.mockReturnValue(false);
+ vi.spyOn(OriginalXHR.prototype, "open").mockImplementation(() => {});
+ const setSpy = vi.fn();
+ const getSpy = vi.fn().mockReturnValue("text");
+ Object.defineProperty(OriginalXHR.prototype, "responseType", {
+ configurable: true,
+ get: getSpy,
+ set: setSpy
+ });
+
+ setupXhrInterceptor();
+ const xhr = new window.XMLHttpRequest();
+ xhr.open("GET", "https://example.com/x");
+ xhr.responseType = "text";
+ expect(setSpy).toHaveBeenCalledWith("text");
+ expect(xhr.responseType).toBe("text");
+ expect(getSpy).toHaveBeenCalled();
+ });
+});
diff --git a/apps/standalone/src/ios-interceptors.ts b/apps/standalone/src/ios-interceptors.ts
new file mode 100644
index 0000000000..547a0c6ee7
--- /dev/null
+++ b/apps/standalone/src/ios-interceptors.ts
@@ -0,0 +1,241 @@
+import { isLocalApiRequest, localFetch } from "./local-bridge.js";
+
+/**
+ * iOS-only request interceptors.
+ *
+ * iOS Capacitor loads the app on the `capacitor://` scheme, and WebKit refuses
+ * to register a service worker for a non-HTTP(S) origin. The standalone stack
+ * normally routes the client's API/sync calls to the in-browser SQLite worker
+ * through that service worker (this is what Android — served on `https://` via
+ * `androidScheme` — and the web build both rely on). Since the SW can't exist
+ * under `capacitor://`, these three interceptors stand in for it, each catching
+ * a request path the SW would otherwise handle:
+ *
+ * - {@link setupFetchInterceptor} — `window.fetch` calls to the local API.
+ * - {@link setupXhrInterceptor} — `XMLHttpRequest` (jQuery `$.ajax`), which
+ * does not go through `window.fetch`.
+ * - {@link setupImageInterceptor} — `<img src="api/images/…">` loads, which
+ * the browser's internal image loader issues
+ * without touching fetch or XHR.
+ *
+ * The caller gates this on `location.protocol === "capacitor:"`, so none of it
+ * runs on Android or the web build.
+ */
+export function installIosInterceptors() {
+ setupFetchInterceptor();
+ setupXhrInterceptor();
+ setupImageInterceptor();
+}
+
+export function setupFetchInterceptor() {
+ const originalFetch = window.fetch.bind(window);
+ window.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
+ const urlStr = typeof input === "string" ? input
+ : input instanceof URL ? input.href
+ : (input as Request).url;
+ const url = new URL(urlStr, location.href);
+ if (url.origin === location.origin && isLocalApiRequest(url)) {
+ return localFetch(new Request(input, init));
+ }
+ return originalFetch(input, init);
+ };
+}
+
+// <img src="api/images/..."> requests are issued by the browser's internal
+// image loader — they don't go through window.fetch or XMLHttpRequest, so the
+// other interceptors can't catch them. On the capacitor:// scheme there is
+// also no Service Worker to fall back on (WebKit only registers SWs for
+// http/https origins), so the request hits Capacitor's URL scheme handler,
+// which has no idea about /api/images/... and silently 404s — that's the
+// broken-image placeholder users see in the iOS app.
+//
+// Watch the DOM for <img> elements whose src points at a local API path and
+// transparently swap the src to a blob: URL backed by the SQLite worker. This
+// catches images added via HTML parsing (initial document, innerHTML), via
+// setAttribute/attr (jQuery, content_renderer), and via the src property.
+// Setting the same src again on the same element is deduplicated so we don't
+// re-fetch on idempotent re-renders.
+export function setupImageInterceptor() {
+ const lastProcessedSrc = new WeakMap<HTMLImageElement, string>();
+
+ function matchesLocalApi(value: string): URL | null {
+ if (!value || value.startsWith("blob:") || value.startsWith("data:")) return null;
+ let abs: URL;
+ try {
+ abs = new URL(value, location.href);
+ } catch {
+ return null;
+ }
+ return (abs.origin === location.origin && isLocalApiRequest(abs)) ? abs : null;
+ }
+
+ async function swapToBlob(img: HTMLImageElement, originalSrc: string, absUrl: URL) {
+ if (lastProcessedSrc.get(img) === originalSrc) return;
+ lastProcessedSrc.set(img, originalSrc);
+
+ try {
+ const resp = await localFetch(new Request(absUrl.toString()));
+ if (!resp.ok) {
+ lastProcessedSrc.delete(img);
+ return;
+ }
+ const blob = await resp.blob();
+ img.setAttribute("src", URL.createObjectURL(blob));
+ } catch (err) {
+ console.warn("[ImageInterceptor] Failed to load", absUrl.href, err);
+ lastProcessedSrc.delete(img);
+ }
+ }
+
+ function checkImage(img: HTMLImageElement) {
+ const src = img.getAttribute("src");
+ if (!src) return;
+ const absUrl = matchesLocalApi(src);
+ if (absUrl) void swapToBlob(img, src, absUrl);
+ }
+
+ const observer = new MutationObserver((records) => {
+ for (const record of records) {
+ if (record.type === "attributes" && record.attributeName === "src" && record.target instanceof HTMLImageElement) {
+ checkImage(record.target);
+ } else if (record.type === "childList") {
+ for (const node of record.addedNodes) {
+ if (node instanceof HTMLImageElement) {
+ checkImage(node);
+ } else if (node instanceof Element) {
+ node.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));
+ }
+ }
+ }
+ }
+ });
+
+ function start() {
+ observer.observe(document.documentElement, {
+ subtree: true,
+ childList: true,
+ attributes: true,
+ attributeFilter: ["src"]
+ });
+ document.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));
+ }
+
+ if (document.documentElement) {
+ start();
+ } else {
+ document.addEventListener("DOMContentLoaded", start, { once: true });
+ }
+}
+
+// jQuery $.ajax uses XMLHttpRequest, which window.fetch interception does not
+// catch. On the capacitor:// scheme there is no Service Worker to route
+// requests, so XHR-bound API calls would hit the native bridge and return
+// something other than the expected JSON. Route them through the local worker.
+export function setupXhrInterceptor() {
+ const OriginalXHR = window.XMLHttpRequest;
+
+ class PatchedXHR extends OriginalXHR {
+ private _ti_method = "GET";
+ private _ti_url = "";
+ private _ti_intercept = false;
+ private _ti_headers: Record<string, string> = {};
+ private _ti_responseType: XMLHttpRequestResponseType = "";
+
+ open(method: string, url: string | URL, async?: boolean, user?: string | null, password?: string | null) {
+ const urlStr = typeof url === "string" ? url : url.href;
+ const abs = new URL(urlStr, location.href);
+ this._ti_method = method;
+ this._ti_url = abs.href;
+ this._ti_intercept = abs.origin === location.origin && isLocalApiRequest(abs);
+ this._ti_headers = {};
+ if (!this._ti_intercept) {
+ return super.open(method, url as string, async ?? true, user ?? null, password ?? null);
+ }
+ }
+
+ setRequestHeader(name: string, value: string) {
+ if (!this._ti_intercept) return super.setRequestHeader(name, value);
+ this._ti_headers[name] = value;
+ }
+
+ get responseType(): XMLHttpRequestResponseType {
+ if (this._ti_intercept) return this._ti_responseType;
+ return super.responseType;
+ }
+
+ set responseType(value: XMLHttpRequestResponseType) {
+ if (this._ti_intercept) {
+ this._ti_responseType = value;
+ return;
+ }
+ super.responseType = value;
+ }
+
+ send(body?: Document | XMLHttpRequestBodyInit | null) {
+ if (!this._ti_intercept) return super.send(body);
+
+ const init: RequestInit = { method: this._ti_method, headers: this._ti_headers };
+ if (body != null && this._ti_method !== "GET" && this._ti_method !== "HEAD") {
+ init.body = body as BodyInit;
+ }
+
+ void (async () => {
+ try {
+ const resp = await localFetch(new Request(this._ti_url, init));
+ const buffer = await resp.arrayBuffer();
+ const text = new TextDecoder().decode(buffer);
+
+ let parsedResponse: unknown = text;
+ if (this._ti_responseType === "json") {
+ try { parsedResponse = JSON.parse(text); } catch { parsedResponse = null; }
+ } else if (this._ti_responseType === "arraybuffer") {
+ parsedResponse = buffer;
+ } else if (this._ti_responseType === "blob") {
+ parsedResponse = new Blob([buffer], { type: resp.headers.get("content-type") ?? "" });
+ }
+
+ const headerLines = [...resp.headers.entries()]
+ .map(([k, v]) => `${k}: ${v}`).join("\r\n");
+
+ Object.defineProperty(this, "readyState", { value: 4, configurable: true });
+ Object.defineProperty(this, "status", { value: resp.status, configurable: true });
+ Object.defineProperty(this, "statusText", { value: resp.statusText, configurable: true });
+ Object.defineProperty(this, "responseURL", { value: this._ti_url, configurable: true });
+ Object.defineProperty(this, "responseText", {
+ get: () => {
+ if (this._ti_responseType && this._ti_responseType !== "text") {
+ throw new DOMException(
+ "responseText is only available when responseType is '' or 'text'",
+ "InvalidStateError"
+ );
+ }
+ return text;
+ },
+ configurable: true,
+ });
+ Object.defineProperty(this, "response", { value: parsedResponse, configurable: true });
+ Object.defineProperty(this, "getAllResponseHeaders", {
+ value: () => headerLines,
+ configurable: true,
+ });
+ Object.defineProperty(this, "getResponseHeader", {
+ value: (name: string) => resp.headers.get(name),
+ configurable: true,
+ });
+
+ this.dispatchEvent(new Event("readystatechange"));
+ this.dispatchEvent(new ProgressEvent("load"));
+ this.dispatchEvent(new ProgressEvent("loadend"));
+ } catch {
+ Object.defineProperty(this, "readyState", { value: 4, configurable: true });
+ Object.defineProperty(this, "status", { value: 0, configurable: true });
+ this.dispatchEvent(new Event("readystatechange"));
+ this.dispatchEvent(new ProgressEvent("error"));
+ this.dispatchEvent(new ProgressEvent("loadend"));
+ }
+ })();
+ }
+ }
+
+ window.XMLHttpRequest = PatchedXHR as unknown as typeof XMLHttpRequest;
+}
diff --git a/apps/standalone/src/main.ts b/apps/standalone/src/main.ts
index 1a757ffd66..3c6c3c0253 100644
--- a/apps/standalone/src/main.ts
+++ b/apps/standalone/src/main.ts
@@ -1,4 +1,5 @@
-import { attachServiceWorkerBridge, startLocalServerWorker, localFetch, isLocalApiRequest, registerNativeHttpHandler } from "./local-bridge.js";
+import { installIosInterceptors } from "./ios-interceptors.js";
+import { attachServiceWorkerBridge, registerNativeHttpHandler, startLocalServerWorker } from "./local-bridge.js";
async function waitForServiceWorkerControl(): Promise<void> {
if (!("serviceWorker" in navigator) || !navigator.serviceWorker) {
@@ -39,220 +40,6 @@ async function waitForServiceWorkerControl(): Promise<void> {
throw new Error("Reloading for service worker activation");
}
-function setupFetchInterceptor() {
- const originalFetch = window.fetch.bind(window);
- window.fetch = (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
- const urlStr = typeof input === "string" ? input
- : input instanceof URL ? input.href
- : (input as Request).url;
- const url = new URL(urlStr, location.href);
- if (url.origin === location.origin && isLocalApiRequest(url)) {
- return localFetch(new Request(input, init));
- }
- return originalFetch(input, init);
- };
-
-}
-
-// <img src="api/images/..."> requests are issued by the browser's internal
-// image loader — they don't go through window.fetch or XMLHttpRequest, so the
-// interceptors above can't catch them. On the capacitor:// scheme there is
-// also no Service Worker to fall back on (WebKit only registers SWs for
-// http/https origins), so the request hits Capacitor's URL scheme handler,
-// which has no idea about /api/images/... and silently 404s — that's the
-// broken-image placeholder users see in the iOS app.
-//
-// Watch the DOM for <img> elements whose src points at a local API path and
-// transparently swap the src to a blob: URL backed by the SQLite worker. This
-// catches images added via HTML parsing (initial document, innerHTML), via
-// setAttribute/attr (jQuery, content_renderer), and via the src property.
-// Setting the same src again on the same element is deduplicated so we don't
-// re-fetch on idempotent re-renders.
-function setupImageInterceptor() {
- const lastProcessedSrc = new WeakMap<HTMLImageElement, string>();
-
- function matchesLocalApi(value: string): URL | null {
- if (!value || value.startsWith("blob:") || value.startsWith("data:")) return null;
- let abs: URL;
- try {
- abs = new URL(value, location.href);
- } catch {
- return null;
- }
- return (abs.origin === location.origin && isLocalApiRequest(abs)) ? abs : null;
- }
-
- async function swapToBlob(img: HTMLImageElement, originalSrc: string, absUrl: URL) {
- if (lastProcessedSrc.get(img) === originalSrc) return;
- lastProcessedSrc.set(img, originalSrc);
-
- try {
- const resp = await localFetch(new Request(absUrl.toString()));
- if (!resp.ok) {
- lastProcessedSrc.delete(img);
- return;
- }
- const blob = await resp.blob();
- img.setAttribute("src", URL.createObjectURL(blob));
- } catch (err) {
- console.warn("[ImageInterceptor] Failed to load", absUrl.href, err);
- lastProcessedSrc.delete(img);
- }
- }
-
- function checkImage(img: HTMLImageElement) {
- const src = img.getAttribute("src");
- if (!src) return;
- const absUrl = matchesLocalApi(src);
- if (absUrl) swapToBlob(img, src, absUrl);
- }
-
- const observer = new MutationObserver((records) => {
- for (const record of records) {
- if (record.type === "attributes" && record.attributeName === "src" && record.target instanceof HTMLImageElement) {
- checkImage(record.target);
- } else if (record.type === "childList") {
- for (const node of record.addedNodes) {
- if (node instanceof HTMLImageElement) {
- checkImage(node);
- } else if (node instanceof Element) {
- node.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));
- }
- }
- }
- }
- });
-
- function start() {
- observer.observe(document.documentElement, {
- subtree: true,
- childList: true,
- attributes: true,
- attributeFilter: ["src"]
- });
- document.querySelectorAll("img").forEach((img) => checkImage(img as HTMLImageElement));
- }
-
- if (document.documentElement) {
- start();
- } else {
- document.addEventListener("DOMContentLoaded", start, { once: true });
- }
-}
-
-// jQuery $.ajax uses XMLHttpRequest, which window.fetch interception does not
-// catch. On the capacitor:// scheme there is no Service Worker to route
-// requests, so XHR-bound API calls would hit the native bridge and return
-// something other than the expected JSON. Route them through the local worker.
-function setupXhrInterceptor() {
- const OriginalXHR = window.XMLHttpRequest;
-
- class PatchedXHR extends OriginalXHR {
- private _ti_method = "GET";
- private _ti_url = "";
- private _ti_intercept = false;
- private _ti_headers: Record<string, string> = {};
- private _ti_responseType: XMLHttpRequestResponseType = "";
-
- open(method: string, url: string | URL, async?: boolean, user?: string | null, password?: string | null) {
- const urlStr = typeof url === "string" ? url : url.href;
- const abs = new URL(urlStr, location.href);
- this._ti_method = method;
- this._ti_url = abs.href;
- this._ti_intercept = abs.origin === location.origin && isLocalApiRequest(abs);
- this._ti_headers = {};
- if (!this._ti_intercept) {
- return super.open(method, url as string, async ?? true, user ?? null, password ?? null);
- }
- }
-
- setRequestHeader(name: string, value: string) {
- if (!this._ti_intercept) return super.setRequestHeader(name, value);
- this._ti_headers[name] = value;
- }
-
- get responseType(): XMLHttpRequestResponseType {
- if (this._ti_intercept) return this._ti_responseType;
- return super.responseType;
- }
-
- set responseType(value: XMLHttpRequestResponseType) {
- if (this._ti_intercept) {
- this._ti_responseType = value;
- return;
- }
- super.responseType = value;
- }
-
- send(body?: Document | XMLHttpRequestBodyInit | null) {
- if (!this._ti_intercept) return super.send(body as any);
-
- const init: RequestInit = { method: this._ti_method, headers: this._ti_headers };
- if (body != null && this._ti_method !== "GET" && this._ti_method !== "HEAD") {
- init.body = body as BodyInit;
- }
-
- (async () => {
- try {
- const resp = await localFetch(new Request(this._ti_url, init));
- const buffer = await resp.arrayBuffer();
- const text = new TextDecoder().decode(buffer);
-
- let parsedResponse: unknown = text;
- if (this._ti_responseType === "json") {
- try { parsedResponse = JSON.parse(text); } catch { parsedResponse = null; }
- } else if (this._ti_responseType === "arraybuffer") {
- parsedResponse = buffer;
- } else if (this._ti_responseType === "blob") {
- parsedResponse = new Blob([buffer], { type: resp.headers.get("content-type") ?? "" });
- }
-
- const headerLines = [...resp.headers.entries()]
- .map(([k, v]) => `${k}: ${v}`).join("\r\n");
-
- Object.defineProperty(this, "readyState", { value: 4, configurable: true });
- Object.defineProperty(this, "status", { value: resp.status, configurable: true });
- Object.defineProperty(this, "statusText", { value: resp.statusText, configurable: true });
- Object.defineProperty(this, "responseURL", { value: this._ti_url, configurable: true });
- Object.defineProperty(this, "responseText", {
- get: () => {
- if (this._ti_responseType && this._ti_responseType !== "text") {
- throw new DOMException(
- "responseText is only available when responseType is '' or 'text'",
- "InvalidStateError"
- );
- }
- return text;
- },
- configurable: true,
- });
- Object.defineProperty(this, "response", { value: parsedResponse, configurable: true });
- Object.defineProperty(this, "getAllResponseHeaders", {
- value: () => headerLines,
- configurable: true,
- });
- Object.defineProperty(this, "getResponseHeader", {
- value: (name: string) => resp.headers.get(name),
- configurable: true,
- });
-
- this.dispatchEvent(new Event("readystatechange"));
- this.dispatchEvent(new ProgressEvent("load"));
- this.dispatchEvent(new ProgressEvent("loadend"));
- } catch (err) {
- Object.defineProperty(this, "readyState", { value: 4, configurable: true });
- Object.defineProperty(this, "status", { value: 0, configurable: true });
- this.dispatchEvent(new Event("readystatechange"));
- this.dispatchEvent(new ProgressEvent("error"));
- this.dispatchEvent(new ProgressEvent("loadend"));
- }
- })();
- }
- }
-
- window.XMLHttpRequest = PatchedXHR as unknown as typeof XMLHttpRequest;
-}
-
async function bootstrap() {
/* fixes https://github.com/webpack/webpack/issues/10035 */
window.global = globalThis;
@@ -268,15 +55,12 @@ async function bootstrap() {
// 1) Start local worker ASAP (so /bootstrap is fast)
startLocalServerWorker();
- // iOS Capacitor loads on capacitor:// scheme — WebKit rejects service worker
- // registration for non-HTTP/HTTPS origins. Use a fetch interceptor instead
- // to route API calls directly to the local SQLite worker. XHR must also be
- // patched because jQuery $.ajax (used by the client's server helpers) does
- // not go through window.fetch.
+ // iOS Capacitor loads on the capacitor:// scheme, where WebKit rejects
+ // service worker registration. Fall back to in-page request interceptors
+ // that route API calls straight to the local SQLite worker; everywhere
+ // else (Android https, web) the service worker handles this.
if (location.protocol === "capacitor:") {
- setupFetchInterceptor();
- setupXhrInterceptor();
- setupImageInterceptor();
+ installIosInterceptors();
} else {
attachServiceWorkerBridge();
await waitForServiceWorkerControl();