-
Notifications
You must be signed in to change notification settings - Fork 58
/
Copy pathkit.ts
81 lines (71 loc) · 2.41 KB
/
kit.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { addTemplate, createResolver, logger, tryUseNuxt, useNuxt } from '@nuxt/kit'
import { relative } from 'pathe'
import { resolvePackageJSON } from 'pkg-types'
import { isCI, provider } from 'std-env'
export function extendTypes(module: string, template: (options: { typesPath: string }) => Promise<string> | string) {
const nuxt = useNuxt()
const { resolve } = createResolver(import.meta.url)
const fileName = `${module.replace('/', '-')}.d.ts`
// paths.d.ts
addTemplate({
filename: `modules/${fileName}`,
getContents: async () => {
const typesPath = relative(resolve(nuxt!.options.rootDir, nuxt!.options.buildDir, 'module'), resolve('runtime/types'))
const s = await template({ typesPath })
return `// Generated by ${module}
${s}
export {}
`
},
})
nuxt.hooks.hook('prepare:types', ({ references }) => {
references.push({ path: resolve(nuxt.options.buildDir, `modules/${fileName}`) })
})
}
const isStackblitz = provider === 'stackblitz'
interface EnsurePackageInstalledOptions {
rootDir: string
searchPaths?: string[]
prompt?: boolean
}
async function promptToInstall(name: string, installCommand: () => Promise<void>, options: EnsurePackageInstalledOptions) {
if (await resolvePackageJSON(name).catch(() => null))
return true
logger.info(`Package ${name} is missing`)
if (isCI)
return false
// In StackBlitz we install packages automatically by default
if (options.prompt === true || (options.prompt !== false && !isStackblitz)) {
const confirm = await logger.prompt(`Do you want to install ${name} package?`, {
type: 'confirm',
name: 'confirm',
initial: true,
})
if (!confirm)
return false
}
logger.info(`Installing ${name}...`)
try {
await installCommand()
logger.success(`Installed ${name}`)
return true
}
catch (err) {
logger.error(err)
return false
}
}
// TODO: refactor to Nuxi
const installPrompts = new Set<string>()
export function installNuxtModule(name: string, options?: EnsurePackageInstalledOptions) {
if (installPrompts.has(name))
return
installPrompts.add(name)
const nuxt = tryUseNuxt()
if (!nuxt)
return
return promptToInstall(name, async () => {
const { runCommand } = await import(String('nuxi'))
await runCommand('module', ['add', name, '--cwd', nuxt.options.rootDir])
}, { rootDir: nuxt.options.rootDir, searchPaths: nuxt.options.modulesDir, ...options })
}