Skip to content
This repository has been archived by the owner on Apr 6, 2023. It is now read-only.

refactor: enable strict type checking everywhere #6943

Merged
merged 9 commits into from
Aug 26, 2022
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
2 changes: 1 addition & 1 deletion docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
"pathe": "^0.3.5",
"rimraf": "^3.0.2",
"scule": "^0.3.2",
"untyped": "^0.4.5",
"untyped": "^0.4.7",
"vue-mq": "^1.0.1",
"vue-plausible": "^1.3.2"
},
Expand Down
2 changes: 1 addition & 1 deletion packages/kit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
"semver": "^7.3.7",
"unctx": "^2.0.1",
"unimport": "^0.6.7",
"untyped": "^0.4.5"
"untyped": "^0.4.7"
},
"devDependencies": {
"@types/lodash.template": "^4",
Expand Down
11 changes: 0 additions & 11 deletions packages/kit/tsconfig.json

This file was deleted.

1 change: 1 addition & 0 deletions packages/nuxi/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
"@nuxt/kit": "3.0.0-rc.8",
"@nuxt/schema": "3.0.0-rc.8",
"@types/clear": "^0",
"@types/flat": "^5.0.2",
"@types/mri": "^1.1.1",
"@types/semver": "^7",
"c12": "^0.2.9",
Expand Down
11 changes: 6 additions & 5 deletions packages/nuxi/src/commands/dev.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { AddressInfo } from 'node:net'
import { RequestListener } from 'node:http'
import { resolve, relative, normalize } from 'pathe'
import chokidar from 'chokidar'
import { debounce } from 'perfect-debounce'
Expand All @@ -24,15 +25,15 @@ export default defineNuxtCommand({
overrideEnv('development')

const { listen } = await import('listhen')
let currentHandler
let currentHandler: RequestListener | undefined
let loadingMessage = 'Nuxt is starting...'
const loadingHandler = async (_req, res) => {
const loadingHandler: RequestListener = async (_req, res) => {
const { loading: loadingTemplate } = await importModule('@nuxt/ui-templates')
res.setHeader('Content-Type', 'text/html; charset=UTF-8')
res.statusCode = 503 // Service Unavailable
res.end(loadingTemplate({ loading: loadingMessage }))
}
const serverHandler = (req, res) => {
const serverHandler: RequestListener = (req, res) => {
return currentHandler ? currentHandler(req, res) : loadingHandler(req, res)
}

Expand Down Expand Up @@ -64,7 +65,7 @@ export default defineNuxtCommand({
const load = async (isRestart: boolean, reason?: string) => {
try {
loadingMessage = `${reason ? reason + '. ' : ''}${isRestart ? 'Restarting' : 'Starting'} nuxt...`
currentHandler = null
currentHandler = undefined
if (isRestart) {
consola.info(loadingMessage)
}
Expand Down Expand Up @@ -103,7 +104,7 @@ export default defineNuxtCommand({
}
} catch (err) {
consola.error(`Cannot ${isRestart ? 'restart' : 'start'} nuxt: `, err)
currentHandler = null
currentHandler = undefined
loadingMessage = 'Error while loading nuxt. Please check console and fix errors.'
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxi/src/commands/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { Argv } from 'mri'

const _rDefault = r => r.default || r
const _rDefault = (r: any) => r.default || r

export const commands = {
dev: () => import('./dev').then(_rDefault),
Expand Down
23 changes: 13 additions & 10 deletions packages/nuxi/src/commands/info.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import jiti from 'jiti'
import destr from 'destr'
import { splitByCase } from 'scule'
import clipboardy from 'clipboardy'
import { NuxtModule } from '@nuxt/schema'
import { getPackageManager, getPackageManagerVersion } from '../utils/packageManagers'
import { findup } from '../utils/fs'
import { defineNuxtCommand } from './index'
Expand All @@ -27,13 +28,13 @@ export default defineNuxtCommand({
const { dependencies = {}, devDependencies = {} } = findPackage(rootDir)

// Utils to query a dependency version
const getDepVersion = name => getPkg(name, rootDir)?.version || dependencies[name] || devDependencies[name]
const getDepVersion = (name: string) => getPkg(name, rootDir)?.version || dependencies[name] || devDependencies[name]

const listModules = (arr = []) => arr
.map(normalizeConfigModule)
.map(m => normalizeConfigModule(m, rootDir))
.filter(Boolean)
.map((name) => {
const npmName = name.split('/').splice(0, 2).join('/') // @foo/bar/baz => @foo/bar
const npmName = name!.split('/').splice(0, 2).join('/') // @foo/bar/baz => @foo/bar
const v = getDepVersion(npmName)
return '`' + (v ? `${name}@${v}` : name) + '`'
})
Expand All @@ -54,6 +55,7 @@ export default defineNuxtCommand({
if (packageManager) {
packageManager += '@' + getPackageManagerVersion(packageManager)
} else {
// @ts-expect-error
packageManager = 'unknown'
}

Expand Down Expand Up @@ -95,14 +97,14 @@ export default defineNuxtCommand({
}
})

function normalizeConfigModule (module, rootDir) {
function normalizeConfigModule (module: NuxtModule | string | null | undefined, rootDir: string): string | null {
if (!module) {
return null
}
if (typeof module === 'string') {
return module
.split(rootDir).pop() // Strip rootDir
.split('node_modules').pop() // Strip node_modules
.split(rootDir).pop()! // Strip rootDir
.split('node_modules').pop()! // Strip node_modules
.replace(/^\//, '')
}
if (typeof module === 'function') {
Expand All @@ -111,9 +113,10 @@ function normalizeConfigModule (module, rootDir) {
if (Array.isArray(module)) {
return normalizeConfigModule(module[0], rootDir)
}
return null
}

function getNuxtConfig (rootDir) {
function getNuxtConfig (rootDir: string) {
try {
return jiti(rootDir, { interopDefault: true, esmResolve: true })('./nuxt.config')
} catch (err) {
Expand All @@ -122,7 +125,7 @@ function getNuxtConfig (rootDir) {
}
}

function getPkg (name, rootDir) {
function getPkg (name: string, rootDir: string) {
// Assume it is in {rootDir}/node_modules/${name}/package.json
let pkgPath = resolve(rootDir, 'node_modules', name, 'package.json')

Expand All @@ -135,7 +138,7 @@ function getPkg (name, rootDir) {
return readJSONSync(pkgPath)
}

function findPackage (rootDir) {
function findPackage (rootDir: string) {
return findup(rootDir, (dir) => {
const p = resolve(dir, 'package.json')
if (existsSync(p)) {
Expand All @@ -144,7 +147,7 @@ function findPackage (rootDir) {
}) || {}
}

function readJSONSync (filePath) {
function readJSONSync (filePath: string) {
try {
return destr(readFileSync(filePath, 'utf-8'))
} catch (err) {
Expand Down
13 changes: 7 additions & 6 deletions packages/nuxi/src/commands/init.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { existsSync, readdirSync } from 'node:fs'
// @ts-expect-error missing types
import createTiged from 'tiged'
import { relative, resolve } from 'pathe'
import superb from 'superb'
import consola from 'consola'
import { defineNuxtCommand } from './index'

const rpath = p => relative(process.cwd(), p)
const rpath = (p: string) => relative(process.cwd(), p)

const resolveTemplate = (template) => {
const resolveTemplate = (template: string | boolean) => {
if (typeof template === 'boolean') {
consola.error('Please specify a template!')
process.exit(1)
Expand Down Expand Up @@ -39,12 +40,12 @@ export default defineNuxtCommand({
consola.error(`Directory ${dstDir} is not empty. Please pick another name or remove it first. Aborting.`)
process.exit(1)
}
const formatArgs = msg => msg.replace('options.', '--')
tiged.on('warn', event => consola.warn(formatArgs(event.message)))
tiged.on('info', event => consola.info(formatArgs(event.message)))
const formatArgs = (msg: string) => msg.replace('options.', '--')
tiged.on('warn', (event: any) => consola.warn(formatArgs(event.message)))
tiged.on('info', (event: any) => consola.info(formatArgs(event.message)))
try {
await tiged.clone(dstDir)
} catch (e) {
} catch (e: any) {
if (e.toString().includes('could not find commit hash')) {
consola.error(`Failed to clone template from \`${src}\`. Please check the repo is valid and that you have installed \`git\` correctly.`)
process.exit(1)
Expand Down
6 changes: 3 additions & 3 deletions packages/nuxi/src/utils/cjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import { pathToFileURL } from 'node:url'
import { normalize, dirname } from 'pathe'

export function getModulePaths (paths?: string | string[]): string[] {
return [].concat(
return [
// @ts-ignore
global.__NUXT_PREPATHS__,
...(Array.isArray(paths) ? paths : [paths]),
...(paths ? [] : Array.isArray(paths) ? paths : [paths]),
process.cwd(),
// @ts-ignore
global.__NUXT_PATHS__
).filter(Boolean)
].filter(Boolean)
}

const _require = createRequire(process.cwd())
Expand Down
20 changes: 10 additions & 10 deletions packages/nuxi/src/utils/diff.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,19 @@ import flatten from 'flat'
import { detailedDiff } from 'deep-object-diff'
import { green, red, blue, cyan } from 'colorette'

function normalizeDiff (diffObj, type, ignore) {
return Object.entries(flatten(diffObj))
function normalizeDiff (diffObj: any, type: 'added' | 'deleted' | 'updated', ignore: string[]) {
return Object.entries(flatten(diffObj) as Record<string, any>)
.map(([key, value]) => ({ key, value, type }))
.filter(item => !ignore.includes(item.key) && typeof item.value !== 'function')
}

export function diff (a, b, ignore) {
export function diff (a: any, b: any, ignore: string[]) {
const _diff: any = detailedDiff(a, b)
return [].concat(
normalizeDiff(_diff.added, 'added', ignore),
normalizeDiff(_diff.deleted, 'deleted', ignore),
normalizeDiff(_diff.updated, 'updated', ignore)
)
return [
...normalizeDiff(_diff.added, 'added', ignore),
...normalizeDiff(_diff.deleted, 'deleted', ignore),
...normalizeDiff(_diff.updated, 'updated', ignore)
]
}

const typeMap = {
Expand All @@ -23,9 +23,9 @@ const typeMap = {
updated: blue('updated')
}

export function printDiff (diff) {
export function printDiff (diff: any) {
for (const item of diff) {
console.log(' ', typeMap[item.type] || item.type, cyan(item.key), item.value ? `~> ${cyan(item.value)}` : '')
console.log(' ', typeMap[item.type as keyof typeof typeMap] || item.type, cyan(item.key), item.value ? `~> ${cyan(item.value)}` : '')
}
console.log()
}
16 changes: 10 additions & 6 deletions packages/nuxi/src/utils/help.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { cyan, magenta } from 'colorette'
export function showHelp (meta?) {
import { NuxtCommandMeta } from '../commands'

export function showHelp (meta?: Partial<NuxtCommandMeta>) {
const sections: string[] = []

if (meta.usage) {
sections.push(magenta('> ') + 'Usage: ' + cyan(meta.usage))
}
if (meta) {
if (meta.usage) {
sections.push(magenta('> ') + 'Usage: ' + cyan(meta.usage))
}

if (meta.description) {
sections.push(magenta('⋮ ') + meta.description)
if (meta.description) {
sections.push(magenta('⋮ ') + meta.description)
}
}

sections.push(`Use ${cyan('npx nuxi [command] --help')} to see help for each command`)
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxi/src/utils/kit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { importModule } from './cjs'
export const loadKit = async (rootDir: string): Promise<typeof import('@nuxt/kit')> => {
try {
return await importModule('@nuxt/kit', rootDir) as typeof import('@nuxt/kit')
} catch (e) {
} catch (e: any) {
if (e.toString().includes("Cannot find module '@nuxt/kit'")) {
throw new Error('nuxi requires `@nuxt/kit` to be installed in your project. Try installing `nuxt3` or `@nuxt/bridge` first.')
}
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxi/src/utils/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type { Nuxt } from '@nuxt/schema'
import { rmRecursive } from './fs'

export interface NuxtProjectManifest {
_hash: string
_hash: string | null
project: {
rootDir: string
},
Expand Down
7 changes: 5 additions & 2 deletions packages/nuxi/src/utils/packageManagers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,17 @@ export const packageManagerLocks = {
pnpm: 'pnpm-lock.yaml'
}

type PackageManager = keyof typeof packageManagerLocks

export function getPackageManager (rootDir: string) {
return findup(rootDir, (dir) => {
for (const name in packageManagerLocks) {
if (existsSync(resolve(dir, packageManagerLocks[name]))) {
const path = packageManagerLocks[name as PackageManager]
if (path && existsSync(resolve(dir, path))) {
return name
}
}
})
}) as PackageManager | null
}

export function getPackageManagerVersion (name: string) {
Expand Down
3 changes: 2 additions & 1 deletion packages/nuxi/src/utils/prepare.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export const writeTypes = async (nuxt: Nuxt) => {
]
})

const aliases = {
const aliases: Record<string, string> = {
...nuxt.options.alias,
'#build': nuxt.options.buildDir
}
Expand All @@ -48,6 +48,7 @@ export const writeTypes = async (nuxt: Nuxt) => {
: aliases[alias]

const stats = await fsp.stat(resolve(nuxt.options.rootDir, relativePath)).catch(() => null /* file does not exist */)
tsConfig.compilerOptions = tsConfig.compilerOptions || {}
if (stats?.isDirectory()) {
tsConfig.compilerOptions.paths[alias] = [relativePath]
tsConfig.compilerOptions.paths[`${alias}/*`] = [`${relativePath}/*`]
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@
"unenv": "^0.6.1",
"unimport": "^0.6.7",
"unplugin": "^0.9.2",
"untyped": "^0.4.5",
"untyped": "^0.4.7",
"vue": "^3.2.37",
"vue-bundle-renderer": "^0.4.2",
"vue-devtools-stub": "^0.1.0",
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/app/composables/asyncData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ export function useAsyncData<
result = options.transform(result)
}
if (options.pick) {
result = pick(result, options.pick) as DataT
result = pick(result as any, options.pick) as DataT
}
asyncData.data.value = result
asyncData.error.value = null
Expand Down
2 changes: 1 addition & 1 deletion packages/nuxt/src/app/nuxt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ export function normalizePlugins (_plugins: Plugin[]) {
return plugins as Plugin[]
}

export function defineNuxtPlugin<T> (plugin: Plugin<T>) {
export function defineNuxtPlugin<T extends Record<string, any>> (plugin: Plugin<T>) {
plugin[NuxtPluginIndicator] = true
return plugin
}
Expand Down
11 changes: 0 additions & 11 deletions packages/nuxt/tsconfig.json

This file was deleted.

3 changes: 2 additions & 1 deletion packages/schema/build.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ export default defineBuildConfig({
'ignore',
// Implicit
'@vue/compiler-core',
'@vue/shared'
'@vue/shared',
'untyped'
]
})
Loading