Skip to content

Commit

Permalink
fix: correct HMR overlay
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Jul 17, 2021
1 parent bd5f1d6 commit a386058
Show file tree
Hide file tree
Showing 8 changed files with 66 additions and 210 deletions.
12 changes: 8 additions & 4 deletions packages/vite-plugin-checker/__tests__/e2e/Sandbox/Sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,11 +93,15 @@ export async function getHmrOverlayText() {
invariant(messageBody, '.message-body is expected in shadow root')
const message = await messageBody.innerText()

const fileLink = await shadowRoot.$('.file-link')
invariant(fileLink, '.file-link is expected in shadow root')
const file = await fileLink.innerText()
const fileDom = await shadowRoot.$('.file-link')
invariant(fileDom, '.file-link is expected in shadow root')
const file = await fileDom.innerText()

return [message, file]
const frameDom = await shadowRoot.$('.frame')
invariant(frameDom, '.frame is expected in shadow root')
const frame = await frameDom.innerText()

return [message, file, frame]
}

export async function viteBuild({
Expand Down
8 changes: 6 additions & 2 deletions packages/vite-plugin-checker/src/checkers/typescript/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,12 @@ import ts from 'typescript'
import { parentPort } from 'worker_threads'

import { Checker, CheckerAbility } from '../../Checker'
import { diagnosticToTerminalLog, diagnosticToViteError, normalizeTsDiagnostic } from '../../logger'
import { ensureCall } from '../../utils'
import {
diagnosticToTerminalLog,
diagnosticToViteError,
ensureCall,
normalizeTsDiagnostic,
} from '../../logger'

import type { CreateDiagnostic } from '../../types'
import type { ErrorPayload } from 'vite'
Expand Down
27 changes: 13 additions & 14 deletions packages/vite-plugin-checker/src/checkers/vls/diagnostics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,17 @@ import {
vscodeUri,
} from 'vite-plugin-checker-vls'
import { PublishDiagnosticsParams } from 'vscode-languageclient/node'

import {
normalizePublishDiagnosticParams,
diagnosticToTerminalLog,
diagnosticToViteError,
normalizeLspDiagnostic,
normalizePublishDiagnosticParams,
} from '../../logger'

import { lspDiagnosticToViteError } from '../../utils'
import { getInitParams } from './initParams'

import type { ErrorPayload } from 'vite'

const { VLS } = vls
const {
createConnection,
Expand Down Expand Up @@ -59,10 +61,7 @@ const logLevel2Severity = {
export interface DiagnosticOptions {
watch: boolean
verbose: boolean
errorCallback?: (
diagnostic: PublishDiagnosticsParams,
viteError: ReturnType<typeof lspDiagnosticToViteError>
) => void
errorCallback?: (diagnostic: PublishDiagnosticsParams, viteError: ErrorPayload['err']) => void
}

export async function diagnostics(
Expand Down Expand Up @@ -151,24 +150,24 @@ async function prepareClientConnection(workspaceUri: vscodeUri.URI, options: Dia
)

// hijack sendDiagnostics
serverConnection.sendDiagnostics = async (diagnostics) => {
serverConnection.sendDiagnostics = async (publishDiagnostics) => {
disposeSuppressConsole?.()
if (diagnostics.version === DOC_VERSION.init) {
if (publishDiagnostics.version === DOC_VERSION.init) {
return
}

if (!diagnostics.diagnostics.length) {
if (!publishDiagnostics.diagnostics.length) {
return
}

const overlayErr = lspDiagnosticToViteError(diagnostics)
if (!overlayErr) return
if (!publishDiagnostics.diagnostics.length) return

const res = await normalizePublishDiagnosticParams(diagnostics)
const res = await normalizePublishDiagnosticParams(publishDiagnostics)
const normalized = diagnosticToViteError(res)
console.log(os.EOL)
console.log(res.map((d) => diagnosticToTerminalLog(d)).join(os.EOL))

options.errorCallback?.(diagnostics, overlayErr)
options.errorCallback?.(publishDiagnostics, normalized)
}

const vls = new VLS(serverConnection as any)
Expand Down
67 changes: 31 additions & 36 deletions packages/vite-plugin-checker/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,13 @@ import { ErrorPayload } from 'vite'

import { codeFrameColumns, SourceLocation } from '@babel/code-frame'

import { lspRange2Location, uriToAbsPath } from './utils'
import type { Range } from 'vscode-languageclient'

import type {
Diagnostic as LspDiagnostic,
URI,
PublishDiagnosticsParams,
} from 'vscode-languageclient/node'

// TODO: remove ./codeFrame.ts and ./utils.ts

import type {
Diagnostic as TsDiagnostic,
flattenDiagnosticMessageText as flattenDiagnosticMessageTextType,
Expand Down Expand Up @@ -75,7 +72,10 @@ export function diagnosticToTerminalLog(d: NormalizedDiagnostic): string {
.join(os.EOL)
}

export function diagnosticToViteError(d: NormalizedDiagnostic): ErrorPayload['err'] {
export function diagnosticToViteError(
diagnostics: NormalizedDiagnostic | NormalizedDiagnostic[]
): ErrorPayload['err'] {
const d = Array.isArray(diagnostics) ? diagnostics[0] : diagnostics
let loc: ErrorPayload['err']['loc']
if (d.loc) {
loc = {
Expand All @@ -86,11 +86,11 @@ export function diagnosticToViteError(d: NormalizedDiagnostic): ErrorPayload['er
}

return {
message: d.message + os.EOL + d.stripedCodeFrame,
message: d.message ?? '',
stack:
typeof d.stack === 'string' ? d.stack : Array.isArray(d.stack) ? d.stack.join(os.EOL) : '',
id: d.id,
frame: d.codeFrame,
frame: d.stripedCodeFrame,
plugin: `vite-plugin-checker(${d.checker})`,
loc,
}
Expand Down Expand Up @@ -165,7 +165,7 @@ export function normalizeTsDiagnostic(d: TsDiagnostic): NormalizedDiagnostic {
}
}

/* ----------------------------------- VLS ---------------------------------- */
/* ----------------------------------- LSP ---------------------------------- */

export function normalizeLspDiagnostic({
diagnostic,
Expand Down Expand Up @@ -223,37 +223,32 @@ export async function normalizePublishDiagnosticParams(
})

return res
}

// const thing = normalizeLspDiagnostic(publishDiagnostics)
// const location = lspRange2Location(d.range)
// const path = publishDiagnostics
// logChunk += `${os.EOL}${chalk.green.bold('FILE ')} ${absFilePath}:${location.start.line}:${
// location.start.column
// }${os.EOL}`

// if (diagnostic.severity === vscodeLanguageserverNode.DiagnosticSeverity.Error) {
// logChunk += `${chalk.red.bold('ERROR ')} ${diagnostic.message.trim()}`
// } else {
// logChunk += `${chalk.yellow.bold('WARN ')} ${diagnostic.message.trim()}`
// }

// logChunk += os.EOL + os.EOL
// logChunk += codeFrameColumns(fileText, location)
// return logChunk

// return {
// message,
// conclusion: '',
// codeFrame,
// stripedCodeFrame: codeFrame && strip(codeFrame),
// id: fileName,
// checker: 'TypeScript',
// loc,
// level: d.category,
// }
// return 1 as any
export function uriToAbsPath(uri: string): string {
return uri.slice('file://'.length)
}

export function lspRange2Location(range: Range): SourceLocation {
return {
start: {
line: range.start.line + 1,
column: range.start.character + 1,
},
end: {
line: range.end.line + 1,
column: range.end.character + 1,
},
}
}

/* --------------------------------- vue-tsc -------------------------------- */

/* --------------------------------- ESLint --------------------------------- */

/* ------------------------------ miscellaneous ----------------------------- */
export function ensureCall(callback: CallableFunction) {
setTimeout(() => {
callback()
})
}
1 change: 0 additions & 1 deletion packages/vite-plugin-checker/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import type {

export * from './types'
export * from './codeFrame'
export * from './utils'
export * from './worker'

const sharedConfigKeys: (keyof SharedConfig)[] = ['enableBuild', 'overlay']
Expand Down
145 changes: 0 additions & 145 deletions packages/vite-plugin-checker/src/utils.ts

This file was deleted.

8 changes: 4 additions & 4 deletions playground/react-ts/__tests__/test.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,19 +46,19 @@ describe('typescript', () => {
it('get initial error and subsequent error', async () => {
await viteServe({ cwd: testDir })
await pollingUntil(getHmrOverlay, (dom) => !!dom)
const [message1, file1] = await getHmrOverlayText()
expect(message1).toContain(snapshot.errorCode1)
const [message1, file1, frame1] = await getHmrOverlayText()
expect(message1).toContain(snapshot.errorMsg)
expect(file1).toContain(snapshot.absPath)
expect(frame1).toContain(snapshot.errorCode1)
expect(stripedLog).toContain(snapshot.errorCode1)
expect(stripedLog).toContain(snapshot.errorMsg)
expect(stripedLog).toContain(snapshot.relativePath)

resetTerminalLog()
editFile('src/App.tsx', (code) => code.replace('useState<string>(1)', 'useState<string>(2)'))
await sleep(2000)
const [message2] = await getHmrOverlayText()
expect(message2).toContain(snapshot.errorCode2)
const [, , frame2] = await getHmrOverlayText()
expect(frame2).toContain(snapshot.errorCode2)
expect(stripedLog).toContain(snapshot.errorCode2)
})

Expand Down
Loading

0 comments on commit a386058

Please sign in to comment.