UNPKG

kirbyup

Version:

Zero-config bundler for Kirby Panel plugins

57 lines (55 loc) 1.99 kB
import { __INJECTED_HMR_CODE__, isHmrRuntimeId } from "./utils.js"; import * as fs from "node:fs"; import * as fsp from "node:fs/promises"; import { resolve } from "pathe"; import { detectPackageManager } from "nypm"; //#region src/node/plugins/hmr.ts function kirbyupHmrPlugin(options) { let config; let entry; let devIndexPath; return { name: "kirbyup:hmr", apply: "serve", configResolved(resolvedConfig) { config = resolvedConfig; entry = resolve(config.root, options.entry); devIndexPath = resolve(config.root, options.outDir || "", "index.dev.mjs"); }, transform(code, id) { if (isHmrRuntimeId(id)) return code.replace(/^.*=\s*record\.Ctor\.super\.extend\(options\)/m, "$_applyKirbyModifications(record.Ctor.options, options) // injected by kirbyup\n$&") + __INJECTED_HMR_CODE__; }, configureServer(server) { if (!server.httpServer) return; server.httpServer.once("listening", async () => { const entryPath = entry.replace(`${config.root}/`, ""); const { address, family, port } = server.httpServer.address(); const baseUrl = `http://${family === "IPv6" ? `[${address}]` : address}:${port}${config.base}`; const entryUrl = new URL(entryPath, baseUrl).href; const pm = await detectPackageManager(config.root); await fsp.writeFile(devIndexPath, getViteProxyModule(entryUrl, pm)); }); }, closeBundle() { if (fs.existsSync(devIndexPath)) fs.unlinkSync(devIndexPath); } }; } /** * Proxy the JS file to "forward" the plugin script loaded by Kirby to the Vite server */ function getViteProxyModule(entryUrl, packageManager) { const pm = packageManager?.name || "npm"; return ` try { await import("${entryUrl}"); } catch (err) { console.error( "[kirbyup] Couldn't connect to the development server. Run \`${pm} run serve\` to start Vite or build the plugin with \`${pm} run build\` so Kirby uses the production version." ); throw err; } `.trimStart(); } //#endregion export { kirbyupHmrPlugin as default };