Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

automatically install imported snippet types #8

Merged
merged 4 commits into from
Dec 17, 2024
Merged
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
Binary file modified bun.lockb
Binary file not shown.
74 changes: 74 additions & 0 deletions cli/installTypes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import * as fs from "node:fs"
import * as path from "node:path"
import * as ts from "typescript"

interface SnippetApiResponse {
snippet: {
dts: string
}
}

export async function installTypes(snippetPath: string) {
const content = fs.readFileSync(snippetPath, "utf-8")
const sourceFile = ts.createSourceFile(
snippetPath,
content,
ts.ScriptTarget.Latest,
true,
)

const imports: string[] = []

function visit(node: ts.Node) {
if (ts.isImportDeclaration(node)) {
const moduleSpecifier = node.moduleSpecifier
if (moduleSpecifier && ts.isStringLiteral(moduleSpecifier)) {
const importPath = moduleSpecifier.text
if (importPath.startsWith("@tsci/")) {
imports.push(importPath)
}
}
}
ts.forEachChild(node, visit)
}

visit(sourceFile)

let projectRoot = path.dirname(snippetPath)
while (projectRoot !== path.parse(projectRoot).root) {
if (fs.existsSync(path.join(projectRoot, "package.json"))) {
break
}
projectRoot = path.dirname(projectRoot)
}

for (const importPath of imports) {
const [owner, name] = importPath.replace("@tsci/", "").split(".")
try {
const response = await fetch(
`https://registry-api.tscircuit.com/snippets/get?owner_name=${owner}&unscoped_name=${name}`,
)

if (!response.ok) {
console.warn(`Failed to fetch types for ${importPath}`)
continue
}

const data: SnippetApiResponse = await response.json()

if (data.snippet.dts) {
const packageDir = path.join(
projectRoot,
"node_modules",
"@tsci",
`${owner}.${name}`,
)
fs.mkdirSync(packageDir, { recursive: true })

fs.writeFileSync(path.join(packageDir, "index.d.ts"), data.snippet.dts)
}
} catch (error) {
console.warn(`Error fetching types for ${importPath}:`, error)
}
}
}
15 changes: 12 additions & 3 deletions cli/main.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#!/usr/bin/env node
import { Command } from "commander"
import * as path from "path"
import * as path from "node:path"
import * as chokidar from "chokidar"
import * as fs from "fs"
import * as fs from "node:fs"
import { createServer } from "../lib/server/createServer"
import { getLocalFileDependencies } from "../lib/dependency-analysis/getLocalFileDependencies"
import { installTypes } from "./installTypes"

const program = new Command()

Expand All @@ -23,6 +24,14 @@ program
const fileDir = path.dirname(absolutePath)
const port = parseInt(options.port)

try {
console.log("Installing types for imported snippets...")
await installTypes(absolutePath)
console.log("Types installed successfully")
} catch (error) {
console.warn("Failed to install types:", error)
}

// Start the server
await createServer(port)

Expand Down Expand Up @@ -63,7 +72,7 @@ circuit.add(<MyCircuit />)
}

// Get initial dependencies
let dependencies = new Set([absolutePath])
const dependencies = new Set([absolutePath])
try {
const deps = getLocalFileDependencies(absolutePath)
deps.forEach((dep) => dependencies.add(dep))
Expand Down
Loading