Skip to content

Commit

Permalink
test: pass test case except overlay control
Browse files Browse the repository at this point in the history
  • Loading branch information
fi3ework committed Feb 6, 2022
1 parent 63c77af commit 458e4cc
Show file tree
Hide file tree
Showing 16 changed files with 136 additions and 84 deletions.
20 changes: 11 additions & 9 deletions packages/vite-plugin-checker/__tests__/e2e/Sandbox/Sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'path'
import playwright from 'playwright-chromium'
import strip from 'strip-ansi'
import invariant from 'tiny-invariant'
import { build, createServer, HMRPayload, ViteDevServer } from 'vite'
import { build, createServer, HMRPayload, ViteDevServer, CustomPayload } from 'vite'
import { Checker } from 'vite-plugin-checker'

import { expectStdoutNotContains, sleep, testDir } from '../testUtils'
Expand Down Expand Up @@ -53,7 +53,7 @@ export async function viteServe({
cwd?: string
port?: number
path?: string
wsSend?: (payload: HMRPayload) => void
wsSend?: (payload: CustomPayload) => void
proxyConsole?: () => void
launchPage?: boolean
} = {}) {
Expand All @@ -68,7 +68,7 @@ export async function viteServe({
await devServer.listen()

if (wsSend) {
devServer.ws.send = (payload) => {
devServer.ws.send = (payload: CustomPayload) => {
wsSend(payload)
}
}
Expand Down Expand Up @@ -105,27 +105,29 @@ export async function pollingUntil<T>(poll: () => Promise<T>, until: (actual: T)
}

export async function waitForHmrOverlay() {
const element = await page.waitForSelector('vite-error-overlay', { state: 'attached' })
const element = await page.waitForSelector('vite-plugin-checker-error-overlay', {
state: 'attached',
})
return element
}

export async function getHmrOverlay() {
const dom = await page.$('vite-error-overlay')
if (dom) console.log('found vite-error-overlay')
const dom = await page.$('vite-plugin-checker-error-overlay')
if (dom) console.log('found vite-plugin-checker-error-overlay')
return dom
}

export async function getHmrOverlayText(
element?: ElementHandleForTag<'vite-error-overlay'> | null
element?: ElementHandleForTag<'vite-plugin-checker-error-overlay'> | null
) {
let shadowRoot: ElementHandleForTag<'vite-error-overlay'> | undefined | null
let shadowRoot: ElementHandleForTag<'vite-plugin-checker-error-overlay'> | undefined | null
if (element) {
shadowRoot = element
} else {
shadowRoot = await getHmrOverlay()
invariant(
shadowRoot,
`<vite-error-overlay> shadow dom is expected to be found, but got ${shadowRoot}`
`<vite-plugin-checker-error-overlay> shadow dom is expected to be found, but got ${shadowRoot}`
)
}

Expand Down
6 changes: 4 additions & 2 deletions packages/vite-plugin-checker/src/@runtime/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,10 @@ export function inject() {
break
}

if (data.type === WS_CHECKER_ERROR_TYPE) {
createErrorOverlay([data.err])
if (data.event === WS_CHECKER_ERROR_TYPE) {
if (data.data.errors.length > 0) {
createErrorOverlay(data.data.errors)
}
}
})
}
Expand Down
15 changes: 9 additions & 6 deletions packages/vite-plugin-checker/src/checkers/eslint/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
diagnosticToTerminalLog,
diagnosticToViteError,
NormalizedDiagnostic,
toViteCustomPayload,
normalizeEslintDiagnostic,
} from '../../logger'
import { ACTION_TYPES } from '../../types'
Expand Down Expand Up @@ -70,12 +71,14 @@ const createDiagnostic: CreateDiagnostic<'eslint'> = (pluginConfig) => {
if (overlay) {
parentPort?.postMessage({
type: ACTION_TYPES.overlayError,
payload: lastErr
? {
type: 'error',
err: diagnosticToViteError(lastErr),
}
: null,
payload: toViteCustomPayload('eslint', lastErr ? [diagnosticToViteError(lastErr)] : []),

// payload: lastErr
// ? {
// type: 'error',
// err: diagnosticToViteError(lastErr),
// }
// : null,
})
}
}
Expand Down
27 changes: 14 additions & 13 deletions packages/vite-plugin-checker/src/checkers/typescript/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@ import {
diagnosticToViteError,
ensureCall,
normalizeTsDiagnostic,
toViteCustomPayload,
} from '../../logger'
import { ACTION_TYPES, CreateDiagnostic } from '../../types'

import type { ErrorPayload } from 'vite'

const createDiagnostic: CreateDiagnostic<'typescript'> = (pluginConfig) => {
let overlay = true // Vite defaults to true
let currErr: ErrorPayload['err'] | null = null
// let currErr: ErrorPayload['err'] | null = null
let currErrs: ErrorPayload['err'][] = []

return {
config: ({ hmr }) => {
Expand Down Expand Up @@ -52,12 +54,13 @@ const createDiagnostic: CreateDiagnostic<'typescript'> = (pluginConfig) => {

// https://github.com/microsoft/TypeScript/blob/a545ab1ac2cb24ff3b1aaf0bfbfb62c499742ac2/src/compiler/watch.ts#L12-L28
const reportDiagnostic = (diagnostic: ts.Diagnostic) => {
const formattedDiagnostics = normalizeTsDiagnostic(diagnostic)
if (!currErr) {
currErr = diagnosticToViteError(formattedDiagnostics)
}
const normalizedDiagnostics = normalizeTsDiagnostic(diagnostic)
currErrs.push(diagnosticToViteError(normalizedDiagnostics))
// if (!currErr) {
// currErr = diagnosticToViteError(normalizedDiagnostics)
// }

logChunk += os.EOL + diagnosticToTerminalLog(formattedDiagnostics, 'TypeScript')
logChunk += os.EOL + diagnosticToTerminalLog(normalizedDiagnostics, 'TypeScript')
}

const reportWatchStatusChanged: ts.WatchStatusReporter = (
Expand All @@ -75,19 +78,17 @@ const createDiagnostic: CreateDiagnostic<'typescript'> = (pluginConfig) => {
case 6032:
// clear current error and use the newer errors
logChunk = ''
currErr = null
// currErr = null
currErrs = []
return
case 6193: // 1 Error
case 6194: // 0 errors or 2+ errors
if (overlay) {
// const normalizedDiagnostics = normalizeTsDiagnostic(diagnostic)
// parentPort?.postMessage(toWsPayload(currErrs))
parentPort?.postMessage({
type: ACTION_TYPES.overlayError,
payload: currErr
? {
type: 'error',
err: currErr,
}
: null,
payload: toViteCustomPayload('typescript', currErrs),
})
}
}
Expand Down
14 changes: 8 additions & 6 deletions packages/vite-plugin-checker/src/checkers/vls/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { parentPort, workerData } from 'worker_threads'
import { Checker } from '../../Checker'
import { ACTION_TYPES } from '../../types'
import { DiagnosticOptions, diagnostics } from './diagnostics'
import { toViteCustomPayload } from '../../logger'

import type { CreateDiagnostic } from '../../types'
export const createDiagnostic: CreateDiagnostic<'vls'> = (pluginConfig) => {
Expand All @@ -22,12 +23,13 @@ export const createDiagnostic: CreateDiagnostic<'vls'> = (pluginConfig) => {
if (!overlay) return
parentPort?.postMessage({
type: ACTION_TYPES.overlayError,
payload: overlayErr
? {
type: 'error',
err: overlayErr,
}
: null,
payload: toViteCustomPayload('vls', overlayErr ? [overlayErr] : []),
// payload: overlayErr
// ? {
// type: 'error',
// err: overlayErr,
// }
// : null,
})
}

Expand Down
55 changes: 37 additions & 18 deletions packages/vite-plugin-checker/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import chalk from 'chalk'
import fs from 'fs'
import os from 'os'
import strip from 'strip-ansi'
import { ErrorPayload } from 'vite'
import { ErrorPayload, CustomPayload } from 'vite'
import { URI } from 'vscode-uri'
import { parentPort, isMainThread } from 'worker_threads'
import { isMainThread, parentPort } from 'worker_threads'

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

import { WS_CHECKER_ERROR_TYPE } from './client/index'
import { ACTION_TYPES } from './types'

import type { Range } from 'vscode-languageclient'
Expand Down Expand Up @@ -81,27 +82,45 @@ export function diagnosticToTerminalLog(
.join(os.EOL)
}

export function diagnosticToViteError(d: NormalizedDiagnostic): ErrorPayload['err']
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 = {
file: d.id,
line: d.loc.start.line,
column: typeof d.loc.start.column === 'number' ? d.loc.start.column : 0,
): ErrorPayload['err'] | ErrorPayload['err'][] {
const diagnosticsArray = Array.isArray(diagnostics) ? diagnostics : [diagnostics]

const results = diagnosticsArray.map((d) => {
let loc: ErrorPayload['err']['loc']
if (d.loc) {
loc = {
file: d.id,
line: d.loc.start.line,
column: typeof d.loc.start.column === 'number' ? d.loc.start.column : 0,
}
}
}

return {
message: d.message ?? '',
stack:
typeof d.stack === 'string' ? d.stack : Array.isArray(d.stack) ? d.stack.join(os.EOL) : '',
id: d.id,
frame: d.stripedCodeFrame,
plugin: `vite-plugin-checker(${d.checker})`,
loc,
}
})

return Array.isArray(diagnostics) ? results : results[0]
}

export function toViteCustomPayload(id: string, errors: ErrorPayload['err'][]): CustomPayload {
return {
message: d.message ?? '',
stack:
typeof d.stack === 'string' ? d.stack : Array.isArray(d.stack) ? d.stack.join(os.EOL) : '',
id: d.id,
frame: d.stripedCodeFrame,
plugin: `vite-plugin-checker(${d.checker})`,
loc,
type: 'custom',
event: WS_CHECKER_ERROR_TYPE,
data: {
checkerId: id,
errors,
},
}
}

Expand Down
2 changes: 0 additions & 2 deletions packages/vite-plugin-checker/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,6 @@ export default function Plugin(userConfig: UserPluginConfig): Plugin {
if (action.type === ACTION_TYPES.overlayError) {
latestOverlayErrors[index] = action.payload
if (action.payload) {
// @ts-ignore
action.payload.type = WS_CHECKER_ERROR_TYPE
server.ws.send(action.payload)
}
} else if (action.type === ACTION_TYPES.console) {
Expand Down
6 changes: 3 additions & 3 deletions packages/vite-plugin-checker/src/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ConfigEnv, HMRPayload } from 'vite'
import type { ConfigEnv, CustomPayload } from 'vite'
import type { Worker } from 'worker_threads'
import type { ESLint } from 'eslint'
import type { VlsOptions } from './checkers/vls/initParams'
Expand Down Expand Up @@ -117,10 +117,10 @@ interface Action {
export interface OverlayErrorAction extends Action {
type: ACTION_TYPES.overlayError
/**
* send `HMRPayload` to raise error overlay provided by Vite
* send `CustomPayload` to raise error overlay provided by Vite
* send `null` to clear overlay for current checker
*/
payload: HMRPayload | null
payload: CustomPayload | null
}

interface ConfigActionPayload {
Expand Down
4 changes: 2 additions & 2 deletions playground/react-ts/__tests__/__snapshots__/test.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`typescript serve get initial error and subsequent error 1`] = `"{\\"frame\\":\\" 4 |/n 5 | function App() {/n > 6 | const [count, setCount] = useState<string>(1)/n | ^/n 7 | return (/n 8 | <div className=/\\"App/\\">/n 9 | <header className=/\\"App-header/\\">\\",\\"id\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"loc\\":{\\"column\\":46,\\"file\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"line\\":6},\\"message\\":\\"Argument of type 'number' is not assignable to parameter of type 'string | (() => string)'.\\",\\"plugin\\":\\"vite-plugin-checker(TypeScript)\\",\\"stack\\":\\"\\"}"`;
exports[`typescript serve get initial error and subsequent error 1`] = `"[{\\"frame\\":\\" 4 |/n 5 | function App() {/n > 6 | const [count, setCount] = useState<string>(1)/n | ^/n 7 | return (/n 8 | <div className=/\\"App/\\">/n 9 | <header className=/\\"App-header/\\">\\",\\"id\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"loc\\":{\\"column\\":46,\\"file\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"line\\":6},\\"message\\":\\"Argument of type 'number' is not assignable to parameter of type 'string | (() => string)'.\\",\\"plugin\\":\\"vite-plugin-checker(TypeScript)\\",\\"stack\\":\\"\\"}]"`;

exports[`typescript serve get initial error and subsequent error 2`] = `
"
Expand All @@ -18,7 +18,7 @@ exports[`typescript serve get initial error and subsequent error 2`] = `
Found 1 error. Watching for file changes."
`;
exports[`typescript serve get initial error and subsequent error 3`] = `"{\\"frame\\":\\" 4 |/n 5 | function App() {/n > 6 | const [count, setCount] = useState<string>(2)/n | ^/n 7 | return (/n 8 | <div className=/\\"App/\\">/n 9 | <header className=/\\"App-header/\\">\\",\\"id\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"loc\\":{\\"column\\":46,\\"file\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"line\\":6},\\"message\\":\\"Argument of type 'number' is not assignable to parameter of type 'string | (() => string)'.\\",\\"plugin\\":\\"vite-plugin-checker(TypeScript)\\",\\"stack\\":\\"\\"}"`;
exports[`typescript serve get initial error and subsequent error 3`] = `"[{\\"frame\\":\\" 4 |/n 5 | function App() {/n > 6 | const [count, setCount] = useState<string>(2)/n | ^/n 7 | return (/n 8 | <div className=/\\"App/\\">/n 9 | <header className=/\\"App-header/\\">\\",\\"id\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"loc\\":{\\"column\\":46,\\"file\\":\\"<PROJECT_ROOT>/temp/react-ts/src/App.tsx\\",\\"line\\":6},\\"message\\":\\"Argument of type 'number' is not assignable to parameter of type 'string | (() => string)'.\\",\\"plugin\\":\\"vite-plugin-checker(TypeScript)\\",\\"stack\\":\\"\\"}]"`;
exports[`typescript serve get initial error and subsequent error 4`] = `
"
Expand Down
17 changes: 12 additions & 5 deletions playground/react-ts/__tests__/test.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
testDir,
WORKER_CLEAN_TIMEOUT,
} from 'vite-plugin-checker/__tests__/e2e/testUtils'
import { WS_CHECKER_ERROR_TYPE } from 'vite-plugin-checker/src/client'

import { copyCode } from '../../../scripts/jestSetupFilesAfterEnv'
import { serializers } from '../../../scripts/serializers'
Expand All @@ -40,18 +41,24 @@ describe('typescript', () => {
})

it('get initial error and subsequent error', async () => {
let err: any
// @ts-expect-error
await viteServe({ cwd: testDir, wsSend: (_payload) => (err = _payload.err) })
let errors: any
await viteServe({
cwd: testDir,
wsSend: (_payload) => {
if (_payload.type === 'custom' && _payload.event == WS_CHECKER_ERROR_TYPE) {
errors = _payload.data.errors
}
},
})
await sleepForServerReady()
expect(stringify(err)).toMatchSnapshot()
expect(stringify(errors)).toMatchSnapshot()
expect(stripedLog).toMatchSnapshot()

console.log('-- edit file --')
resetReceivedLog()
editFile('src/App.tsx', (code) => code.replace('useState<string>(1)', 'useState<string>(2)'))
await sleepForEdit()
expect(stringify(err)).toMatchSnapshot()
expect(stringify(errors)).toMatchSnapshot()
expect(stripedLog).toMatchSnapshot()
})
})
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`eslint serve get initial error and subsequent error 1`] = `"{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello'/n | ^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}"`;
exports[`eslint serve get initial error and subsequent error 1`] = `"[{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello'/n | ^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}]"`;

exports[`eslint serve get initial error and subsequent error 2`] = `
" ERROR(ESLint) Unexpected var, use let or const instead.
Expand All @@ -16,7 +16,7 @@ exports[`eslint serve get initial error and subsequent error 2`] = `
"
`;
exports[`eslint serve get initial error and subsequent error 3`] = `"{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello~'/n | ^^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}"`;
exports[`eslint serve get initial error and subsequent error 3`] = `"[{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello~'/n | ^^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}]"`;
exports[`eslint serve get initial error and subsequent error 4`] = `
" ERROR(ESLint) Unexpected var, use let or const instead.
Expand All @@ -32,7 +32,7 @@ exports[`eslint serve get initial error and subsequent error 4`] = `
"
`;
exports[`eslint serve get initial error and subsequent error 5`] = `"{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello~'/n | ^^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}"`;
exports[`eslint serve get initial error and subsequent error 5`] = `"[{\\"frame\\":\\" 1 | import { text } from './text'/n 2 |/n > 3 | var hello = 'Hello~'/n | ^^^^^^^^^^^^^^^^^^^^/n 4 |/n 5 | const rootDom = document.querySelector('#root')!/n 6 | rootDom.innerHTML = hello + text\\",\\"id\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"loc\\":{\\"column\\":1,\\"file\\":\\"<PROJECT_ROOT>/temp/vanilla-ts/src/main.ts\\",\\"line\\":3},\\"message\\":\\"Unexpected var, use let or const instead.\\",\\"plugin\\":\\"vite-plugin-checker(ESLint)\\",\\"stack\\":\\"\\"}]"`;
exports[`eslint serve get initial error and subsequent error 6`] = `
" ERROR(ESLint) Unexpected var, use let or const instead.
Expand Down
Loading

0 comments on commit 458e4cc

Please sign in to comment.