Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/success-json-guard.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@upstash/context7-sdk": patch
---

Convert empty or malformed successful JSON responses into a typed `Context7Error` instead of exposing a native `SyntaxError`. Valid JSON responses and retry behavior are unchanged.
52 changes: 52 additions & 0 deletions packages/sdk/src/http/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,4 +78,56 @@ describe("HttpClient error handling", () => {
expect(error).toBeInstanceOf(Context7Error);
expect(error.message).toBe("Service Unavailable");
});

test("throws Context7Error (not SyntaxError) on empty application/json success body", async () => {
mockFetch(
new Response("", {
status: 200,
headers: { "content-type": "application/json" },
})
);

const error = await newClient()
.request({ path: ["search"] })
.catch((e) => e);

expect(error).toBeInstanceOf(Context7Error);
expect(error).not.toBeInstanceOf(SyntaxError);
expect(error.message).toBe("Failed to parse JSON response from Context7 API");
expect(fetch).toHaveBeenCalledTimes(1);
});

test("throws Context7Error (not SyntaxError) on malformed application/json success body", async () => {
mockFetch(
new Response("{ invalid json }", {
status: 200,
headers: { "content-type": "application/json" },
})
);

const error = await newClient()
.request({ path: ["search"] })
.catch((e) => e);

expect(error).toBeInstanceOf(Context7Error);
expect(error).not.toBeInstanceOf(SyntaxError);
expect(error.message).toBe("Failed to parse JSON response from Context7 API");
expect(fetch).toHaveBeenCalledTimes(1);
});

test("returns parsed result on valid application/json success body", async () => {
mockFetch(
new Response(JSON.stringify({ ok: true, items: [1, 2, 3] }), {
status: 200,
headers: { "content-type": "application/json; charset=utf-8" },
})
);

const response = await newClient().request<{ ok: boolean; items: number[] }>({
path: ["search"],
});

expect(response.result).toEqual({ ok: true, items: [1, 2, 3] });
expect(fetch).toHaveBeenCalledTimes(1);
});
});
7 changes: 6 additions & 1 deletion packages/sdk/src/http/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,12 @@ export class HttpClient implements Requester {
const contentType = res.headers.get("content-type");

if (contentType?.includes("application/json")) {
const body = await res.json();
let body: unknown;
try {
body = await res.json();
} catch {
throw new Context7Error("Failed to parse JSON response from Context7 API");
}
return { result: body as TResult };
} else {
const text = await res.text();
Expand Down