mirror of
https://github.com/Sevichecc/Urara-Blog.git
synced 2025-05-02 10:49:31 +08:00
1035 lines
31 KiB
Text
1035 lines
31 KiB
Text
'use strict';
|
|
|
|
Object.defineProperty(exports, '__esModule', { value: true });
|
|
|
|
const UnocssInspector = require('@unocss/inspector');
|
|
const core = require('@unocss/core');
|
|
const pluginutils = require('@rollup/pluginutils');
|
|
const config = require('@unocss/config');
|
|
const crypto = require('crypto');
|
|
const path = require('path');
|
|
const MagicString = require('magic-string');
|
|
const remapping = require('@ampproject/remapping');
|
|
const fs = require('fs');
|
|
const url = require('url');
|
|
|
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
|
|
|
|
const UnocssInspector__default = /*#__PURE__*/_interopDefaultLegacy(UnocssInspector);
|
|
const MagicString__default = /*#__PURE__*/_interopDefaultLegacy(MagicString);
|
|
const remapping__default = /*#__PURE__*/_interopDefaultLegacy(remapping);
|
|
const fs__default = /*#__PURE__*/_interopDefaultLegacy(fs);
|
|
|
|
const defaultExclude = [core.cssIdRE];
|
|
const defaultInclude = [/\.vue$/, /\.vue\?vue/, /\.svelte$/, /\.[jt]sx$/, /\.mdx?$/, /\.astro$/, /\.elm$/, /\.html$/];
|
|
|
|
const VIRTUAL_ENTRY_ALIAS = [
|
|
/^(?:virtual:)?uno(?::(.+))?\.css(\?.*)?$/
|
|
];
|
|
const LAYER_MARK_ALL = "__ALL__";
|
|
function resolveId(id) {
|
|
for (const alias of VIRTUAL_ENTRY_ALIAS) {
|
|
const match = id.match(alias);
|
|
if (match) {
|
|
return match[1] ? `/__uno_${match[1]}.css` : "/__uno.css";
|
|
}
|
|
}
|
|
}
|
|
const RESOLVED_ID_RE = /\/__uno(?:(_.*?))?\.css$/;
|
|
function resolveLayer(id) {
|
|
const match = id.match(RESOLVED_ID_RE);
|
|
if (match)
|
|
return match[1] || LAYER_MARK_ALL;
|
|
}
|
|
const LAYER_PLACEHOLDER_RE = /(\\?")?#--unocss--\s*{\s*layer\s*:\s*(.+?);?\s*}/g;
|
|
function getLayerPlaceholder(layer) {
|
|
return `#--unocss--{layer:${layer}}`;
|
|
}
|
|
const HASH_PLACEHOLDER_RE = /#--unocss-hash--\s*{\s*content\s*:\s*\\*"(.+?)\\*";?\s*}/g;
|
|
function getHashPlaceholder(hash) {
|
|
return `#--unocss-hash--{content:"${hash}"}`;
|
|
}
|
|
|
|
const INCLUDE_COMMENT = "@unocss-include";
|
|
const IGNORE_COMMENT = "@unocss-ignore";
|
|
const CSS_PLACEHOLDER = "@unocss-placeholder";
|
|
|
|
function createContext(configOrPath, defaults = {}, extraConfigSources = [], resolveConfigResult = () => {
|
|
}) {
|
|
let root = process.cwd();
|
|
let rawConfig = {};
|
|
const uno = core.createGenerator(rawConfig, defaults);
|
|
let rollupFilter = pluginutils.createFilter(defaultInclude, defaultExclude);
|
|
const invalidations = [];
|
|
const reloadListeners = [];
|
|
const modules = new core.BetterMap();
|
|
const tokens = /* @__PURE__ */ new Set();
|
|
const affectedModules = /* @__PURE__ */ new Set();
|
|
let ready = reloadConfig();
|
|
async function reloadConfig() {
|
|
const result = await config.loadConfig(root, configOrPath, extraConfigSources);
|
|
resolveConfigResult(result);
|
|
rawConfig = result.config;
|
|
uno.setConfig(rawConfig);
|
|
uno.config.envMode = "dev";
|
|
rollupFilter = pluginutils.createFilter(
|
|
rawConfig.include || defaultInclude,
|
|
rawConfig.exclude || defaultExclude
|
|
);
|
|
tokens.clear();
|
|
await Promise.all(modules.map((code, id) => uno.applyExtractors(code, id, tokens)));
|
|
invalidate();
|
|
dispatchReload();
|
|
const presets = /* @__PURE__ */ new Set();
|
|
uno.config.presets.forEach((i) => {
|
|
if (!i.name)
|
|
return;
|
|
if (presets.has(i.name))
|
|
console.warn(`[unocss] duplication of preset ${i.name} found, there might be something wrong with your config.`);
|
|
else
|
|
presets.add(i.name);
|
|
});
|
|
return result;
|
|
}
|
|
async function updateRoot(newRoot) {
|
|
if (newRoot !== root) {
|
|
root = newRoot;
|
|
ready = reloadConfig();
|
|
}
|
|
return await ready;
|
|
}
|
|
function invalidate() {
|
|
invalidations.forEach((cb) => cb());
|
|
}
|
|
function dispatchReload() {
|
|
reloadListeners.forEach((cb) => cb());
|
|
}
|
|
async function extract(code, id) {
|
|
if (id)
|
|
modules.set(id, code);
|
|
const len = tokens.size;
|
|
await uno.applyExtractors(code, id, tokens);
|
|
if (tokens.size > len)
|
|
invalidate();
|
|
}
|
|
const filter = (code, id) => {
|
|
if (code.includes(IGNORE_COMMENT))
|
|
return false;
|
|
return code.includes(INCLUDE_COMMENT) || code.includes(CSS_PLACEHOLDER) || rollupFilter(id);
|
|
};
|
|
async function getConfig() {
|
|
await ready;
|
|
return rawConfig;
|
|
}
|
|
return {
|
|
get ready() {
|
|
return ready;
|
|
},
|
|
tokens,
|
|
modules,
|
|
affectedModules,
|
|
invalidate,
|
|
onInvalidate(fn) {
|
|
invalidations.push(fn);
|
|
},
|
|
filter,
|
|
reloadConfig,
|
|
onReload(fn) {
|
|
reloadListeners.push(fn);
|
|
},
|
|
uno,
|
|
extract,
|
|
getConfig,
|
|
root,
|
|
updateRoot
|
|
};
|
|
}
|
|
|
|
function getPath(id) {
|
|
return id.replace(/\?.*$/, "");
|
|
}
|
|
|
|
function getHash(input, length = 8) {
|
|
return crypto.createHash("sha256").update(input).digest("hex").slice(0, length);
|
|
}
|
|
|
|
function replaceAsync(string, searchValue, replacer) {
|
|
try {
|
|
if (typeof replacer === "function") {
|
|
const values = [];
|
|
String.prototype.replace.call(string, searchValue, (...args) => {
|
|
values.push(replacer(...args));
|
|
return "";
|
|
});
|
|
return Promise.all(values).then((resolvedValues) => {
|
|
return String.prototype.replace.call(string, searchValue, () => {
|
|
return resolvedValues.shift() || "";
|
|
});
|
|
});
|
|
} else {
|
|
return Promise.resolve(
|
|
String.prototype.replace.call(string, searchValue, replacer)
|
|
);
|
|
}
|
|
} catch (error) {
|
|
return Promise.reject(error);
|
|
}
|
|
}
|
|
|
|
function ChunkModeBuildPlugin({ uno, filter }) {
|
|
let cssPlugin;
|
|
const files = {};
|
|
return {
|
|
name: "unocss:chunk",
|
|
apply: "build",
|
|
enforce: "pre",
|
|
configResolved(config) {
|
|
cssPlugin = config.plugins.find((i) => i.name === "vite:css-post");
|
|
},
|
|
transform(code, id) {
|
|
if (!filter(code, id))
|
|
return;
|
|
files[id] = code;
|
|
return null;
|
|
},
|
|
async renderChunk(_, chunk) {
|
|
const chunks = Object.keys(chunk.modules).map((i) => files[i]).filter(Boolean);
|
|
if (!chunks.length)
|
|
return null;
|
|
const tokens = /* @__PURE__ */ new Set();
|
|
await Promise.all(chunks.map((c) => uno.applyExtractors(c, void 0, tokens)));
|
|
const { css } = await uno.generate(tokens);
|
|
const fakeCssId = `${chunk.fileName}.css`;
|
|
await cssPlugin.transform(css, fakeCssId);
|
|
chunk.modules[fakeCssId] = {
|
|
code: null,
|
|
originalLength: 0,
|
|
removedExports: [],
|
|
renderedExports: [],
|
|
renderedLength: 0
|
|
};
|
|
return null;
|
|
},
|
|
async transformIndexHtml(code) {
|
|
const { css } = await uno.generate(code);
|
|
if (css)
|
|
return `${code}<style>${css}</style>`;
|
|
}
|
|
};
|
|
}
|
|
|
|
function GlobalModeBuildPlugin({ uno, ready, extract, tokens, filter, getConfig }) {
|
|
const vfsLayers = /* @__PURE__ */ new Set();
|
|
const layerImporterMap = /* @__PURE__ */ new Map();
|
|
let tasks = [];
|
|
let viteConfig;
|
|
const cssPostPlugins = /* @__PURE__ */ new Map();
|
|
const cssPlugins = /* @__PURE__ */ new Map();
|
|
async function applyCssTransform(css, id, dir) {
|
|
const {
|
|
postcss = true
|
|
} = await getConfig();
|
|
if (!cssPlugins.get(dir) || !postcss)
|
|
return css;
|
|
const result = await cssPlugins.get(dir).transform(css, id);
|
|
if (!result)
|
|
return css;
|
|
if (typeof result === "string")
|
|
css = result;
|
|
else if (result.code)
|
|
css = result.code;
|
|
css = css.replace(/[\n\r]/g, "");
|
|
return css;
|
|
}
|
|
let lastTokenSize = 0;
|
|
let lastResult;
|
|
async function generateAll() {
|
|
await Promise.all(tasks);
|
|
if (lastResult && lastTokenSize === tokens.size)
|
|
return lastResult;
|
|
lastResult = await uno.generate(tokens, { minify: true });
|
|
lastTokenSize = tokens.size;
|
|
return lastResult;
|
|
}
|
|
return [
|
|
{
|
|
name: "unocss:global:build:scan",
|
|
apply: "build",
|
|
enforce: "pre",
|
|
buildStart() {
|
|
tasks = [];
|
|
lastTokenSize = 0;
|
|
lastResult = void 0;
|
|
},
|
|
transform(code, id) {
|
|
if (filter(code, id))
|
|
tasks.push(extract(code, id));
|
|
return null;
|
|
},
|
|
transformIndexHtml: {
|
|
enforce: "pre",
|
|
transform(code, { filename }) {
|
|
tasks.push(extract(code, filename));
|
|
}
|
|
},
|
|
resolveId(id, importer) {
|
|
const entry = resolveId(id);
|
|
if (entry) {
|
|
const layer = resolveLayer(entry);
|
|
if (layer) {
|
|
vfsLayers.add(layer);
|
|
if (importer)
|
|
layerImporterMap.set(importer, entry);
|
|
}
|
|
return entry;
|
|
}
|
|
},
|
|
load(id) {
|
|
const layer = resolveLayer(getPath(id));
|
|
if (layer)
|
|
return getLayerPlaceholder(layer);
|
|
},
|
|
moduleParsed({ id, importedIds }) {
|
|
if (!layerImporterMap.has(id))
|
|
return;
|
|
const layerKey = layerImporterMap.get(id);
|
|
if (!importedIds.includes(layerKey)) {
|
|
layerImporterMap.delete(id);
|
|
vfsLayers.delete(resolveLayer(layerKey));
|
|
}
|
|
},
|
|
async configResolved(config) {
|
|
const distDir = path.resolve(config.root, config.build.outDir);
|
|
cssPostPlugins.set(distDir, config.plugins.find((i) => i.name === "vite:css-post"));
|
|
cssPlugins.set(distDir, config.plugins.find((i) => i.name === "vite:css"));
|
|
await ready;
|
|
},
|
|
async renderChunk(_, chunk, options) {
|
|
if (!Object.keys(chunk.modules).some((i) => i.match(RESOLVED_ID_RE)))
|
|
return null;
|
|
const cssPost = cssPostPlugins.get(options.dir);
|
|
if (!cssPost) {
|
|
this.warn("[unocss] failed to find vite:css-post plugin. It might be an internal bug of UnoCSS");
|
|
return null;
|
|
}
|
|
let { css } = await generateAll();
|
|
const fakeCssId = `${chunk.fileName}-unocss-hash.css`;
|
|
css = await applyCssTransform(css, fakeCssId, options.dir);
|
|
const hash = getHash(css);
|
|
await cssPost.transform.call({}, getHashPlaceholder(hash), fakeCssId);
|
|
chunk.modules[fakeCssId] = {
|
|
code: null,
|
|
originalLength: 0,
|
|
removedExports: [],
|
|
renderedExports: [],
|
|
renderedLength: 0
|
|
};
|
|
return null;
|
|
}
|
|
},
|
|
{
|
|
name: "unocss:global:build:generate",
|
|
apply(options, { command }) {
|
|
return command === "build" && !options.build?.ssr;
|
|
},
|
|
configResolved(config) {
|
|
viteConfig = config;
|
|
},
|
|
enforce: "post",
|
|
async generateBundle(options, bundle) {
|
|
const checkJs = ["umd", "amd", "iife"].includes(options.format);
|
|
const files = Object.keys(bundle).filter((i) => i.endsWith(".css") || checkJs && i.endsWith(".js"));
|
|
if (!files.length)
|
|
return;
|
|
if (!vfsLayers.size) {
|
|
const msg = "[unocss] entry module not found, have you add `import 'uno.css'` in your main entry?";
|
|
this.warn(msg);
|
|
return;
|
|
}
|
|
const result = await generateAll();
|
|
let replaced = false;
|
|
for (const file of files) {
|
|
const chunk = bundle[file];
|
|
if (chunk.type === "asset" && typeof chunk.source === "string") {
|
|
const css = chunk.source.replace(HASH_PLACEHOLDER_RE, "");
|
|
chunk.source = await replaceAsync(css, LAYER_PLACEHOLDER_RE, async (_, __, layer) => {
|
|
replaced = true;
|
|
return await applyCssTransform(layer === LAYER_MARK_ALL ? result.getLayers(void 0, Array.from(vfsLayers)) : result.getLayer(layer) || "", `${chunk.fileName}.css`, options.dir);
|
|
});
|
|
} else if (chunk.type === "chunk" && typeof chunk.code === "string") {
|
|
const js = chunk.code.replace(HASH_PLACEHOLDER_RE, "");
|
|
chunk.code = await replaceAsync(js, LAYER_PLACEHOLDER_RE, async (_, __, layer) => {
|
|
replaced = true;
|
|
const css = layer === LAYER_MARK_ALL ? result.getLayers(void 0, Array.from(vfsLayers)) : result.getLayer(layer) || "";
|
|
return css.replace(/\n/g, "").replace(/(?<!\\)(['"])/g, "\\$1");
|
|
});
|
|
}
|
|
}
|
|
if (!replaced) {
|
|
let msg = "[unocss] does not found CSS placeholder in the generated chunks";
|
|
if (viteConfig.build.lib && checkJs)
|
|
msg += "\nIt seems you are building in library mode, it's recommanded to set `build.cssCodeSplit` to true.\nSee https://github.com/vitejs/vite/issues/1579";
|
|
else
|
|
msg += "\nThis is likely an internal bug of unocss vite plugin";
|
|
this.error(new Error(msg));
|
|
}
|
|
}
|
|
}
|
|
];
|
|
}
|
|
|
|
const WARN_TIMEOUT = 2e4;
|
|
const WS_EVENT_PREFIX = "unocss:hmr";
|
|
const HASH_LENGTH = 6;
|
|
function GlobalModeDevPlugin({ uno, tokens, affectedModules, onInvalidate, extract, filter }) {
|
|
const servers = [];
|
|
let base = "";
|
|
const tasks = [];
|
|
const entries = /* @__PURE__ */ new Set();
|
|
let invalidateTimer;
|
|
const lastServedHash = /* @__PURE__ */ new Map();
|
|
let lastServedTime = Date.now();
|
|
let resolved = false;
|
|
let resolvedWarnTimer;
|
|
function configResolved(config) {
|
|
base = config.base || "";
|
|
if (base === "/")
|
|
base = "";
|
|
else if (base.endsWith("/"))
|
|
base = base.slice(0, base.length - 1);
|
|
}
|
|
function invalidate(timer = 10, ids = entries) {
|
|
for (const server of servers) {
|
|
for (const id of ids) {
|
|
const mod = server.moduleGraph.getModuleById(id);
|
|
if (!mod)
|
|
continue;
|
|
server.moduleGraph.invalidateModule(mod);
|
|
}
|
|
}
|
|
clearTimeout(invalidateTimer);
|
|
invalidateTimer = setTimeout(() => {
|
|
lastServedHash.clear();
|
|
sendUpdate(ids);
|
|
}, timer);
|
|
}
|
|
function sendUpdate(ids) {
|
|
for (const server of servers) {
|
|
server.ws.send({
|
|
type: "update",
|
|
updates: Array.from(ids).map((id) => {
|
|
const mod = server.moduleGraph.getModuleById(id);
|
|
if (!mod)
|
|
return null;
|
|
return {
|
|
acceptedPath: mod.url,
|
|
path: mod.url,
|
|
timestamp: lastServedTime,
|
|
type: "js-update"
|
|
};
|
|
}).filter(core.notNull)
|
|
});
|
|
}
|
|
}
|
|
function setWarnTimer() {
|
|
if (!resolved && !resolvedWarnTimer) {
|
|
resolvedWarnTimer = setTimeout(() => {
|
|
if (process.env.TEST || process.env.NODE_ENV === "test")
|
|
return;
|
|
if (!resolved) {
|
|
const msg = "[unocss] entry module not found, have you add `import 'uno.css'` in your main entry?";
|
|
console.warn(msg);
|
|
servers.forEach(({ ws }) => ws.send({
|
|
type: "error",
|
|
err: { message: msg, stack: "" }
|
|
}));
|
|
}
|
|
}, WARN_TIMEOUT);
|
|
}
|
|
}
|
|
onInvalidate(() => {
|
|
invalidate(10, /* @__PURE__ */ new Set([...entries, ...affectedModules]));
|
|
});
|
|
return [
|
|
{
|
|
name: "unocss:global",
|
|
apply: "serve",
|
|
enforce: "pre",
|
|
configResolved,
|
|
async configureServer(_server) {
|
|
servers.push(_server);
|
|
_server.ws.on(WS_EVENT_PREFIX, ([layer, hash]) => {
|
|
if (lastServedHash.get(layer) !== hash)
|
|
sendUpdate(entries);
|
|
});
|
|
},
|
|
buildStart() {
|
|
uno.generate("", { preflights: true });
|
|
},
|
|
transform(code, id) {
|
|
if (filter(code, id))
|
|
tasks.push(extract(code, id));
|
|
return null;
|
|
},
|
|
transformIndexHtml: {
|
|
enforce: "pre",
|
|
transform(code, { filename }) {
|
|
setWarnTimer();
|
|
tasks.push(extract(code, filename));
|
|
}
|
|
},
|
|
resolveId(id) {
|
|
const entry = resolveId(id);
|
|
if (entry) {
|
|
resolved = true;
|
|
entries.add(entry);
|
|
return entry;
|
|
}
|
|
},
|
|
async load(id) {
|
|
const layer = resolveLayer(getPath(id));
|
|
if (!layer)
|
|
return null;
|
|
await Promise.all(tasks);
|
|
const result = await uno.generate(tokens);
|
|
const css = layer === LAYER_MARK_ALL ? result.getLayers(void 0, Array.from(entries).map((i) => resolveLayer(i)).filter((i) => !!i)) : result.getLayer(layer);
|
|
const hash = getHash(css || "", HASH_LENGTH);
|
|
lastServedHash.set(layer, hash);
|
|
lastServedTime = Date.now();
|
|
return `/*${hash}*/${css}`;
|
|
}
|
|
},
|
|
{
|
|
name: "unocss:global:post",
|
|
configResolved,
|
|
apply(config, env) {
|
|
return env.command === "serve" && !config.build?.ssr;
|
|
},
|
|
enforce: "post",
|
|
transform(code, id) {
|
|
const layer = resolveLayer(getPath(id));
|
|
if (layer && code.includes("import.meta.hot")) {
|
|
return `${code}
|
|
if (import.meta.hot) {
|
|
try { await import.meta.hot.send('${WS_EVENT_PREFIX}', ['${layer}', __vite__css.slice(2,${2 + HASH_LENGTH})]); }
|
|
catch (e) { console.warn('[unocss-hmr]', e) }
|
|
if (!import.meta.url.includes('?'))
|
|
await new Promise(resolve => setTimeout(resolve, 100))
|
|
}`;
|
|
}
|
|
}
|
|
}
|
|
];
|
|
}
|
|
|
|
function GlobalModePlugin(ctx) {
|
|
return [
|
|
...GlobalModeBuildPlugin(ctx),
|
|
...GlobalModeDevPlugin(ctx)
|
|
];
|
|
}
|
|
|
|
const VIRTUAL_PREFIX = "/@unocss/";
|
|
const SCOPE_IMPORT_RE = / from (['"])(@unocss\/scope)\1/;
|
|
function PerModuleModePlugin({ uno, filter }) {
|
|
const moduleMap = /* @__PURE__ */ new Map();
|
|
let server;
|
|
const invalidate = (hash) => {
|
|
if (!server)
|
|
return;
|
|
const id = `${VIRTUAL_PREFIX}${hash}.css`;
|
|
const mod = server.moduleGraph.getModuleById(id);
|
|
if (!mod)
|
|
return;
|
|
server.moduleGraph.invalidateModule(mod);
|
|
server.ws.send({
|
|
type: "update",
|
|
updates: [{
|
|
acceptedPath: id,
|
|
path: id,
|
|
timestamp: +Date.now(),
|
|
type: "js-update"
|
|
}]
|
|
});
|
|
};
|
|
return [
|
|
{
|
|
name: "unocss:module-scope:pre",
|
|
enforce: "pre",
|
|
async transform(code, id) {
|
|
if (!filter(code, id))
|
|
return;
|
|
const hash = getHash(id);
|
|
const { css } = await uno.generate(code, {
|
|
id,
|
|
preflights: true
|
|
});
|
|
if (!css)
|
|
return null;
|
|
moduleMap.set(hash, [id, css]);
|
|
invalidate(hash);
|
|
return {
|
|
code: `import "${VIRTUAL_PREFIX}${hash}.css";${code}`,
|
|
map: null
|
|
};
|
|
}
|
|
},
|
|
{
|
|
name: "unocss:module-scope",
|
|
enforce: "post",
|
|
configureServer(_server) {
|
|
server = _server;
|
|
},
|
|
async transform(code, id) {
|
|
if (!filter(code, id))
|
|
return;
|
|
const hash = getHash(id);
|
|
const hasScope = code.match(SCOPE_IMPORT_RE);
|
|
const { css } = await uno.generate(code, { id, scope: hasScope ? `.${hash}` : void 0, preflights: false });
|
|
if (!css && !hasScope)
|
|
return null;
|
|
if (hasScope)
|
|
code = code.replace(SCOPE_IMPORT_RE, ` from 'data:text/javascript;base64,${Buffer.from(`export default () => "${hash}"`).toString("base64")}'`);
|
|
moduleMap.set(hash, [id, css]);
|
|
invalidate(hash);
|
|
return {
|
|
code: `import "${VIRTUAL_PREFIX}${hash}.css";${code}`,
|
|
map: null
|
|
};
|
|
},
|
|
resolveId(id) {
|
|
return id.startsWith(VIRTUAL_PREFIX) ? id : null;
|
|
},
|
|
load(id) {
|
|
if (!id.startsWith(VIRTUAL_PREFIX))
|
|
return null;
|
|
const hash = id.slice(VIRTUAL_PREFIX.length, -".css".length);
|
|
const [source, css] = moduleMap.get(hash) || [];
|
|
if (source)
|
|
this.addWatchFile(source);
|
|
return `
|
|
/* unocss ${source} */
|
|
${css}`;
|
|
}
|
|
}
|
|
];
|
|
}
|
|
|
|
function VueScopedPlugin({ uno, ready }) {
|
|
let filter = pluginutils.createFilter([/\.vue$/], defaultExclude);
|
|
async function transformSFC(code) {
|
|
const { css } = await uno.generate(code);
|
|
if (!css)
|
|
return null;
|
|
return `${code}
|
|
<style scoped>${css}</style>`;
|
|
}
|
|
return {
|
|
name: "unocss:vue-scoped",
|
|
enforce: "pre",
|
|
async configResolved() {
|
|
const { config } = await ready;
|
|
filter = pluginutils.createFilter(
|
|
config.include || [/\.vue$/],
|
|
config.exclude || defaultExclude
|
|
);
|
|
},
|
|
transform(code, id) {
|
|
if (!filter(id))
|
|
return;
|
|
return transformSFC(code);
|
|
},
|
|
handleHotUpdate(ctx) {
|
|
const read = ctx.read;
|
|
if (filter(ctx.file)) {
|
|
ctx.read = async () => {
|
|
const code = await read();
|
|
return await transformSFC(code) || code;
|
|
};
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function SvelteScopedPlugin({ uno, ready }) {
|
|
let filter = pluginutils.createFilter([/\.svelte$/], defaultExclude);
|
|
async function transformSFC(code) {
|
|
const { css } = await uno.generate(code);
|
|
if (!css)
|
|
return null;
|
|
if (code.match(/<style[^>]*>[\s\S]*?<\/style\s*>/))
|
|
return code.replace(/(<style[^>]*>)/, `$1${css}`);
|
|
return `${code}
|
|
<style>${css}</style>`;
|
|
}
|
|
return {
|
|
name: "unocss:svelte-scoped",
|
|
enforce: "pre",
|
|
async configResolved() {
|
|
const { config } = await ready;
|
|
filter = pluginutils.createFilter(
|
|
config.include || [/\.svelte$/],
|
|
config.exclude || defaultExclude
|
|
);
|
|
},
|
|
transform(code, id) {
|
|
if (!filter(id))
|
|
return;
|
|
return transformSFC(code);
|
|
},
|
|
handleHotUpdate(ctx) {
|
|
const read = ctx.read;
|
|
if (filter(ctx.file)) {
|
|
ctx.read = async () => {
|
|
const code = await read();
|
|
return await transformSFC(code) || code;
|
|
};
|
|
}
|
|
}
|
|
};
|
|
}
|
|
|
|
function ShadowDomModuleModePlugin({ uno }) {
|
|
const partExtractorRegex = /^part-\[(.+)]:/;
|
|
const nameRegexp = /<([^\s^!>]+)\s*([^>]*)>/;
|
|
const checkElement = (useParts, idxResolver, element) => {
|
|
if (!element)
|
|
return null;
|
|
const applyParts = useParts.filter((p) => element[2].includes(p.rule));
|
|
if (applyParts.length === 0)
|
|
return null;
|
|
const name = element[1];
|
|
const idx = idxResolver(name);
|
|
return {
|
|
name,
|
|
entries: applyParts.map(({ rule, part }) => [
|
|
`.${rule.replace(/[:[\]]/g, "\\$&")}::part(${part})`,
|
|
`${name}:nth-of-type(${idx})::part(${part})`
|
|
])
|
|
};
|
|
};
|
|
const idxMapFactory = () => {
|
|
const elementIdxMap = /* @__PURE__ */ new Map();
|
|
return {
|
|
idxResolver: (name) => {
|
|
let idx = elementIdxMap.get(name);
|
|
if (!idx) {
|
|
idx = 1;
|
|
elementIdxMap.set(name, idx);
|
|
}
|
|
return idx;
|
|
},
|
|
incrementIdx: (name) => {
|
|
elementIdxMap.set(name, elementIdxMap.get(name) + 1);
|
|
}
|
|
};
|
|
};
|
|
const transformWebComponent = async (code) => {
|
|
if (!code.match(CSS_PLACEHOLDER))
|
|
return code;
|
|
let { css, matched } = await uno.generate(code, {
|
|
preflights: true,
|
|
safelist: true
|
|
});
|
|
if (css && matched) {
|
|
const useParts = Array.from(matched).reduce((acc, rule) => {
|
|
const matcher = rule.match(partExtractorRegex);
|
|
if (matcher)
|
|
acc.push({ part: matcher[1], rule });
|
|
return acc;
|
|
}, new Array());
|
|
if (useParts.length > 0) {
|
|
let useCode = code;
|
|
let element;
|
|
const partsToApply = /* @__PURE__ */ new Map();
|
|
const { idxResolver, incrementIdx } = idxMapFactory();
|
|
while (element = nameRegexp.exec(useCode)) {
|
|
const result = checkElement(
|
|
useParts,
|
|
idxResolver,
|
|
element
|
|
);
|
|
if (result) {
|
|
result.entries.forEach(([name, replacement]) => {
|
|
let list = partsToApply.get(name);
|
|
if (!list) {
|
|
list = [];
|
|
partsToApply.set(name, list);
|
|
}
|
|
list.push(replacement);
|
|
});
|
|
incrementIdx(result.name);
|
|
}
|
|
useCode = useCode.slice(element[0].length + 1);
|
|
}
|
|
if (partsToApply.size > 0) {
|
|
css = Array.from(partsToApply.entries()).reduce((k, [r, name]) => {
|
|
return k.replace(r, name.join(",\n"));
|
|
}, css);
|
|
}
|
|
}
|
|
}
|
|
return code.replace(CSS_PLACEHOLDER, css?.replace(/\\/g, "\\\\") ?? "");
|
|
};
|
|
return {
|
|
name: "unocss:shadow-dom",
|
|
enforce: "pre",
|
|
async transform(code) {
|
|
return transformWebComponent(code);
|
|
},
|
|
handleHotUpdate(ctx) {
|
|
const read = ctx.read;
|
|
ctx.read = async () => {
|
|
const code = await read();
|
|
return await transformWebComponent(code);
|
|
};
|
|
}
|
|
};
|
|
}
|
|
|
|
function ConfigHMRPlugin(ctx) {
|
|
const { ready, uno } = ctx;
|
|
return {
|
|
name: "unocss:config",
|
|
async configResolved(config) {
|
|
await ctx.updateRoot(config.root);
|
|
},
|
|
async configureServer(server) {
|
|
uno.config.envMode = "dev";
|
|
const { sources } = await ready;
|
|
if (!sources.length)
|
|
return;
|
|
server.watcher.add(sources);
|
|
server.watcher.on("change", async (p) => {
|
|
if (!sources.includes(p))
|
|
return;
|
|
await ctx.reloadConfig();
|
|
server.ws.send({
|
|
type: "custom",
|
|
event: "unocss:config-changed"
|
|
});
|
|
});
|
|
}
|
|
};
|
|
}
|
|
|
|
async function applyTransformers(ctx, original, id, enforce = "default") {
|
|
if (original.includes(IGNORE_COMMENT))
|
|
return;
|
|
const transformers = (ctx.uno.config.transformers || []).filter((i) => (i.enforce || "default") === enforce);
|
|
if (!transformers.length)
|
|
return;
|
|
let code = original;
|
|
let s = new MagicString__default(code);
|
|
const maps = [];
|
|
for (const t of transformers) {
|
|
if (t.idFilter) {
|
|
if (!t.idFilter(id))
|
|
continue;
|
|
} else if (!ctx.filter(code, id)) {
|
|
continue;
|
|
}
|
|
await t.transform(s, id, ctx);
|
|
if (s.hasChanged()) {
|
|
code = s.toString();
|
|
maps.push(s.generateMap({ hires: true, source: id }));
|
|
s = new MagicString__default(code);
|
|
}
|
|
}
|
|
if (code !== original) {
|
|
ctx.affectedModules.add(id);
|
|
return {
|
|
code,
|
|
map: remapping__default(maps, () => null)
|
|
};
|
|
}
|
|
}
|
|
|
|
function createTransformerPlugins(ctx) {
|
|
const enforces = ["default", "pre", "post"];
|
|
return enforces.map((enforce) => ({
|
|
name: `unocss:transformers:${enforce}`,
|
|
enforce: enforce === "default" ? void 0 : enforce,
|
|
transform(code, id) {
|
|
return applyTransformers(ctx, code, id, enforce);
|
|
},
|
|
transformIndexHtml: {
|
|
enforce: enforce === "default" ? void 0 : enforce,
|
|
transform(code) {
|
|
return applyTransformers(ctx, code, "index.html", enforce).then((t) => t?.code);
|
|
}
|
|
}
|
|
}));
|
|
}
|
|
|
|
const _dirname = typeof __dirname !== "undefined" ? __dirname : path.dirname(url.fileURLToPath((typeof document === 'undefined' ? new (require('u' + 'rl').URL)('file:' + __filename).href : (document.currentScript && document.currentScript.src || new URL('index.cjs', document.baseURI).href))));
|
|
const DEVTOOLS_MODULE_ID = "virtual:unocss-devtools";
|
|
const MOCK_CLASSES_MODULE_ID = "virtual:unocss-mock-classes";
|
|
const MOCK_CLASSES_PATH = "/@unocss/mock-classes";
|
|
const DEVTOOLS_PATH = "/@unocss/devtools";
|
|
const DEVTOOLS_CSS_PATH = "/@unocss/devtools.css";
|
|
const devtoolCss = /* @__PURE__ */ new Set();
|
|
const MODULES_MAP = {
|
|
[DEVTOOLS_MODULE_ID]: DEVTOOLS_PATH,
|
|
[MOCK_CLASSES_MODULE_ID]: MOCK_CLASSES_PATH
|
|
};
|
|
const POST_PATH = "/@unocss-devtools-update";
|
|
function getBodyJson(req) {
|
|
return new Promise((resolve2, reject) => {
|
|
let body = "";
|
|
req.on("data", (chunk) => body += chunk);
|
|
req.on("error", reject);
|
|
req.on("end", () => {
|
|
try {
|
|
resolve2(JSON.parse(body) || {});
|
|
} catch (e) {
|
|
reject(e);
|
|
}
|
|
});
|
|
});
|
|
}
|
|
function createDevtoolsPlugin(ctx) {
|
|
let config;
|
|
let server;
|
|
let clientCode = "";
|
|
let devtoolTimer;
|
|
let lastUpdate = Date.now();
|
|
function toClass(name) {
|
|
return `${core.toEscapedSelector(name)}{}`;
|
|
}
|
|
function updateDevtoolClass() {
|
|
clearTimeout(devtoolTimer);
|
|
devtoolTimer = setTimeout(() => {
|
|
lastUpdate = Date.now();
|
|
if (!server)
|
|
return;
|
|
const mod = server.moduleGraph.getModuleById(DEVTOOLS_CSS_PATH);
|
|
if (!mod)
|
|
return;
|
|
server.moduleGraph.invalidateModule(mod);
|
|
server.ws.send({
|
|
type: "update",
|
|
updates: [{
|
|
acceptedPath: DEVTOOLS_CSS_PATH,
|
|
path: DEVTOOLS_CSS_PATH,
|
|
timestamp: lastUpdate,
|
|
type: "js-update"
|
|
}]
|
|
});
|
|
}, 100);
|
|
}
|
|
async function getMockClassesInjector() {
|
|
const suggest = Object.keys(ctx.uno.config.rulesStaticMap);
|
|
const comment = "/* unocss CSS mock class names for devtools auto-completion */\n";
|
|
const css = suggest.map(toClass).join("");
|
|
return `
|
|
const style = document.createElement('style')
|
|
style.setAttribute('type', 'text/css')
|
|
style.innerHTML = ${JSON.stringify(comment + css)}
|
|
document.head.prepend(style)
|
|
`;
|
|
}
|
|
return [
|
|
{
|
|
name: "unocss:devtools",
|
|
configResolved(_config) {
|
|
config = _config;
|
|
},
|
|
configureServer(_server) {
|
|
server = _server;
|
|
server.middlewares.use(async (req, res, next) => {
|
|
if (req.url !== POST_PATH)
|
|
return next();
|
|
try {
|
|
const data = await getBodyJson(req);
|
|
const type = data?.type;
|
|
let changed = false;
|
|
switch (type) {
|
|
case "add-classes":
|
|
data.data.forEach((key) => {
|
|
if (!devtoolCss.has(key)) {
|
|
devtoolCss.add(key);
|
|
changed = true;
|
|
}
|
|
});
|
|
if (changed)
|
|
updateDevtoolClass();
|
|
}
|
|
res.statusCode = 200;
|
|
} catch (e) {
|
|
console.error(e);
|
|
res.statusCode = 500;
|
|
}
|
|
res.end();
|
|
});
|
|
},
|
|
resolveId(id) {
|
|
if (id === DEVTOOLS_CSS_PATH)
|
|
return DEVTOOLS_CSS_PATH;
|
|
return MODULES_MAP[id];
|
|
},
|
|
async load(id) {
|
|
if (id === DEVTOOLS_PATH) {
|
|
if (!clientCode) {
|
|
clientCode = [
|
|
await fs__default.promises.readFile(path.resolve(_dirname, "client.mjs"), "utf-8"),
|
|
`import('${MOCK_CLASSES_MODULE_ID}')`,
|
|
`import('${DEVTOOLS_CSS_PATH}')`
|
|
].join("\n").replace("__POST_PATH__", (config.server?.origin ?? "") + POST_PATH);
|
|
}
|
|
return config.command === "build" ? "" : clientCode;
|
|
} else if (id === MOCK_CLASSES_PATH) {
|
|
return await getMockClassesInjector();
|
|
} else if (id === DEVTOOLS_CSS_PATH) {
|
|
const { css } = await ctx.uno.generate(devtoolCss);
|
|
return css;
|
|
}
|
|
}
|
|
}
|
|
];
|
|
}
|
|
|
|
function defineConfig(config) {
|
|
return config;
|
|
}
|
|
function UnocssPlugin(configOrPath, defaults = {}) {
|
|
const ctx = createContext(configOrPath, defaults);
|
|
const inlineConfig = configOrPath && typeof configOrPath !== "string" ? configOrPath : {};
|
|
const mode = inlineConfig.mode ?? "global";
|
|
const plugins = [
|
|
ConfigHMRPlugin(ctx),
|
|
...createTransformerPlugins(ctx),
|
|
...createDevtoolsPlugin(ctx)
|
|
];
|
|
if (inlineConfig.inspector !== false)
|
|
plugins.push(UnocssInspector__default(ctx));
|
|
if (mode === "per-module") {
|
|
plugins.push(...PerModuleModePlugin(ctx));
|
|
} else if (mode === "vue-scoped") {
|
|
plugins.push(VueScopedPlugin(ctx));
|
|
} else if (mode === "svelte-scoped") {
|
|
plugins.push(SvelteScopedPlugin(ctx));
|
|
} else if (mode === "shadow-dom") {
|
|
plugins.push(ShadowDomModuleModePlugin(ctx));
|
|
} else if (mode === "global") {
|
|
plugins.push(...GlobalModePlugin(ctx));
|
|
} else if (mode === "dist-chunk") {
|
|
plugins.push(
|
|
ChunkModeBuildPlugin(ctx),
|
|
...GlobalModeDevPlugin(ctx)
|
|
);
|
|
} else {
|
|
throw new Error(`[unocss] unknown mode "${mode}"`);
|
|
}
|
|
return plugins.filter(Boolean);
|
|
}
|
|
|
|
exports.ChunkModeBuildPlugin = ChunkModeBuildPlugin;
|
|
exports.GlobalModeBuildPlugin = GlobalModeBuildPlugin;
|
|
exports.GlobalModeDevPlugin = GlobalModeDevPlugin;
|
|
exports.GlobalModePlugin = GlobalModePlugin;
|
|
exports.PerModuleModePlugin = PerModuleModePlugin;
|
|
exports.SvelteScopedPlugin = SvelteScopedPlugin;
|
|
exports.VueScopedPlugin = VueScopedPlugin;
|
|
exports["default"] = UnocssPlugin;
|
|
exports.defineConfig = defineConfig;
|