109 lines
2.7 KiB
JavaScript
109 lines
2.7 KiB
JavaScript
/**
|
|
* {一些工具类函数}
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2023/05/22 14:52:00
|
|
*/
|
|
|
|
import { createHash, randomUUID } from 'node:crypto'
|
|
import { join } from 'node:path'
|
|
import { Worker } from 'node:worker_threads'
|
|
import { red, cyan, blue } from 'kolorist'
|
|
|
|
// 修正路径合并 避免在windows下被转义
|
|
export function urlJoin(...args) {
|
|
return join(...args).replace(/\\/g, '/')
|
|
}
|
|
|
|
export function uuid() {
|
|
return randomUUID().slice(-8)
|
|
}
|
|
|
|
export function md5(str = '') {
|
|
let sum = createHash('md5')
|
|
sum.update(str, 'utf8')
|
|
return sum.digest('hex').slice(0, 8)
|
|
}
|
|
|
|
export function friendlyErrors(pathname, ext = '') {
|
|
console.log(cyan(pathname), red(`not found!!!`))
|
|
console.log(
|
|
red('请正确填写引入的文件路径, fite 不再自动补全【%s】\n'),
|
|
blue(`/index.${ext}`)
|
|
)
|
|
}
|
|
|
|
export function createHmrScript(legacy, session = '') {
|
|
return `
|
|
!(function vue_live_hmr(){
|
|
var ws = new WebSocket(\`ws\${location.protocol === 'https:' ? 's' : ''}://\${location.host}/ws-fite-hmr?session=${session}\`)
|
|
|
|
ws.addEventListener('open', function (r) {
|
|
if(vue_live_hmr.closed){
|
|
delete vue_live_hmr.closed
|
|
location.reload()
|
|
}
|
|
console.log('fite hmr ready...')
|
|
})
|
|
|
|
ws.addEventListener('close', function(){
|
|
vue_live_hmr.closed = true
|
|
setTimeout(vue_live_hmr, 2000)
|
|
})
|
|
|
|
ws.addEventListener('message', function (ev) {
|
|
var { action, data } = JSON.parse(ev.data)
|
|
|
|
switch (action) {
|
|
case 'reload':
|
|
location.reload()
|
|
break
|
|
|
|
case 'render':
|
|
{
|
|
${
|
|
legacy
|
|
? `
|
|
let stylesheet = document.head.children.namedItem(data.path)
|
|
if (stylesheet) {
|
|
stylesheet.textContent = data.content
|
|
}
|
|
`
|
|
: `
|
|
let tmp = [...document.adoptedStyleSheets]
|
|
for (let i = -1, it; (it = tmp[++i]); ) {
|
|
if (it.path === data.path) {
|
|
let stylesheet = new CSSStyleSheet()
|
|
stylesheet.path = data.path
|
|
stylesheet.replaceSync(data.content)
|
|
tmp[i] = stylesheet
|
|
document.adoptedStyleSheets = tmp
|
|
break
|
|
}
|
|
}
|
|
`
|
|
}
|
|
}
|
|
break
|
|
}
|
|
})
|
|
})()
|
|
`
|
|
}
|
|
|
|
export function isCustomElement(tag) {
|
|
return tag.startsWith('wc-')
|
|
}
|
|
|
|
export function startWorker(file) {
|
|
return new Promise((resolve, reject) => {
|
|
let worker = new Worker(file)
|
|
worker.on('message', resolve)
|
|
worker.on('error', reject)
|
|
worker.on('exit', code => {
|
|
if (code !== 0) {
|
|
reject(new Error(`Worker stopped with exit code ${code}`))
|
|
}
|
|
})
|
|
})
|
|
}
|