Departure commit

This commit is contained in:
mio
2023-05-01 15:52:32 +08:00
commit 92cafdadb8
61 changed files with 9597 additions and 0 deletions

97
.electron-vite/build.js Normal file
View File

@ -0,0 +1,97 @@
'use strict'
process.env.NODE_ENV = 'production'
const { say } = require('cfonts')
const { sync } = require('del')
const chalk = require('chalk')
const rollup = require("rollup")
const { build } = require('vite')
const Multispinner = require('multispinner')
const mainOptions = require('./rollup.main.config');
const rendererOptions = require('./vite.config')
const opt = mainOptions(process.env.NODE_ENV);
const doneLog = chalk.bgGreen.white(' DONE ') + ' '
const errorLog = chalk.bgRed.white(' ERROR ') + ' '
const okayLog = chalk.bgBlue.white(' OKAY ') + ' '
const isCI = process.env.CI || false
if (process.env.BUILD_TARGET === 'web') web()
else unionBuild()
function clean() {
sync(['dist/electron/main/*', 'dist/electron/renderer/*', 'dist/web/*', 'build/*', '!build/icons', '!build/lib', '!build/lib/electron-build.*', '!build/icons/icon.*'])
console.log(`\n${doneLog}clear done`)
if (process.env.BUILD_TARGET === 'onlyClean') process.exit()
}
function unionBuild() {
greeting()
if (process.env.BUILD_TARGET === 'clean' || process.env.BUILD_TARGET === 'onlyClean') clean()
const tasks = ['main', 'renderer']
const m = new Multispinner(tasks, {
preText: 'building',
postText: 'process'
})
let results = ''
m.on('success', () => {
process.stdout.write('\x1B[2J\x1B[0f')
console.log(`\n\n${results}`)
console.log(`${okayLog}take it away ${chalk.yellow('`electron-builder`')}\n`)
process.exit()
})
rollup.rollup(opt)
.then(build => {
results += `${doneLog}MainProcess build success` + '\n\n'
build.write(opt.output).then(() => {
m.success('main')
})
})
.catch(error => {
m.error('main')
console.log(`\n ${errorLog}failed to build main process`)
console.error(`\n${error}\n`)
process.exit(1)
});
build(rendererOptions).then(res => {
results += `${doneLog}RendererProcess build success` + '\n\n'
m.success('renderer')
}).catch(err => {
m.error('renderer')
console.log(`\n ${errorLog}failed to build renderer process`)
console.error(`\n${err}\n`)
process.exit(1)
})
}
function web() {
sync(['dist/web/*', '!.gitkeep'])
build(rendererOptions).then(res => {
console.log(`${doneLog}RendererProcess build success`)
process.exit()
})
}
function greeting() {
const cols = process.stdout.columns
let text = ''
if (cols > 85) text = `let's-build`
else if (cols > 60) text = `let's-|build`
else text = false
if (text && !isCI) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else console.log(chalk.yellow.bold(`\n let's-build`))
console.log()
}

View File

@ -0,0 +1,198 @@
process.env.NODE_ENV = 'development'
const chalk = require('chalk')
const electron = require('electron')
const path = require('path')
const rollup = require("rollup")
const Portfinder = require("portfinder")
const { say } = require('cfonts')
const { spawn } = require('child_process')
const { createServer } = require('vite')
const rendererOptions = require("./vite.config")
const mainOptions = require("./rollup.main.config")
const opt = mainOptions(process.env.NODE_ENV);
let electronProcess = null
let manualRestart = false
function logStats(proc, data) {
let log = ''
log += chalk.yellow.bold(`${proc} 'Process' ${new Array((19 - proc.length) + 1).join('-')}`)
log += '\n\n'
if (typeof data === 'object') {
data.toString({
colors: true,
chunks: false
}).split(/\r?\n/).forEach(line => {
log += ' ' + line + '\n'
})
} else {
log += ` ${data}\n`
}
log += '\n' + chalk.yellow.bold(`${new Array(28 + 1).join('-')}`) + '\n'
console.log(log)
}
function removeJunk(chunk) {
// Example: 2018-08-10 22:48:42.866 Electron[90311:4883863] *** WARNING: Textured window <AtomNSWindow: 0x7fb75f68a770>
if (/\d+-\d+-\d+ \d+:\d+:\d+\.\d+ Electron(?: Helper)?\[\d+:\d+] /.test(chunk)) {
return false;
}
// Example: [90789:0810/225804.894349:ERROR:CONSOLE(105)] "Uncaught (in promise) Error: Could not instantiate: ProductRegistryImpl.Registry", source: chrome-devtools://devtools/bundled/inspector.js (105)
if (/\[\d+:\d+\/|\d+\.\d+:ERROR:CONSOLE\(\d+\)\]/.test(chunk)) {
return false;
}
// Example: ALSA lib confmisc.c:767:(parse_card) cannot find card '0'
if (/ALSA lib [a-z]+\.c:\d+:\([a-z_]+\)/.test(chunk)) {
return false;
}
return chunk;
}
function startRenderer() {
return new Promise((resolve, reject) => {
Portfinder.basePort = 9080
Portfinder.getPort(async (err, port) => {
if (err) {
console.log('PortError:', err)
process.exit(1)
} else {
const server = await createServer(rendererOptions)
process.env.PORT = port
await server.listen(port)
if (process.env.TARGET === 'web') {
server.config.logger.info(
chalk.cyan(`\n vite v${require('vite/package.json').version}`) +
chalk.green(` dev server running at:\n`),
{
clear: !server.config.logger.hasWarned,
}
)
server.printUrls()
}
resolve()
}
})
})
}
function startMain() {
return new Promise((resolve, reject) => {
const watcher = rollup.watch(opt);
watcher.on('change', filename => {
// 主进程日志部分
logStats('Main-FileChange', filename)
});
watcher.on('event', event => {
if (event.code === 'END') {
if (electronProcess && electronProcess.kill) {
manualRestart = true
process.kill(electronProcess.pid)
electronProcess = null
startElectron()
setTimeout(() => {
manualRestart = false
}, 5000)
}
resolve()
} else if (event.code === 'ERROR') {
reject(event.error)
}
})
})
}
function startElectron() {
var args = [
'--inspect=5858',
path.join(__dirname, '../dist/electron/main/main.js')
]
// detect yarn or npm and process commandline args accordingly
if (process.env.npm_execpath.endsWith('yarn.js')) {
args = args.concat(process.argv.slice(3))
} else if (process.env.npm_execpath.endsWith('npm-cli.js')) {
args = args.concat(process.argv.slice(2))
}
electronProcess = spawn(electron, args)
electronProcess.stdout.on('data', data => {
electronLog(removeJunk(data), 'blue')
})
electronProcess.stderr.on('data', data => {
electronLog(removeJunk(data), 'red')
})
electronProcess.on('close', () => {
if (!manualRestart) process.exit()
})
}
function electronLog(data, color) {
if (data) {
let log = ''
data = data.toString().split(/\r?\n/)
data.forEach(line => {
log += ` ${line}\n`
})
console.log(
chalk[color].bold(`┏ Electron -------------------`) +
'\n\n' +
log +
chalk[color].bold('┗ ----------------------------') +
'\n'
)
}
}
function greeting() {
const cols = process.stdout.columns
let text = ''
if (cols > 104) text = 'electron-vite'
else if (cols > 76) text = 'electron-|vite'
else text = false
if (text) {
say(text, {
colors: ['yellow'],
font: 'simple3d',
space: false
})
} else console.log(chalk.yellow.bold('\n electron-vite'))
console.log(chalk.blue(`getting ready...`) + '\n')
}
async function init() {
greeting()
try {
await startRenderer()
if (process.env.TARGET !== 'web') {
await startMain()
await startElectron()
}
} catch (error) {
console.error(error)
process.exit(1)
}
}
init()

View File

@ -0,0 +1,64 @@
const path = require('path')
const { nodeResolve } = require('@rollup/plugin-node-resolve')
const commonjs = require('@rollup/plugin-commonjs')
const esbuild = require('rollup-plugin-esbuild').default
const alias = require('@rollup/plugin-alias')
const json = require('@rollup/plugin-json')
module.exports = (env = 'production') => {
return {
input: path.join(__dirname, '../src/main/main.js'),
output: {
file: path.join(__dirname, '../dist/electron/main/main.js'),
format: 'cjs',
name: 'MainProcess',
sourcemap: false,
exports: 'auto'
},
plugins: [
nodeResolve({ jsnext: true, preferBuiltins: true, browser: true }), // 消除碰到 node.js 模块时⚠警告
commonjs(),
json(),
esbuild({
// All options are optional
include: /\.[jt]sx?$/, // default, inferred from `loaders` option
exclude: /node_modules/, // default
// watch: process.argv.includes('--watch'), // rollup 中有配置
sourceMap: false, // default
minify: process.env.NODE_ENV === 'production',
target: 'esnext', // default, or 'es20XX', 'esnext'
// Like @rollup/plugin-replace
define: {
__VERSION__: '"x.y.z"'
},
// Add extra loaders
loaders: {
// Add .json files support
// require @rollup/plugin-commonjs
'.json': 'json',
// Enable JSX in .js files too
'.js': 'jsx'
},
}),
alias({
entries: [
{ find: '@main', replacement: path.join(__dirname, '../src/main'), },
]
})
],
external: [
'crypto',
'assert',
'fs',
'util',
'os',
'events',
'child_process',
'http',
'https',
'path',
'electron',
'original-fs'
],
}
}

63
.electron-vite/update.js Normal file
View File

@ -0,0 +1,63 @@
const fs = require('fs-extra')
const path = require('path')
const crypto = require('crypto')
const AdmZip = require('adm-zip')
const { version } = require('../package.json')
const hash = (data, type = 'sha256') => {
const hmac = crypto.createHmac(type, 'hk4e')
hmac.update(data)
return hmac.digest('hex')
}
const createZip = (filePath, dest) => {
const zip = new AdmZip()
zip.addLocalFolder(filePath)
zip.toBuffer()
zip.writeZip(dest)
}
const start = async () => {
copyAppZip()
const appPath = './build/win-unpacked/resources/app'
const name = 'app.zip'
const outputPath = path.resolve('./build/update/update/')
const zipPath = path.resolve(outputPath, name)
await fs.ensureDir(outputPath)
await fs.emptyDir(outputPath)
await fs.outputFile('./build/update/CNAME', 'star-rail-warp-export.css.moe')
createZip(appPath, zipPath)
const buffer = await fs.readFile(zipPath)
const sha256 = hash(buffer)
const hashName = sha256.slice(7, 12)
await fs.copy(zipPath, path.resolve(outputPath, `${hashName}.zip`))
await fs.remove(zipPath)
await fs.outputJSON(path.join(outputPath, 'manifest.json'), {
active: true,
version,
from: '0.1.5',
name: `${hashName}.zip`,
hash: sha256
})
copyHTML()
}
const copyAppZip = () => {
try {
const dir = path.resolve('./build')
const filePath = path.resolve(dir, `StarRailWarpExport-${version}-win.zip`)
fs.copySync(filePath, path.join(dir, 'app.zip'))
} catch (e) {}
}
const copyHTML = () => {
try {
const output = path.resolve('./build/update/')
const dir = path.resolve('./src/web/')
fs.copySync(dir, output)
} catch (e) {
console.error(e)
}
}
start()

View File

@ -0,0 +1,37 @@
const { join } = require("path")
const vuePlugin = require("@vitejs/plugin-vue")
const { defineConfig } = require("vite")
function resolve(dir) {
return join(__dirname, '..', dir)
}
const root = resolve('src/renderer')
const config = defineConfig({
mode: process.env.NODE_ENV,
root,
resolve: {
alias: {
'@renderer': root,
}
},
base: './',
build: {
outDir: process.env.BUILD_TARGET === 'web' ? resolve('dist/web') : resolve('dist/electron/renderer'),
emptyOutDir: true
},
server: {
port: Number(process.env.PORT),
},
plugins: [
vuePlugin({
script: {
refSugar: true
}
})
],
publicDir: resolve('static')
})
module.exports = config