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
11 changes: 7 additions & 4 deletions cli/import/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,15 @@ export const registerImport = (program: Command) => {
.option("--jlcpcb", "Search JLCPCB components")
.option("--lcsc", "Alias for --jlcpcb")
.option("--tscircuit", "Search tscircuit registry packages")
.option("--download", "Download 3D models locally")
.action(
async (
queryParts: string[],
opts: {
jlcpcb?: boolean
lcsc?: boolean
tscircuit?: boolean
download?: boolean
},
) => {
const query = getQueryFromParts(queryParts)
Expand Down Expand Up @@ -144,13 +146,14 @@ export const registerImport = (program: Command) => {
return process.exit(1)
}
} else {
const partId = `C${choice.part}`
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Unclear naming here, rename part and partId

partNumber is fine. lcscId is better than partId and used elsewhere

const importSpinner = ora(
`Importing "C${choice.part}" from JLCPCB...`,
`Importing "${partId}" from JLCPCB...`,
).start()
try {
const { filePath } = await importComponentFromJlcpcb(
`C${String(choice.part)}`,
)
const { filePath } = await importComponentFromJlcpcb(partId, {
download: opts.download,
})
importSpinner.succeed(kleur.green(`Imported ${filePath}`))
} catch (error) {
importSpinner.fail(kleur.red("Failed to import part"))
Expand Down
96 changes: 90 additions & 6 deletions lib/import/import-component-from-jlcpcb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,103 @@ import { fetchEasyEDAComponent, convertRawEasyToTsx } from "easyeda/browser"
import fs from "node:fs/promises"
import path from "node:path"

export interface ImportOptions {
download?: boolean
projectDir?: string
}

/**
* Imports a component from JLCPCB/EasyEDA, optionally downloading its 3D model.
*/
export const importComponentFromJlcpcb = async (
jlcpcbPartNumber: string,
projectDir: string = process.cwd(),
options: ImportOptions | string = {},
) => {
const projectDir =
typeof options === "string" ? options : options.projectDir || process.cwd()
const shouldDownload =
typeof options === "object" ? Boolean(options.download) : false

const component = await fetchEasyEDAComponent(jlcpcbPartNumber)
const tsx = await convertRawEasyToTsx(component)
const fileName = tsx.match(/export const (\w+) = .*/)?.[1]
let tsxContent = await convertRawEasyToTsx(component)

const componentNameMatch = tsxContent.match(/export const (\w+) = .*/)
const fileName = componentNameMatch?.[1]
if (!fileName) {
throw new Error("Could not determine file name of converted component")
}

const importsDir = path.join(projectDir, "imports")
await fs.mkdir(importsDir, { recursive: true })
const filePath = path.join(importsDir, `${fileName}.tsx`)
await fs.writeFile(filePath, tsx)
const componentDir = path.join(importsDir, fileName)
await fs.mkdir(componentDir, { recursive: true })

if (shouldDownload) {
tsxContent = await downloadAndLocalize3dModel({
tsxContent,
jlcpcbPartNumber,
componentDir,
})
}

const filePath = path.join(componentDir, "index.tsx")
await fs.writeFile(filePath, tsxContent)

return { filePath }
}

/**
* Downloads the 3D model referenced in the TSX and updates the TSX to use a local path.
*/
async function downloadAndLocalize3dModel(params: {
tsxContent: string
jlcpcbPartNumber: string
componentDir: string
}): Promise<string> {
const { tsxContent, jlcpcbPartNumber, componentDir } = params

const objUrlMatch = tsxContent.match(/objUrl: "(https?:\/\/[^"]+)"/)
const modelUrlMatch = tsxContent.match(/modelUrl: "(https?:\/\/[^"]+)"/)
const remoteUrlMatch = objUrlMatch || modelUrlMatch

if (!remoteUrlMatch) {
return tsxContent
}

const remoteUrl = remoteUrlMatch[1]

try {
const response = await fetch(remoteUrl)
Copy link
Contributor

@MustafaMulla29 MustafaMulla29 Mar 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ig you should be using platformFetch instead of fetch

if (!response.ok) {
console.warn(`Failed to download 3D model from ${remoteUrl}`)
return tsxContent
}

const contentDisposition = response.headers.get("content-disposition")
let modelFileName = `${jlcpcbPartNumber}.obj`

if (contentDisposition) {
// Robust extraction of filename from content-disposition
const filenameMatch = contentDisposition.match(
/filename\*?=['"]?([^;'"\n]*)['"]?/i,
)
if (filenameMatch?.[1]) {
modelFileName = path.basename(filenameMatch[1])
}
}

const modelFilePath = path.join(componentDir, modelFileName)
const arrayBuffer = await response.arrayBuffer()
await fs.writeFile(modelFilePath, Buffer.from(arrayBuffer))

// Update TSX to use relative path (safer string replacement)
const localModelPath = `./${modelFileName}`
const urlPattern = objUrlMatch ? "objUrl" : "modelUrl"
const oldUrlLine = remoteUrlMatch[0]
const newUrlLine = `${urlPattern}: "${localModelPath}"`

return tsxContent.replace(oldUrlLine, newUrlLine)
} catch (error) {
console.error("Error downloading 3D model:", error)
return tsxContent
}
}
Loading