@qwik.dev/core
Version:
An open source framework for building instant loading web apps at any scale, without the extra effort.
84 lines (83 loc) • 2.88 kB
JavaScript
import { existsSync as w, mkdirSync as _ } from "node:fs";
import { readFile as y, writeFile as v } from "node:fs/promises";
import { resolve as k, join as $ } from "node:path";
const q = (r, ...o) => {
console.warn("\x1B[33m%s\x1B[0m", `qwikInsight()[WARN]: ${r}`, ...o);
}, b = (r) => {
console.log("\x1B[35m%s\x1B[0m", `qwikInsight(): ${r}`);
};
async function F(r) {
const { publicApiKey: o, baseUrl: I = "https://insights.qwik.dev", outDir: h = "" } = r;
if (!o) {
console.warn("qwikInsights: publicApiKey is required, skipping...");
return;
}
let f = !1, u, n, i = null, l = null;
const g = `${I}/api/v1/${o}`, p = `${g}/post/`;
async function m() {
return i || (w(n) ? (b("Reading Qwik Insight data from: " + n), i = JSON.parse(await y(n, "utf-8"))) : null);
}
return {
name: "vite-plugin-qwik-insights",
enforce: "pre",
// Only activate in production builds
apply: "build",
async config(s) {
return u = k(s.root || ".", h), n = $(u, "q-insights.json"), f = s.mode !== "ssr", {
define: {
"globalThis.__QI_KEY__": JSON.stringify(o),
"globalThis.__QI_URL__": JSON.stringify(p)
}
};
},
configResolved: {
// we want to register the bundle graph adder last so we overwrite existing routes
order: "post",
async handler(s) {
if (l = s.plugins.find(
(t) => t.name === "vite-plugin-qwik"
), !l)
throw new Error("Missing vite-plugin-qwik");
const c = l.api.getOptions();
if (f)
try {
const t = { manual: {}, prefetch: [] }, a = await (await fetch(`${g}/bundles/strategy/`)).json();
Object.assign(t, a), i = t, _(u, { recursive: !0 }), b("Fetched latest Qwik Insight data into: " + n), await v(n, JSON.stringify(t));
} catch (t) {
q(`Failed to fetch manifest from Insights DB at ${g}/bundles/strategy/`, t), await m();
}
else
await m();
i && (c.entryStrategy.manual = {
...i.manual,
...c.entryStrategy.manual
}, l.api.registerBundleGraphAdder((t) => {
const d = {};
for (const a of i?.prefetch || [])
if (a.symbols) {
let e = a.route;
e.startsWith("/") && (e = e.slice(1)), e.endsWith("/") || (e += "/"), d[e] = { ...t.bundles[e], imports: a.symbols };
}
return d;
}));
}
},
closeBundle: async () => {
const s = k(h, "q-manifest.json");
if (f && w(s)) {
const c = await y(s, "utf-8");
try {
await fetch(`${p}manifest`, {
method: "post",
body: c
});
} catch (t) {
q(`Failed to post manifest to Insights DB at ${p}manifest`, t);
}
}
}
};
}
export {
F as qwikInsights
};