electron-vite/src/utils.ts

76 lines
2.4 KiB
TypeScript
Raw Normal View History

2022-11-07 17:36:22 +01:00
import { URL, URLSearchParams } from 'node:url'
2023-01-04 15:53:22 +01:00
import path from 'node:path'
2023-12-11 15:06:22 +01:00
import fs from 'node:fs'
2023-01-04 15:53:22 +01:00
import { createHash } from 'node:crypto'
2023-12-11 15:06:22 +01:00
import { createRequire } from 'node:module'
import { loadEnv as viteLoadEnv } from 'vite'
2022-11-07 17:36:22 +01:00
2022-03-17 09:21:02 +01:00
export function isObject(value: unknown): value is Record<string, unknown> {
return Object.prototype.toString.call(value) === '[object Object]'
}
export const wildcardHosts = new Set(['0.0.0.0', '::', '0000:0000:0000:0000:0000:0000:0000:0000'])
export function resolveHostname(optionsHost: string | boolean | undefined): string {
return typeof optionsHost === 'string' && !wildcardHosts.has(optionsHost) ? optionsHost : 'localhost'
}
2022-11-07 17:36:22 +01:00
export const queryRE = /\?.*$/s
export const hashRE = /#.*$/s
export const cleanUrl = (url: string): string => url.replace(hashRE, '').replace(queryRE, '')
export function parseRequest(id: string): Record<string, string> | null {
const { search } = new URL(id, 'file:')
if (!search) {
return null
}
return Object.fromEntries(new URLSearchParams(search))
}
2023-01-04 15:53:22 +01:00
export function getHash(text: Buffer | string): string {
return createHash('sha256').update(text).digest('hex').substring(0, 8)
}
export function toRelativePath(filename: string, importer: string): string {
const relPath = path.posix.relative(path.dirname(importer), filename)
return relPath.startsWith('.') ? relPath : `./${relPath}`
}
/**
* Load `.env` files within the `envDir`(default: `process.cwd()`).
* By default, only env variables prefixed with `MAIN_VITE_`, `PRELOAD_VITE_` and
* `RENDERER_VITE_` are loaded, unless `prefixes` is changed.
*/
export function loadEnv(
mode: string,
envDir: string = process.cwd(),
prefixes: string | string[] = ['MAIN_VITE_', 'PRELOAD_VITE_', 'RENDERER_VITE_']
): Record<string, string> {
return viteLoadEnv(mode, envDir, prefixes)
}
2023-12-11 15:06:22 +01:00
interface PackageData {
main?: string
type?: 'module' | 'commonjs'
dependencies?: Record<string, string>
2023-12-11 15:06:22 +01:00
}
let packageCached: PackageData | null = null
export function loadPackageData(root = process.cwd()): PackageData | null {
if (packageCached) return packageCached
const pkg = path.join(root, 'package.json')
if (fs.existsSync(pkg)) {
const _require = createRequire(import.meta.url)
const data = _require(pkg)
packageCached = {
main: data.main,
type: data.type,
dependencies: data.dependencies
2023-12-11 15:06:22 +01:00
}
return packageCached
}
return null
}