Skip to content

Commit 96064f1

Browse files
committed
fix: fallback to load types from builtin twind
1 parent 2901cc3 commit 96064f1

File tree

1 file changed

+43
-3
lines changed

1 file changed

+43
-3
lines changed

src/twind.ts

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
11
import * as path from 'path'
2+
import Module from 'module'
3+
import { fileURLToPath, pathToFileURL } from 'url'
24

35
import type { Logger } from 'typescript-template-language-service-decorator'
46
import type * as TS from 'typescript/lib/tsserverlibrary'
@@ -235,7 +237,7 @@ export class Twind {
235237
return this._state
236238
}
237239

238-
const program = this.info.languageService.getProgram()
240+
let program = this.info.languageService.getProgram()
239241

240242
if (!program) {
241243
return undefined
@@ -263,17 +265,55 @@ export class Twind {
263265
})
264266

265267
// Prefer project twind and fallback to bundled twind
266-
const twindDTSFile = this.info.project
268+
let twindDTSFile = this.info.project
267269
.resolveModuleNames(['twind'], program.getRootFileNames()[0])
268270
.map((moduleName) => moduleName?.resolvedFileName)[0]
269271

270-
const twindDTSSourceFile =
272+
this.logger.log('local twind dts: ' + twindDTSFile)
273+
274+
let twindDTSSourceFile =
271275
(twindDTSFile &&
272276
program.getSourceFiles().find((sourceFile) => sourceFile.fileName == twindDTSFile)) ||
273277
program
274278
.getSourceFiles()
275279
.find((sourceFile) => sourceFile.fileName.endsWith('twind/twind.d.ts'))
276280

281+
// No local twind but a twind.config -> use our twind
282+
if (
283+
!twindDTSFile &&
284+
!twindDTSSourceFile &&
285+
configFile &&
286+
/twind\.config\.\w+$/.test(configFile)
287+
) {
288+
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
289+
// @ts-ignore
290+
const from: string | URL = import.meta.url || pathToFileURL(__filename)
291+
292+
const { resolve } =
293+
Module.createRequire?.(from) || Module.createRequireFromPath(fileURLToPath(from))
294+
295+
try {
296+
twindDTSFile = resolve('twind').replace(/\.\w+$/, '.d.ts')
297+
this.logger.log('builtin twind dts: ' + twindDTSFile)
298+
} catch {
299+
// ignore
300+
}
301+
}
302+
303+
if (twindDTSFile) {
304+
program = this.typescript.createProgram({
305+
rootNames: [...program.getRootFileNames(), twindDTSFile],
306+
options: program.getCompilerOptions(),
307+
// projectReferences?: readonly ProjectReference[];
308+
// host?: program.getCom
309+
oldProgram: program,
310+
})
311+
312+
twindDTSSourceFile = program
313+
.getSourceFiles()
314+
.find((sourceFile) => sourceFile.fileName.endsWith('twind/twind.d.ts'))
315+
}
316+
277317
this.logger.log('twindDTSSourceFile: ' + twindDTSSourceFile?.fileName)
278318

279319
if (twindDTSSourceFile) {

0 commit comments

Comments
 (0)