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
15 changes: 15 additions & 0 deletions cli/import/format-jlcpcb-import-choice-title.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import {
type JlcpcbComponentSearchResult,
getJlcpcbComponentDisplayText,
} from "./jlcpcb-component"
import { getJlcpcbPartIdentifier } from "./jlcpcb-part-number"

export const formatJlcpcbImportChoiceTitle = (
comp: Pick<JlcpcbComponentSearchResult, "lcsc" | "mfr" | "description">,
) => {
const detailText = getJlcpcbComponentDisplayText(comp)

return `${getJlcpcbPartIdentifier(comp.lcsc)}${
detailText ? ` - ${detailText}` : ""
}`
}
35 changes: 35 additions & 0 deletions cli/import/jlcpcb-component.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
export type JlcpcbComponentSearchResult = {
lcsc: number | string
mfr?: string | null
package?: string | null
description?: string | null
stock?: number | null
price?: number | null
}

const normalizeDisplayText = (value?: string | null) => value?.trim() ?? ""

const hasSameDisplayText = (left?: string | null, right?: string | null) =>
normalizeDisplayText(left).toLocaleLowerCase() ===
normalizeDisplayText(right).toLocaleLowerCase()

export const getJlcpcbComponentDisplayParts = (
comp: Pick<JlcpcbComponentSearchResult, "mfr" | "description">,
) => {
const manufacturer = normalizeDisplayText(comp.mfr)
const description = normalizeDisplayText(comp.description)

if (
manufacturer &&
description &&
hasSameDisplayText(manufacturer, description)
) {
return [manufacturer]
}

return [manufacturer, description].filter(Boolean)
}

export const getJlcpcbComponentDisplayText = (
comp: Pick<JlcpcbComponentSearchResult, "mfr" | "description">,
) => getJlcpcbComponentDisplayParts(comp).join(" - ")
11 changes: 11 additions & 0 deletions cli/import/jlcpcb-part-number.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const normalizeJlcpcbPartNumber = (partNumber: number | string) =>
String(partNumber)
.trim()
.replace(/^jlcpcb:/i, "")
.replace(/^c/i, "")

export const getJlcpcbPartNumber = (partNumber: number | string) =>
`C${normalizeJlcpcbPartNumber(partNumber)}`

export const getJlcpcbPartIdentifier = (partNumber: number | string) =>
`jlcpcb:${getJlcpcbPartNumber(partNumber)}`
7 changes: 4 additions & 3 deletions cli/import/parse-direct-lcsc-part-number.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { getJlcpcbPartNumber } from "./jlcpcb-part-number"

export const parseDirectLcscPartNumber = (query: string): string | null => {
const normalizedQuery = query.trim().toUpperCase()
const directPartMatch = normalizedQuery.match(/^C?(\d+)$/)
const directPartMatch = query.trim().match(/^(?:jlcpcb:)?c?(\d+)$/i)
if (!directPartMatch) return null
return `C${directPartMatch[1]}`
return getJlcpcbPartNumber(directPartMatch[1])
}
75 changes: 33 additions & 42 deletions cli/import/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,12 @@ import { getRegistryApiKy } from "lib/registry-api/get-ky"
import { addPackage } from "lib/shared/add-package"
import { prompts } from "lib/utils/prompts"
import ora from "ora"
import { formatJlcpcbImportChoiceTitle } from "./format-jlcpcb-import-choice-title"
import type { JlcpcbComponentSearchResult } from "./jlcpcb-component"
import {
getJlcpcbPartIdentifier,
getJlcpcbPartNumber,
} from "./jlcpcb-part-number"
import { parseDirectLcscPartNumber } from "./parse-direct-lcsc-part-number"

export const registerImport = (program: Command) => {
Expand Down Expand Up @@ -38,19 +44,34 @@ export const registerImport = (program: Command) => {
text: "Searching...",
stream: process.stdout,
}).start()
const importJlcpcbPart = async (partNumber: number | string) => {
const normalizedPartNumber = getJlcpcbPartNumber(partNumber)
const partIdentifier = getJlcpcbPartIdentifier(partNumber)
const importSpinner = ora({
text: `Importing "${partIdentifier}" from JLCPCB...`,
stream: process.stdout,
}).start()

try {
const { filePath } = await importComponentFromJlcpcb(
normalizedPartNumber,
process.cwd(),
{ download: opts.download },
)
importSpinner.succeed(kleur.green(`Imported ${filePath}`))
} catch (error) {
importSpinner.fail(kleur.red("Failed to import part"))
console.error(error instanceof Error ? error.message : error)
process.exit(1)
}
}

let registryResults: Array<{
name: string
version: string
description?: string
}> = []
let jlcResults: Array<{
lcsc: number
mfr: string
package: string
description: string
price: number
}> = []
let jlcResults: JlcpcbComponentSearchResult[] = []

if (searchTscircuit) {
try {
Expand Down Expand Up @@ -92,23 +113,8 @@ export const registerImport = (program: Command) => {
? parseDirectLcscPartNumber(query)
: null
if (directLcscPartNumber) {
const importSpinner = ora({
text: `Importing "${directLcscPartNumber}" from JLCPCB...`,
stream: process.stdout,
}).start()
try {
const { filePath } = await importComponentFromJlcpcb(
directLcscPartNumber,
process.cwd(),
{ download: opts.download },
)
importSpinner.succeed(kleur.green(`Imported ${filePath}`))
return
} catch (error) {
importSpinner.fail(kleur.red("Failed to import part"))
console.error(error instanceof Error ? error.message : error)
return process.exit(1)
}
await importJlcpcbPart(directLcscPartNumber)
return
}

console.log(
Expand All @@ -123,7 +129,7 @@ export const registerImport = (program: Command) => {
title: string
value:
| { type: "registry"; name: string }
| { type: "jlcpcb"; part: number }
| { type: "jlcpcb"; part: number | string }
selected?: boolean
}> = []

Expand All @@ -137,7 +143,7 @@ export const registerImport = (program: Command) => {

jlcResults?.forEach((comp, idx) => {
choices.push({
title: `[jlcpcb] ${comp.mfr} (C${comp.lcsc}) - ${comp.description}`,
title: formatJlcpcbImportChoiceTitle(comp),
value: { type: "jlcpcb", part: comp.lcsc },
selected: !choices.length && idx === 0,
})
Expand Down Expand Up @@ -176,22 +182,7 @@ export const registerImport = (program: Command) => {
return process.exit(1)
}
} else {
const importSpinner = ora({
text: `Importing "C${choice.part}" from JLCPCB...`,
stream: process.stdout,
}).start()
try {
const { filePath } = await importComponentFromJlcpcb(
`C${String(choice.part)}`,
process.cwd(),
{ download: opts.download },
)
importSpinner.succeed(kleur.green(`Imported ${filePath}`))
} catch (error) {
importSpinner.fail(kleur.red("Failed to import part"))
console.error(error instanceof Error ? error.message : error)
return process.exit(1)
}
await importJlcpcbPart(choice.part)
}
},
)
Expand Down
22 changes: 22 additions & 0 deletions tests/cli/import/format-jlcpcb-import-choice-title.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { expect, test } from "bun:test"
import { formatJlcpcbImportChoiceTitle } from "cli/import/format-jlcpcb-import-choice-title"

test("formatJlcpcbImportChoiceTitle prefixes JLCPCB identifiers", () => {
expect(
formatJlcpcbImportChoiceTitle({
lcsc: 2040,
mfr: "RP2040",
description: "RP2040",
}),
).toBe("jlcpcb:C2040 - RP2040")
})

test("formatJlcpcbImportChoiceTitle keeps distinct descriptions", () => {
expect(
formatJlcpcbImportChoiceTitle({
lcsc: "C5555",
mfr: "SN74LVC1G00",
description: "Single 2-input NAND gate",
}),
).toBe("jlcpcb:C5555 - SN74LVC1G00 - Single 2-input NAND gate")
})
75 changes: 75 additions & 0 deletions tests/cli/import/import-jlcpcb-prefixed-identifier.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { afterEach, expect, mock, test } from "bun:test"
import { Command } from "commander"

const originalFetch = globalThis.fetch

afterEach(() => {
globalThis.fetch = originalFetch
mock.restore()
})

test("import command accepts jlcpcb-prefixed identifiers", async () => {
const importCalls: Array<{
partNumber: string
projectDir: string
options: { download?: boolean }
}> = []

mock.module("ora", () => ({
default: () => ({
text: "",
start() {
return this
},
stop() {
return this
},
succeed() {
return this
},
fail() {
return this
},
}),
}))

mock.module("lib/import/import-component-from-jlcpcb", () => ({
importComponentFromJlcpcb: async (
partNumber: string,
projectDir: string,
options: { download?: boolean },
) => {
importCalls.push({ partNumber, projectDir, options })
return { filePath: "imports/RP2040.tsx" }
},
}))

globalThis.fetch = (async (input: string | URL | Request) => {
const url = String(input)

expect(url).toContain("https://jlcsearch.tscircuit.com/api/search")
expect(url).toContain("q=jlcpcb%3AC2040")

return new Response(JSON.stringify({ components: [] }), {
headers: {
"Content-Type": "application/json",
},
})
}) as typeof fetch

const { registerImport } = await import("cli/import/register")

const program = new Command()
registerImport(program)

await program.parseAsync(["import", "jlcpcb:C2040"], {
from: "user",
})

expect(importCalls).toHaveLength(1)
expect(importCalls[0]).toEqual({
partNumber: "C2040",
projectDir: process.cwd(),
options: { download: undefined },
})
})
4 changes: 4 additions & 0 deletions tests/cli/import/parse-direct-lcsc-part-number.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,10 @@ test("parseDirectLcscPartNumber returns normalized C-prefixed part for prefixed
expect(parseDirectLcscPartNumber("c14877")).toBe("C14877")
})

test("parseDirectLcscPartNumber accepts jlcpcb-prefixed identifiers", () => {
expect(parseDirectLcscPartNumber("jlcpcb:C14877")).toBe("C14877")
})

test("parseDirectLcscPartNumber returns null for non-part queries", () => {
expect(parseDirectLcscPartNumber("RP2040")).toBe(null)
})
Loading