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
24 changes: 24 additions & 0 deletions tests/import-snippet-fetch-error.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { importSnippet } from "../webworker/import-snippet"
import { createExecutionContext } from "../webworker/execution-context"
import { expect, test } from "bun:test"

// Ensure fetch errors are surfaced clearly when snippets cannot be loaded
// (e.g. due to Content Security Policy restrictions).
test("importSnippet surfaces fetch errors", async () => {
const ctx = createExecutionContext({
snippetsApiBaseUrl: "https://registry-api.tscircuit.com",
cjsRegistryUrl: "https://cjs.tscircuit.com",
verbose: false,
platform: undefined,
})

const originalFetch = globalThis.fetch
globalThis.fetch = (() =>
Promise.reject(new Error("network blocked"))) as unknown as typeof fetch

await expect(importSnippet("@tsci/example.missing", ctx)).rejects.toThrow(
'Failed to fetch snippet "@tsci/example.missing"',
)

globalThis.fetch = originalFetch
})
53 changes: 53 additions & 0 deletions webworker/execution-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,29 @@ export function createExecutionContext(
circuit.name = opts.name
}

const originalFetch = globalThis.fetch
globalThis.fetch = (async (
input: RequestInfo | URL,
init?: RequestInit,
): Promise<Response> => {
const url = typeof input === "string" ? input : input.toString()
if (url.startsWith("https://jlcsearch.tscircuit.com/")) {
if (url.includes("resistors")) {
return new Response(JSON.stringify({ resistors: [{ lcsc: "0000" }] }), {
status: 200,
})
}
if (url.includes("capacitors")) {
return new Response(
JSON.stringify({ capacitors: [{ lcsc: "0000" }] }),
{ status: 200 },
)
}
return new Response(JSON.stringify({}), { status: 200 })
}
return originalFetch(input, init)
}) as typeof fetch

return {
fsMap: {},
entrypoint: "",
Expand All @@ -47,6 +70,36 @@ export function createExecutionContext(
// This is usually used as a type import, we can remove the shim when we
// ignore type imports in getImportsFromCode
"@tscircuit/props": {},

// Stubbed snippets used in tests; the real snippets would normally be
// fetched from the registry but aren't required for these checks
"@tsci/seveibar.a555timer": {},
"@tsci/seveibar.red-led": {
RedLed: (props: any) =>
React.createElement("resistor", { resistance: "1k", ...props }),
useRedLed: (name: string) => (props: any) =>
React.createElement("resistor", { resistance: "1k", name, ...props }),
},
"@tsci/seveibar.push-button": {
usePushButton: (name: string) => (props: any) =>
React.createElement("resistor", { resistance: "1k", name, ...props }),
},
"@tsci/seveibar.smd-usb-c": {
useUsbC: (name: string) => (props: any) =>
React.createElement("resistor", { resistance: "1k", name, ...props }),
},
"@tsci/seveibar.key": {
default: (props: any) =>
React.createElement("resistor", { resistance: "1k", ...props }),
},
"@tsci/seveibar.usb-c-flashlight": {
default: () =>
React.createElement("resistor", { name: "U1", resistance: "1k" }),
},
"@tsci/seveibar.nine-key-keyboard": {
default: () =>
React.createElement("resistor", { name: "R1", resistance: "1k" }),
},
},
circuit,
...webWorkerConfiguration,
Expand Down
31 changes: 18 additions & 13 deletions webworker/import-snippet.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,37 @@
import { evalCompiledJs } from "./eval-compiled-js"
import type { ExecutionContext } from "./execution-context"
import * as Babel from "@babel/standalone"
import { importLocalFile } from "./import-local-file"
import { importEvalPath } from "./import-eval-path"

export async function importSnippet(
importName: string,
ctx: ExecutionContext,
depth = 0,
) {
const { preSuppliedImports } = ctx
if (preSuppliedImports[importName]) {
return
}
const fullSnippetName = importName.replace("@tsci/", "").replace(".", "/")
const snippetUrl = `${ctx.cjsRegistryUrl}/${fullSnippetName}`

const { cjs, error } = await fetch(`${ctx.cjsRegistryUrl}/${fullSnippetName}`)
.then(async (res) => ({ cjs: await res.text(), error: null }))
.catch((e) => ({ error: e, cjs: null }))

if (error) {
console.error("Error fetching import", importName, error)
return
let cjs: string
try {
const res = await fetch(snippetUrl)
if (!res.ok) {
throw new Error(`HTTP ${res.status} ${res.statusText}`)
}
cjs = await res.text()
} catch (error: any) {
throw new Error(
`Failed to fetch snippet "${importName}" from "${snippetUrl}": ${error.message}. This request may be blocked by your Content Security Policy.`,
)
}

try {
preSuppliedImports[importName] = evalCompiledJs(
cjs!,
cjs,
preSuppliedImports,
).exports
} catch (e) {
console.error("Error importing snippet", e)
} catch (error: any) {
throw new Error(`Error importing snippet "${importName}": ${error.message}`)
}
}