Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: HMR on web/shared worker #10262

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
92 changes: 63 additions & 29 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ console.debug('[vite] connecting...')

const importMetaUrl = new URL(import.meta.url)

const onUi = typeof window !== 'undefined'
const logReloadMessage =
'[vite] running on worker, please reload the page manually!'

// use server configuration, then fallback to inference
const serverHost = __SERVER_HOST__
const socketProtocol =
Expand Down Expand Up @@ -102,6 +106,11 @@ function setupWebSocket(

console.log(`[vite] server connection lost. polling for restart...`)
await waitForSuccessfulPing(protocol, hostAndPath)
if (!onUi) {
console.warn(logReloadMessage)
return
}

location.reload()
})

Expand Down Expand Up @@ -162,32 +171,34 @@ async function handleMessage(payload: HMRPayload) {
// this is only sent when a css file referenced with <link> is updated
const { path, timestamp } = update
const searchUrl = cleanUrl(path)
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link')
).find(
(e) =>
!outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)
)
if (el) {
const newPath = `${base}${searchUrl.slice(1)}${
searchUrl.includes('?') ? '&' : '?'
}t=${timestamp}`

// rather than swapping the href on the existing tag, we will
// create a new link tag. Once the new stylesheet has loaded we
// will remove the existing link tag. This removes a Flash Of
// Unstyled Content that can occur when swapping out the tag href
// directly, as the new stylesheet has not yet been loaded.
const newLinkTag = el.cloneNode() as HTMLLinkElement
newLinkTag.href = new URL(newPath, el.href).href
const removeOldEl = () => el.remove()
newLinkTag.addEventListener('load', removeOldEl)
newLinkTag.addEventListener('error', removeOldEl)
outdatedLinkTags.add(el)
el.after(newLinkTag)
if (onUi) {
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link')
).find(
(e) =>
!outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl)
)
if (el) {
const newPath = `${base}${searchUrl.slice(1)}${
searchUrl.includes('?') ? '&' : '?'
}t=${timestamp}`

// rather than swapping the href on the existing tag, we will
// create a new link tag. Once the new stylesheet has loaded we
// will remove the existing link tag. This removes a Flash Of
// Unstyled Content that can occur when swapping out the tag href
// directly, as the new stylesheet has not yet been loaded.
const newLinkTag = el.cloneNode() as HTMLLinkElement
newLinkTag.href = new URL(newPath, el.href).href
const removeOldEl = () => el.remove()
newLinkTag.addEventListener('load', removeOldEl)
newLinkTag.addEventListener('error', removeOldEl)
outdatedLinkTags.add(el)
el.after(newLinkTag)
}
}
console.debug(`[vite] css hot updated: ${searchUrl}`)
}
Expand All @@ -209,10 +220,18 @@ async function handleMessage(payload: HMRPayload) {
payload.path === '/index.html' ||
(pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)
) {
if (!onUi) {
console.warn(logReloadMessage)
return
}
location.reload()
}
return
} else {
if (!onUi) {
console.warn(logReloadMessage)
return
}
location.reload()
}
break
Expand Down Expand Up @@ -264,16 +283,30 @@ const enableOverlay = __HMR_ENABLE_OVERLAY__
function createErrorOverlay(err: ErrorPayload['err']) {
if (!enableOverlay) return
clearErrorOverlay()
if (!onUi) {
console.log(`[vite] Internal Server Error\n${err.message}\n${err.stack}`)
return
}

document.body.appendChild(new ErrorOverlay(err))
}

function clearErrorOverlay() {
document
.querySelectorAll(overlayId)
.forEach((n) => (n as ErrorOverlay).close())
if (!onUi) {
// TODO: clear console?
// console.clear()
return
}

document.querySelectorAll(overlayId).forEach((n) =>
// @ts-ignore
(n as ErrorOverlay).close()
)
}

function hasErrorOverlay() {
if (!onUi) return false

return document.querySelectorAll(overlayId).length
}

Expand Down Expand Up @@ -547,6 +580,7 @@ export function createHotContext(ownerPath: string): ViteHotContext {
decline() {},

invalidate() {
if (!onUi) return
// TODO should tell the server to re-perform hmr propagation
// from this module as root
location.reload()
Expand Down
151 changes: 84 additions & 67 deletions packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,17 @@
import type { ErrorPayload } from 'types/hmrPayload'

// set :host styles to make playwright detect the element as visible
const template = /*html*/ `
let ErrorOverlay:
| InstanceType<
typeof HTMLElement & {
text(selector: string, text: string, linkFiles?: boolean): void
close(): void
}
>
| any = typeof window !== 'undefined' ? Object : undefined

if (typeof window !== 'undefined') {
// set :host styles to make playwright detect the element as visible
const template = /*html*/ `
<style>
:host {
position: fixed;
Expand Down Expand Up @@ -123,82 +133,89 @@ code {
</div>
`

const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g
const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm

// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where
// `HTMLElement` was not originally defined.
const { HTMLElement = class {} as typeof globalThis.HTMLElement } = globalThis
export class ErrorOverlay extends HTMLElement {
root: ShadowRoot

constructor(err: ErrorPayload['err']) {
super()
this.root = this.attachShadow({ mode: 'open' })
this.root.innerHTML = template

codeframeRE.lastIndex = 0
const hasFrame = err.frame && codeframeRE.test(err.frame)
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `)
}
this.text('.message-body', message.trim())
const fileRE = /(?:[a-zA-Z]:\\|\/).*?:\d+:\d+/g
const codeframeRE = /^(?:>?\s+\d+\s+\|.*|\s+\|\s*\^.*)\r?\n/gm

// Allow `ErrorOverlay` to extend `HTMLElement` even in environments where
// `HTMLElement` was not originally defined.
const { HTMLElement = class {} as typeof globalThis.HTMLElement } = globalThis
class DOMErrorOverlay extends HTMLElement {
root: ShadowRoot

constructor(err: ErrorPayload['err']) {
super()
this.root = this.attachShadow({ mode: 'open' })
this.root.innerHTML = template

codeframeRE.lastIndex = 0
const hasFrame = err.frame && codeframeRE.test(err.frame)
const message = hasFrame
? err.message.replace(codeframeRE, '')
: err.message
if (err.plugin) {
this.text('.plugin', `[plugin:${err.plugin}] `)
}
this.text('.message-body', message.trim())

const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)
} else if (err.id) {
this.text('.file', file)
}
const [file] = (err.loc?.file || err.id || 'unknown file').split(`?`)
if (err.loc) {
this.text('.file', `${file}:${err.loc.line}:${err.loc.column}`, true)
} else if (err.id) {
this.text('.file', file)
}

if (hasFrame) {
this.text('.frame', err.frame!.trim())
if (hasFrame) {
this.text('.frame', err.frame!.trim())
}
this.text('.stack', err.stack, true)

this.root.querySelector('.window')!.addEventListener('click', (e) => {
e.stopPropagation()
})
this.addEventListener('click', () => {
this.close()
})
}
this.text('.stack', err.stack, true)

this.root.querySelector('.window')!.addEventListener('click', (e) => {
e.stopPropagation()
})
this.addEventListener('click', () => {
this.close()
})
}

text(selector: string, text: string, linkFiles = false): void {
const el = this.root.querySelector(selector)!
if (!linkFiles) {
el.textContent = text
} else {
let curIndex = 0
let match: RegExpExecArray | null
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch('/__open-in-editor?file=' + encodeURIComponent(file))
text(selector: string, text: string, linkFiles = false): void {
const el = this.root.querySelector(selector)!
if (!linkFiles) {
el.textContent = text
} else {
let curIndex = 0
let match: RegExpExecArray | null
while ((match = fileRE.exec(text))) {
const { 0: file, index } = match
if (index != null) {
const frag = text.slice(curIndex, index)
el.appendChild(document.createTextNode(frag))
const link = document.createElement('a')
link.textContent = file
link.className = 'file-link'
link.onclick = () => {
fetch('/__open-in-editor?file=' + encodeURIComponent(file))
}
el.appendChild(link)
curIndex += frag.length + file.length
}
el.appendChild(link)
curIndex += frag.length + file.length
}
}
}
}

close(): void {
this.parentNode?.removeChild(this)
close(): void {
this.parentNode?.removeChild(this)
}
}

ErrorOverlay = DOMErrorOverlay
}

export { ErrorOverlay }

export const overlayId = 'vite-error-overlay'
const { customElements } = globalThis // Ensure `customElements` is defined before the next line.
if (customElements && !customElements.get(overlayId)) {
customElements.define(overlayId, ErrorOverlay)
if (typeof globalThis !== 'undefined') {
const { customElements } = globalThis // Ensure `customElements` is defined before the next line.
if (customElements && !customElements.get(overlayId)) {
customElements.define(overlayId, ErrorOverlay)
}
}
20 changes: 19 additions & 1 deletion playground/worker/__tests__/iife/iife-worker.spec.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import fs from 'node:fs'
import path from 'node:path'
import { describe, expect, test } from 'vitest'
import { isBuild, page, testDir, untilUpdated } from '~utils'
import { editFile, isBuild, page, testDir, untilUpdated } from '~utils'

test('normal', async () => {
await untilUpdated(() => page.textContent('.pong'), 'pong')
Expand Down Expand Up @@ -106,6 +106,24 @@ test('url query worker', async () => {
() => page.textContent('.simple-worker-url'),
'Hello from simple worker!'
)

editFile('simple-worker.js', (code) =>
code.replace('hey there', 'hey there!')
)

await untilUpdated(
() => page.textContent('.simple-worker-url'),
'Hello from simple worker (HMR message: hey there!)!'
)

editFile('simple-worker.js', (code) =>
code.replace('hey there!', 'hey there')
)

await untilUpdated(
() => page.textContent('.simple-worker-url'),
'Hello from simple worker (HMR message: hey there)!'
)
})

test('import.meta.glob eager in worker', async () => {
Expand Down
12 changes: 12 additions & 0 deletions playground/worker/my-shared-worker.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
const ports = new Set()

export let message = 'hey there'

// @ts-expect-error
self.onconnect = (event) => {
const port = event.ports[0]
Expand All @@ -12,5 +14,15 @@ self.onconnect = (event) => {
}
}

if (import.meta.hot) {
import.meta.hot.accept((data) => {
const message = data && data.message
if (message) {
ports.forEach((p: any) => {
p.postMessage(`HMR pong: ${message}`)
})
}
})
}
// for sourcemap
console.log('my-shared-worker.js')
12 changes: 12 additions & 0 deletions playground/worker/simple-worker.js
Original file line number Diff line number Diff line change
@@ -1 +1,13 @@
export let simpleWorkerMessage = 'hey there'

self.postMessage('Hello from simple worker!')

if (import.meta.hot) {
import.meta.hot.accept((data) => {
console.log(data)
simpleWorkerMessage = data && data.simpleWorkerMessage
self.postMessage(
`Hello from simple worker (HMR message: ${simpleWorkerMessage})!`
)
})
}