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

feat: automatically refresh import types on update #32

Merged
merged 18 commits into from
Jan 30, 2025
Merged
Show file tree
Hide file tree
Changes from 13 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
56 changes: 56 additions & 0 deletions cli/dev/DevServer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import path from "node:path"
import fs from "node:fs"
import type { FileUpdatedEvent } from "lib/file-server/FileServerEvent"
import * as chokidar from "chokidar"
import { installNodeModuleTypesForSnippet } from "lib/dependency-analysis/installNodeModuleTypesForSnippet"
import { findImportsInSnippet } from "lib/dependency-analysis/findImportsInSnippet"

export class DevServer {
port: number
Expand Down Expand Up @@ -77,6 +79,8 @@ export class DevServer {
)

this.upsertInitialFiles()

await this.handleTypeDependencies(this.componentFilePath)
}

async addEntrypoint() {
Expand Down Expand Up @@ -119,6 +123,15 @@ circuit.add(<MyCircuit />)
// because it can be edited by the browser
if (relativeFilePath.includes("manual-edits.json")) return

try {
if (!this.areTypesInstalled(absoluteFilePath)) {
console.log("Types outdated, installing...")
await installNodeModuleTypesForSnippet(absoluteFilePath)
}
} catch (error) {
console.warn("Failed to verify types:", error)
}

console.log(`${relativeFilePath} saved. Applying changes...`)
await this.fsKy
.post("api/files/upsert", {
Expand Down Expand Up @@ -155,4 +168,47 @@ circuit.add(<MyCircuit />)
this.httpServer?.close()
this.eventsWatcher?.stop()
}

private async handleTypeDependencies(absoluteFilePath: string) {
console.log("Checking type dependencies...")
try {
const needsInstallation = !this.areTypesInstalled(absoluteFilePath)
if (needsInstallation) {
console.log("Installing missing types...")
await installNodeModuleTypesForSnippet(absoluteFilePath)
}
} catch (error) {
console.warn("Error handling type dependencies:", error)
}
}

private areTypesInstalled(absoluteFilePath: string): boolean {
const imports = findImportsInSnippet(absoluteFilePath)
return imports.every((imp) => this.checkTypeExists(imp))
}

private checkTypeExists(importPath: string): boolean {
if (!importPath.startsWith("@tsci/")) return true

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

const pathWithoutPrefix = importPath.replace("@tsci/", "")
const [owner, name] = pathWithoutPrefix.split(".")

const typePath = path.join(
projectRoot,
"node_modules",
"@tsci",
`${owner}.${name}`,
"index.d.ts",
)

return fs.existsSync(typePath)
}
}
31 changes: 31 additions & 0 deletions lib/dependency-analysis/findImportsInSnippet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import * as fs from "node:fs"
import * as ts from "typescript"

export function findImportsInSnippet(snippetPath: string): 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)

return imports
}
Loading