index.mjs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435
  1. import path from 'node:path';
  2. import { promises } from 'node:fs';
  3. const defaultCacheDir = "node_modules/.vite";
  4. function viteBasicSslPlugin() {
  5. return {
  6. name: "vite:basic-ssl",
  7. async configResolved(config) {
  8. const certificate = await getCertificate((config.cacheDir ?? defaultCacheDir) + "/basic-ssl");
  9. const https = () => ({ cert: certificate, key: certificate });
  10. config.server.https = Object.assign({}, config.server.https, https());
  11. config.preview.https = Object.assign({}, config.preview.https, https());
  12. }
  13. };
  14. }
  15. async function getCertificate(cacheDir) {
  16. const cachePath = path.join(cacheDir, "_cert.pem");
  17. try {
  18. const [stat, content] = await Promise.all([
  19. promises.stat(cachePath),
  20. promises.readFile(cachePath, "utf8")
  21. ]);
  22. if (Date.now() - stat.ctime.valueOf() > 30 * 24 * 60 * 60 * 1e3) {
  23. throw new Error("cache is outdated.");
  24. }
  25. return content;
  26. } catch {
  27. const content = (await import('./chunks/certificate.mjs')).createCertificate();
  28. promises.mkdir(cacheDir, { recursive: true }).then(() => promises.writeFile(cachePath, content)).catch(() => {
  29. });
  30. return content;
  31. }
  32. }
  33. export { viteBasicSslPlugin as default, getCertificate };