one
Version:
One is a new React Framework that makes Vite serve both native and web.
185 lines (183 loc) • 7 kB
JavaScript
import { VIRTUAL_SSR_CSS_ENTRY, VIRTUAL_SSR_CSS_HREF } from "../../constants.native.js";
var cssCache = null,
routesPreWarmed = !1,
CSS_CACHE_TTL = 1e3;
function SSRCSSPlugin(pluginOpts) {
var server;
return {
name: "one-plugin-ssr-css",
apply: "serve",
configureServer(server_) {
server = server_;
var preWarmRoutes = async function () {
if (!routesPreWarmed) {
routesPreWarmed = !0;
try {
await server.transformRequest(pluginOpts.entries[0]);
var routeFiles = await collectRouteFiles(server, pluginOpts.entries);
await Promise.all(routeFiles.map(function (file) {
return server.transformRequest(file).catch(function () {});
})), process.env.ONE_DEBUG && console.log(`[one] Pre-warmed ${routeFiles.length} route modules for CSS collection`);
} catch (err) {
console.error("[one] Error pre-warming routes:", err);
}
}
};
server.watcher.on("change", function () {
cssCache = null;
}), server.middlewares.use(async function (req, res, next) {
var _req_url;
if (!((_req_url = req.url) === null || _req_url === void 0) && _req_url.includes(VIRTUAL_SSR_CSS_HREF)) {
await preWarmRoutes(), invalidateModule(server, "\0" + VIRTUAL_SSR_CSS_ENTRY + "?direct");
var now = Date.now();
if (cssCache && now - cssCache.timestamp < CSS_CACHE_TTL) {
res.setHeader("Content-Type", "text/css"), res.setHeader("Cache-Control", "no-store"), res.setHeader("Vary", "*"), res.write(cssCache.css), res.end();
return;
}
var code = await collectStyle(server, pluginOpts.entries);
cssCache = {
css: code,
timestamp: now
}, res.setHeader("Content-Type", "text/css"), res.setHeader("Cache-Control", "no-store"), res.setHeader("Vary", "*"), res.write(code), res.end();
return;
}
next();
});
},
// virtual module
// (use `startsWith` since Vite adds `?direct` for raw css request)
resolveId(source, _importer, _options) {
return source.startsWith(VIRTUAL_SSR_CSS_ENTRY) ? "\0" + source : void 0;
},
async load(id, _options) {
if (id.startsWith("\0" + VIRTUAL_SSR_CSS_ENTRY)) {
var url = new URL(id.slice(1), "https://test.local"),
code = await collectStyle(server, pluginOpts.entries);
return url.searchParams.has("direct") || (code = `export default ${JSON.stringify(code)}`), code;
}
},
// also expose via transformIndexHtml
transformIndexHtml: {
handler: async function () {
return [{
tag: "link",
injectTo: "head",
attrs: {
rel: "stylesheet",
href: VIRTUAL_SSR_CSS_HREF,
"data-ssr-css": !0
}
}, {
tag: "script",
injectTo: "head",
attrs: {
type: "module"
},
children: (/* js */
`
import { createHotContext } from "/@vite/client";
const hot = createHotContext("/__clear_ssr_css");
hot.on("vite:afterUpdate", () => {
document
.querySelectorAll("[data-ssr-css]")
.forEach(node => node.remove());
});
`)
}];
}
}
};
}
function invalidateModule(server, id) {
var mod = server.moduleGraph.getModuleById(id);
mod && server.moduleGraph.invalidateModule(mod);
}
async function collectStyle(server, entries) {
var {
transform
} = await import("lightningcss"),
urls = await collectStyleUrls(server, entries),
codes = await Promise.all(urls.map(async function (url) {
var res = await server.transformRequest(url + "?direct"),
code = res?.code || "",
prefix = `/* [collectStyle] ${url} */`;
try {
var buffer2 = Buffer.from(code),
codeOut2 = new Uint8Array(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength),
processed = transform({
filename: "code.css",
code: codeOut2,
...server.config.css.lightningcss
}).code.toString();
return [prefix, processed];
} catch (err) {
return console.error(` [one] Error post-processing CSS, leaving un-processed: ${err}`), [prefix, code];
}
})),
out = codes.flat().filter(Boolean).join(`
`);
try {
var buffer = Buffer.from(out),
codeOut = new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
out = transform({
filename: "code.css",
code: codeOut,
...server.config.css.lightningcss
}).code.toString();
} catch {
console.error(" [one] Error post-processing merged CSS, leaving un-processed");
}
return out;
}
async function collectStyleUrls(server, entries) {
var visited = /* @__PURE__ */new Set();
async function traverse(url) {
var [, id] = await server.moduleGraph.resolveUrl(url);
if (!visited.has(id)) {
visited.add(id);
var mod = server.moduleGraph.getModuleById(id);
mod && (await Promise.all([...mod.importedModules].map(function (childMod) {
return traverse(childMod.url);
})));
}
}
return await Promise.all(entries.map(function (e) {
return server.transformRequest(e);
})), await Promise.all(entries.map(function (url) {
return traverse(url);
})), [...visited].filter(function (url) {
return url.match(CSS_LANGS_RE);
});
}
var CSS_LANGS_RE = /\.(css|less|sass|scss|styl|stylus|pcss|postcss|sss)(?:$|\?)/,
DYNAMIC_IMPORT_RE = /import\s*\(\s*["'`]([^"'`]+)["'`]\s*\)/g;
async function collectRouteFiles(server, entries) {
var routeFiles = [],
_iteratorNormalCompletion = !0,
_didIteratorError = !1,
_iteratorError = void 0;
try {
for (var _iterator = entries[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = !0) {
var entry = _step.value;
try {
var result = await server.transformRequest(entry);
if (!result?.code) continue;
for (var match = void 0; (match = DYNAMIC_IMPORT_RE.exec(result.code)) !== null;) {
var importPath = match[1];
importPath && !importPath.includes("node_modules") && !importPath.startsWith("\0") && !importPath.startsWith("virtual:") && (importPath.endsWith(".tsx") || importPath.endsWith(".ts") || importPath.endsWith(".jsx") || importPath.endsWith(".js")) && routeFiles.push(importPath);
}
} catch {}
}
} catch (err) {
_didIteratorError = !0, _iteratorError = err;
} finally {
try {
!_iteratorNormalCompletion && _iterator.return != null && _iterator.return();
} finally {
if (_didIteratorError) throw _iteratorError;
}
}
return routeFiles;
}
export { SSRCSSPlugin, collectStyle };
//# sourceMappingURL=SSRCSSPlugin.native.js.map