import { createResolver, getRoots, isInstalledGlobally, resolveEntry, resolveImportPath, resolveImportUrl, toAtFS } from "./chunk-UNQ5DBLZ.js"; // package.json var version = "0.50.0"; // node/integrations/themes.ts import { join } from "node:path"; import fs from "fs-extra"; import { satisfies } from "semver"; var officialThemes = { "none": "", "default": "@slidev/theme-default", "seriph": "@slidev/theme-seriph", "apple-basic": "@slidev/theme-apple-basic", "shibainu": "@slidev/theme-shibainu", "bricks": "@slidev/theme-bricks" }; var resolveTheme = createResolver("theme", officialThemes); async function getThemeMeta(name, root) { const path4 = join(root, "package.json"); if (!fs.existsSync(path4)) return {}; const { slidev = {}, engines = {} } = await fs.readJSON(path4); if (engines.slidev && !satisfies(version, engines.slidev, { includePrerelease: true })) throw new Error(`[slidev] theme "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`); return slidev; } // node/parser.ts import * as parser from "@slidev/parser/fs"; // node/options.ts import path3 from "node:path"; import { objectMap as objectMap2, uniq as uniq5 } from "@antfu/utils"; import Debug from "debug"; import fg4 from "fast-glob"; import mm from "micromatch"; // node/integrations/addons.ts import { resolve } from "node:path"; import fs2 from "fs-extra"; import { satisfies as satisfies2 } from "semver"; async function resolveAddons(addonsInConfig) { const { userRoot, userPkgJson } = await getRoots(); const resolved = []; const resolveAddonNameAndRoot = createResolver("addon", {}); async function resolveAddon(name, parent) { const [, pkgRoot] = await resolveAddonNameAndRoot(name, parent); if (!pkgRoot) return; resolved.push(pkgRoot); const { slidev = {}, engines = {} } = await fs2.readJSON(resolve(pkgRoot, "package.json")); if (engines.slidev && !satisfies2(version, engines.slidev, { includePrerelease: true })) throw new Error(`[slidev] addon "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`); if (Array.isArray(slidev.addons)) await Promise.all(slidev.addons.map((addon) => resolveAddon(addon, pkgRoot))); } if (Array.isArray(addonsInConfig)) await Promise.all(addonsInConfig.map((addon) => resolveAddon(addon, userRoot))); if (Array.isArray(userPkgJson.slidev?.addons)) await Promise.all(userPkgJson.slidev.addons.map((addon) => resolveAddon(addon, userRoot))); return resolved; } // node/setups/indexHtml.ts import { existsSync as existsSync8, readFileSync as readFileSync2 } from "node:fs"; import { join as join13 } from "node:path"; import { slash as slash4 } from "@antfu/utils"; import { white, yellow as yellow2 } from "kolorist"; import { escapeHtml } from "markdown-it/lib/common/utils.mjs"; // node/commands/shared.ts import { existsSync as existsSync7 } from "node:fs"; import { join as join12 } from "node:path"; import MarkdownIt from "markdown-it"; import { loadConfigFromFile, mergeConfig as mergeConfig2 } from "vite"; // node/syntax/markdown-it/markdown-it-link.ts function MarkdownItLink(md) { const defaultRender = md.renderer.rules.link_open ?? ((tokens, idx, options, _env, self) => self.renderToken(tokens, idx, options)); md.renderer.rules.link_open = function(tokens, idx, options, env, self) { const token = tokens[idx]; const hrefIndex = token.attrIndex("href"); const attr = token.attrs?.[hrefIndex]; const href = attr?.[1] ?? ""; if ("./#".includes(href[0]) || /^\d+$/.test(href)) { token.tag = "Link"; attr[0] = "to"; for (let i = idx + 1; i < tokens.length; i++) { if (tokens[i].type === "link_close") { tokens[i].tag = "Link"; break; } } } else if (token.attrGet("target") == null) { token.attrPush(["target", "_blank"]); } return defaultRender(tokens, idx, options, env, self); }; } // node/utils.ts import { fileURLToPath } from "node:url"; import { createJiti } from "jiti"; import YAML from "yaml"; var jiti; function loadModule(absolutePath) { jiti ??= createJiti(fileURLToPath(import.meta.url)); return jiti.import(absolutePath); } function stringifyMarkdownTokens(tokens) { return tokens.map((token) => token.children?.filter((t) => ["text", "code_inline"].includes(t.type) && !t.content.match(/^\s*$/)).map((t) => t.content.trim()).join(" ")).filter(Boolean).join(" "); } function generateGoogleFontsUrl(options) { const weights = options.weights.flatMap((i) => options.italic ? [`0,${i}`, `1,${i}`] : [`${i}`]).sort().join(";"); const fonts = options.webfonts.map((i) => `family=${i.replace(/^(['"])(.*)\1$/, "$1").replace(/\s+/g, "+")}:${options.italic ? "ital," : ""}wght@${weights}`).join("&"); return `https://fonts.googleapis.com/css2?${fonts}&display=swap`; } function updateFrontmatterPatch(slide, frontmatter) { const source = slide.source; let doc = source.frontmatterDoc; if (!doc) { source.frontmatterStyle = "frontmatter"; source.frontmatterDoc = doc = new YAML.Document({}); } for (const [key, value] of Object.entries(frontmatter)) { slide.frontmatter[key] = source.frontmatter[key] = value; if (value == null) { doc.delete(key); } else { const valueNode = doc.createNode(value); let found = false; YAML.visit(doc.contents, { Pair(_key, node, path4) { if (path4.length === 1 && YAML.isScalar(node.key) && node.key.value === key) { node.value = valueNode; found = true; return YAML.visit.BREAK; } } }); if (!found) { if (!YAML.isMap(doc.contents)) doc.contents = doc.createNode({}); doc.contents.add( doc.createPair(key, valueNode) ); } } } } function getBodyJson(req) { return new Promise((resolve9, reject) => { let body = ""; req.on("data", (chunk) => body += chunk); req.on("error", reject); req.on("end", () => { try { resolve9(JSON.parse(body) || {}); } catch (e) { reject(e); } }); }); } // node/vite/compilerFlagsVue.ts import { objectEntries } from "@antfu/utils"; function createVueCompilerFlagsPlugin(options) { const define = objectEntries(options.utils.define); return { name: "slidev:flags", enforce: "pre", transform(code, id) { if (!id.match(/\.vue($|\?)/) && !id.includes("?vue&")) return; const original = code; define.forEach(([from, to]) => { code = code.replaceAll(from, to); }); if (original !== code) return code; } }; } // node/vite/components.ts import { join as join2 } from "node:path"; import IconsResolver from "unplugin-icons/resolver"; import Components from "unplugin-vue-components/vite"; function createComponentsPlugin({ clientRoot, roots }, pluginOptions) { return Components({ extensions: ["vue", "md", "js", "ts", "jsx", "tsx"], dirs: [ join2(clientRoot, "builtin"), ...roots.map((i) => join2(i, "components")) ], include: [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/, /\.md$/, /\.md\?vue/], exclude: [], resolvers: [ IconsResolver({ prefix: "", customCollections: Object.keys(pluginOptions.icons?.customCollections || []) }) ], dts: false, ...pluginOptions.components }); } // node/vite/common.ts var regexSlideReqPath = /^\/__slidev\/slides\/(\d+)\.json$/; var regexSlideFacadeId = /^\/@slidev\/slides\/(\d+)\/(md|frontmatter)($|\?)/; var regexSlideSourceId = /__slidev_(\d+)\.(md|frontmatter)$/; var templateInjectionMarker = "/* @slidev-injection */"; var templateImportContextUtils = `import { useSlideContext as _useSlideContext, frontmatterToProps as _frontmatterToProps } from "@slidev/client/context.ts"`; var templateInitContext = `const { $slidev, $nav, $clicksContext, $clicks, $page, $renderContext, $frontmatter } = _useSlideContext()`; // node/vite/contextInjection.ts function createContextInjectionPlugin() { return { name: "slidev:context-injection", async transform(code, id) { if (!id.endsWith(".vue") || id.includes("/@slidev/client/") || id.includes("/packages/client/")) return; if (code.includes(templateInjectionMarker) || code.includes("useSlideContext()")) return code; const imports = [ templateImportContextUtils, templateInitContext, templateInjectionMarker ]; const matchScript = code.match(//); if (matchScript && matchScript[2]) { return code.replace(/()/g, `$1 ${imports.join("\n")} `); } else if (matchScript && !matchScript[2]) { const matchExport = code.match(/export\s+default\s+\{/); if (matchExport) { const exportIndex = (matchExport.index || 0) + matchExport[0].length; let component = code.slice(exportIndex); component = component.slice(0, component.indexOf("")); const scriptIndex = (matchScript.index || 0) + matchScript[0].length; const provideImport = '\nimport { injectionSlidevContext } from "@slidev/client/constants.ts"\n'; code = `${code.slice(0, scriptIndex)}${provideImport}${code.slice(scriptIndex)}`; let injectIndex = exportIndex + provideImport.length; let injectObject = "$slidev: { from: injectionSlidevContext },"; const matchInject = component.match(/.*inject\s*:\s*([[{])/); if (matchInject) { injectIndex += (matchInject.index || 0) + matchInject[0].length; if (matchInject[1] === "[") { let injects = component.slice((matchInject.index || 0) + matchInject[0].length); const injectEndIndex = injects.indexOf("]"); injects = injects.slice(0, injectEndIndex); injectObject += injects.split(",").map((inject) => `${inject}: {from: ${inject}}`).join(","); return `${code.slice(0, injectIndex - 1)}{ ${injectObject} }${code.slice(injectIndex + injectEndIndex + 1)}`; } else { return `${code.slice(0, injectIndex)} ${injectObject} ${code.slice(injectIndex)}`; } } return `${code.slice(0, injectIndex)} inject: { ${injectObject} }, ${code.slice(injectIndex)}`; } } return ` ${code}`; } }; } // node/vite/extendConfig.ts import { join as join3 } from "node:path"; import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url"; import { slash, uniq } from "@antfu/utils"; import { createResolve } from "mlly"; import { mergeConfig } from "vite"; var INCLUDE_GLOBAL = [ "@typescript/ata", "file-saver", "lz-string", "prettier", "recordrtc", "typescript", "yaml", "html-to-image" ]; var INCLUDE_LOCAL = INCLUDE_GLOBAL.map((i) => `@slidev/cli > @slidev/client > ${i}`); var EXCLUDE_GLOBAL = [ "@antfu/utils", "@shikijs/monaco", "@shikijs/vitepress-twoslash/client", "@slidev/client", "@slidev/client/constants", "@slidev/client/context", "@slidev/client/logic/dark", "@slidev/parser", "@slidev/parser/core", "@slidev/rough-notation", "@slidev/types", "@unhead/vue", "@unocss/reset", "@vueuse/core", "@vueuse/math", "@vueuse/motion", "@vueuse/shared", "drauu", "floating-vue", "fuse.js", "mermaid", "monaco-editor", "shiki-magic-move/vue", "shiki", "shiki/core", "vue-demi", "vue-router", "vue" ]; var EXCLUDE_LOCAL = EXCLUDE_GLOBAL; var ASYNC_MODULES = [ "file-saver", "vue", "@vue" ]; function createConfigPlugin(options) { const resolveClientDep = createResolve({ // Same as Vite's default resolve conditions conditions: ["import", "module", "browser", "default", options.mode === "build" ? "production" : "development"], url: pathToFileURL(options.clientRoot) }); return { name: "slidev:config", async config(config) { const injection = { define: options.utils.define, resolve: { alias: [ { find: /^@slidev\/client$/, replacement: `${toAtFS(options.clientRoot)}/index.ts` }, { find: /^@slidev\/client\/(.*)/, replacement: `${toAtFS(options.clientRoot)}/$1` }, { find: /^#slidev\/(.*)/, replacement: "/@slidev/$1" }, { find: "vue", replacement: await resolveImportPath("vue/dist/vue.esm-bundler.js", true) }, ...isInstalledGlobally.value ? await Promise.all(INCLUDE_GLOBAL.map(async (dep) => ({ find: dep, replacement: fileURLToPath2(await resolveClientDep(dep)) }))) : [] ], dedupe: ["vue"] }, optimizeDeps: isInstalledGlobally.value ? { exclude: EXCLUDE_GLOBAL, include: INCLUDE_GLOBAL } : { // We need to specify the full deps path for non-hoisted modules exclude: EXCLUDE_LOCAL, include: INCLUDE_LOCAL }, css: { postcss: { plugins: [ await import("postcss-nested").then((r) => (r.default || r)()) ] } }, server: { fs: { strict: true, allow: uniq([ options.userWorkspaceRoot, options.clientRoot, // Special case for PNPM global installation isInstalledGlobally.value ? slash(options.cliRoot).replace(/\/\.pnpm\/.*$/gi, "") : options.cliRoot, ...options.roots ]) } }, publicDir: join3(options.userRoot, "public"), build: { rollupOptions: { output: { chunkFileNames(chunkInfo) { const DEFAULT = "assets/[name]-[hash].js"; if (chunkInfo.name.includes("/")) return DEFAULT; if (chunkInfo.moduleIds.filter((i) => isSlidevClient(i)).length > chunkInfo.moduleIds.length * 0.6) return "assets/slidev/[name]-[hash].js"; if (chunkInfo.moduleIds.filter((i) => i.match(/\/monaco-editor(-core)?\//)).length > chunkInfo.moduleIds.length * 0.6) return "assets/monaco/[name]-[hash].js"; return DEFAULT; }, manualChunks(id) { if (id.startsWith("/@slidev-monaco-types/") || id.includes("/@slidev/monaco-types") || id.endsWith("?monaco-types&raw")) return "monaco/bundled-types"; if (id.includes("/shiki/") || id.includes("/@shikijs/")) return `modules/shiki`; if (id.startsWith("~icons/")) return "modules/unplugin-icons"; const matchedAsyncModule = ASYNC_MODULES.find((i) => id.includes(`/node_modules/${i}`)); if (matchedAsyncModule) return `modules/${matchedAsyncModule.replace("@", "").replace("/", "-")}`; } } } }, cacheDir: isInstalledGlobally.value ? join3(options.cliRoot, "node_modules/.vite") : void 0 }; function isSlidevClient(id) { return id.includes("/@slidev/") || id.includes("/slidev/packages/client/") || id.includes("/@vueuse/"); } return mergeConfig(injection, config); }, configureServer(server) { return () => { server.middlewares.use(async (req, res, next) => { if (req.url === "/index.html") { res.setHeader("Content-Type", "text/html"); res.statusCode = 200; res.end(options.utils.indexHtml); return; } next(); }); }; } }; } // node/vite/hmrPatch.ts function createHmrPatchPlugin() { return { name: "slidev:hmr-patch", transform(code, id) { if (!id.match(regexSlideSourceId)) return; return code.replace("if (_rerender_only)", "if (false)"); } }; } // node/vite/icons.ts import Icons from "unplugin-icons/vite"; function createIconsPlugin(options, pluginOptions) { return Icons({ defaultClass: "slidev-icon", collectionsNodeResolvePath: options.utils.iconsResolvePath, ...pluginOptions.icons }); } // node/vite/inspect.ts async function createInspectPlugin(options, pluginOptions) { if (!options.inspect) return; const { default: PluginInspect } = await import("vite-plugin-inspect"); return PluginInspect({ dev: true, build: true, ...pluginOptions.inspect }); } // node/vite/layoutWrapper.ts import { bold, gray, red, yellow } from "kolorist"; function createLayoutWrapperPlugin({ data, utils }) { return { name: "slidev:layout-wrapper", async transform(code, id) { const match = id.match(regexSlideSourceId); if (!match) return; const [, no, type] = match; if (type !== "md") return; const index = +no - 1; const layouts = utils.getLayouts(); const rawLayoutName = data.slides[index]?.frontmatter?.layout ?? data.slides[0]?.frontmatter?.defaults?.layout; let layoutName = rawLayoutName || (index === 0 ? "cover" : "default"); if (!layouts[layoutName]) { console.error(red(` Unknown layout "${bold(layoutName)}".${yellow(" Available layouts are:")}`) + Object.keys(layouts).map((i, idx) => (idx % 3 === 0 ? "\n " : "") + gray(i.padEnd(15, " "))).join(" ")); console.error(); layoutName = "default"; } const setupTag = code.match(/^ `; } }; // node/virtual/global-layers.ts import { existsSync } from "node:fs"; import { join as join4 } from "node:path"; var templateGlobalLayers = { id: `/@slidev/global-layers`, getContent({ roots }) { const imports = []; let n = 0; function getComponent(names) { const components = roots.flatMap((root) => names.map((name) => join4(root, name))).filter((i) => existsSync(i)); imports.push(components.map((path4, i) => `import __n${n}_${i} from '${toAtFS(path4)}'`).join("\n")); const render = components.map((_, i) => `h(__n${n}_${i})`).join(","); n++; return `{ render: () => [${render}] }`; } const globalTop = getComponent(["global.vue", "global-top.vue", "GlobalTop.vue"]); const globalBottom = getComponent(["global-bottom.vue", "GlobalBottom.vue"]); const slideTop = getComponent(["slide-top.vue", "SlideTop.vue"]); const slideBottom = getComponent(["slide-bottom.vue", "SlideBottom.vue"]); return [ imports.join("\n"), `import { h } from 'vue'`, `export const GlobalTop = ${globalTop}`, `export const GlobalBottom = ${globalBottom}`, `export const SlideTop = ${slideTop}`, `export const SlideBottom = ${slideBottom}` ].join("\n"); } }; // node/virtual/layouts.ts import { objectMap } from "@antfu/utils"; var templateLayouts = { id: "/@slidev/layouts", getContent({ utils }) { const imports = []; const layouts = objectMap( utils.getLayouts(), (k, v) => { imports.push(`import __layout_${k} from "${toAtFS(v)}"`); return [k, `__layout_${k}`]; } ); return [ imports.join("\n"), `export default { ${Object.entries(layouts).map(([k, v]) => `"${k}": ${v}`).join(",\n")} }` ].join("\n\n"); } }; // node/virtual/monaco-deps.ts import { resolve as resolve2 } from "node:path"; import { uniq as uniq2 } from "@antfu/utils"; var templateMonacoRunDeps = { id: "/@slidev/monaco-run-deps", async getContent({ userRoot, data }) { if (!data.features.monaco) return ""; const deps = uniq2(data.features.monaco.deps.concat(data.config.monacoTypesAdditionalPackages)); const importerPath = resolve2(userRoot, "./snippets/__importer__.ts"); let result = ""; for (let i = 0; i < deps.length; i++) { const specifier = deps[i]; const resolved = await this.resolve(specifier, importerPath); if (!resolved) continue; result += `import * as vendored${i} from ${JSON.stringify(resolved.id)} `; } result += "export default {\n"; for (let i = 0; i < deps.length; i++) result += `${JSON.stringify(deps[i])}: vendored${i}, `; result += "}\n"; return result; } }; // node/virtual/monaco-types.ts import { builtinModules } from "node:module"; import { join as join5, resolve as resolve3 } from "node:path"; import { uniq as uniq3 } from "@antfu/utils"; import fg from "fast-glob"; var templateMonacoTypes = { id: "/@slidev/monaco-types", getContent: async ({ userRoot, data, utils }) => { if (!data.features.monaco) return ""; const typesRoot = join5(userRoot, "snippets"); const files = await fg(["**/*.ts", "**/*.mts", "**/*.cts"], { cwd: typesRoot }); let result = 'import { addFile } from "@slidev/client/setup/monaco.ts"\n'; for (const file of files) { const url = `${toAtFS(resolve3(typesRoot, file))}?monaco-types&raw`; result += `addFile(() => import(${JSON.stringify(url)}), ${JSON.stringify(file)}) `; } function mapModuleNameToModule(moduleSpecifier) { if (moduleSpecifier.startsWith("node:")) return "node"; if (builtinModules.includes(moduleSpecifier)) return "node"; const mainPackageName = moduleSpecifier.split("/")[0]; if (builtinModules.includes(mainPackageName) && !mainPackageName.startsWith("@")) return "node"; const [a = "", b = ""] = moduleSpecifier.split("/"); const moduleName = a.startsWith("@") ? `${a}/${b}` : a; return moduleName; } let deps = [...data.config.monacoTypesAdditionalPackages]; if (data.config.monacoTypesSource === "local") deps.push(...data.features.monaco.types); deps = uniq3(deps.map((specifier) => { if (specifier[0] === ".") return ""; return mapModuleNameToModule(specifier); }).filter(Boolean)); deps = deps.filter((pkg) => !utils.isMonacoTypesIgnored(pkg)); for (const pkg of deps) { result += `import(${JSON.stringify(`/@slidev-monaco-types/resolve?${new URLSearchParams({ pkg })}`)}) `; } return result; } }; // node/virtual/nav-controls.ts import { existsSync as existsSync2 } from "node:fs"; import { join as join6 } from "node:path"; var templateNavControls = { id: "/@slidev/custom-nav-controls", getContent({ roots }) { const components = roots.flatMap((root) => { return [ join6(root, "custom-nav-controls.vue"), join6(root, "CustomNavControls.vue") ]; }).filter((i) => existsSync2(i)); const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n"); const render = components.map((i, idx) => `h(__n${idx})`).join(","); return `${imports} import { h } from 'vue' export default { render: () => [${render}], }`; } }; // node/virtual/setups.ts import { existsSync as existsSync3 } from "node:fs"; import { join as join7 } from "node:path"; function createSetupTemplate(name) { return { id: `/@slidev/setups/${name}`, getContent({ roots }) { const setups = roots.flatMap((i) => { const path4 = join7(i, "setup", name); return [".ts", ".mts", ".js", ".mjs"].map((ext) => path4 + ext); }).filter((i) => existsSync3(i)); const imports = []; setups.forEach((path4, idx) => { imports.push(`import __n${idx} from '${toAtFS(path4)}'`); }); imports.push(`export default [${setups.map((_, idx) => `__n${idx}`).join(",")}]`); return imports.join("\n"); } }; } var setupModules = ["shiki", "code-runners", "monaco", "mermaid", "main", "root", "routes", "shortcuts", "context-menu"]; var templateSetups = setupModules.map(createSetupTemplate); // node/virtual/shiki.ts import { uniq as uniq4 } from "@antfu/utils"; var templateShiki = { id: "/@slidev/shiki", getContent: async ({ utils }) => { const options = utils.shikiOptions; const langs = await resolveLangs(options.langs || ["markdown", "vue", "javascript", "typescript", "html", "css"]); const resolvedThemeOptions = "themes" in options ? { themes: Object.fromEntries(await Promise.all( Object.entries(options.themes).map(async ([name, value]) => [name, await resolveTheme2(value)]) )) } : { theme: await resolveTheme2(options.theme || "vitesse-dark") }; const themes = resolvedThemeOptions.themes ? Object.values(resolvedThemeOptions.themes) : [resolvedThemeOptions.theme]; const themeOptionsNames = resolvedThemeOptions.themes ? { themes: Object.fromEntries(Object.entries(resolvedThemeOptions.themes).map(([name, value]) => [name, typeof value === "string" ? value : value.name])) } : { theme: typeof resolvedThemeOptions.theme === "string" ? resolvedThemeOptions.theme : resolvedThemeOptions.theme.name }; async function normalizeGetter(p) { const r = typeof p === "function" ? p() : p; return r.default || r; } async function resolveLangs(langs2) { const awaited = await Promise.all(langs2.map((lang) => normalizeGetter(lang))); return uniq4(awaited.flat()); } async function resolveTheme2(theme) { return typeof theme === "string" ? theme : await normalizeGetter(theme); } const langsInit = await Promise.all( langs.map(async (lang) => typeof lang === "string" ? `import('${await resolveImportUrl(`shiki/langs/${lang}.mjs`)}')` : JSON.stringify(lang)) ); const themesInit = await Promise.all(themes.map(async (theme) => typeof theme === "string" ? `import('${await resolveImportUrl(`shiki/themes/${theme}.mjs`)}')` : JSON.stringify(theme))); const langNames = langs.flatMap((lang) => typeof lang === "string" ? lang : lang.name); const lines = []; lines.push( `import { createHighlighterCore } from "${await resolveImportUrl("shiki/core")}"`, `export { shikiToMonaco } from "${await resolveImportUrl("@shikijs/monaco")}"`, `export const languages = ${JSON.stringify(langNames)}`, `export const themes = ${JSON.stringify(themeOptionsNames.themes || themeOptionsNames.theme)}`, "export const shiki = createHighlighterCore({", ` themes: [${themesInit.join(",")}],`, ` langs: [${langsInit.join(",")}],`, ` loadWasm: import('${await resolveImportUrl("shiki/wasm")}'),`, "})", "let highlight", "export async function getHighlighter() {", " if (highlight) return highlight", " const highlighter = await shiki", " highlight = (code, lang, options) => highlighter.codeToHtml(code, {", " lang,", ` theme: ${JSON.stringify(themeOptionsNames.theme)},`, ` themes: ${JSON.stringify(themeOptionsNames.themes)},`, " defaultColor: false,", " ...options,", " })", " return highlight", "}" ); return lines.join("\n"); } }; // node/virtual/slides.ts var VIRTUAL_SLIDE_PREFIX = "/@slidev/slides/"; var templateSlides = { id: "/@slidev/slides", getContent({ data, utils }) { const layouts = utils.getLayouts(); const statements = [ `import { defineAsyncComponent, shallowRef } from 'vue'`, `import SlideError from '${layouts.error}'`, `import SlideLoading from '@slidev/client/internals/SlideLoading.vue'`, `const componentsCache = new Array(${data.slides.length})`, `const getAsyncComponent = (idx, loader) => defineAsyncComponent({`, ` loader,`, ` delay: 300,`, ` loadingComponent: SlideLoading,`, ` errorComponent: SlideError,`, ` onError: e => console.error('Failed to load slide ' + (idx + 1), e) `, `})` ]; const slides = data.slides.map((_, idx) => { const no = idx + 1; statements.push( `import { meta as f${no} } from '${VIRTUAL_SLIDE_PREFIX}${no}/frontmatter'`, // For some unknown reason, import error won't be caught by the error component. Catch it here. `const load${no} = async () => {`, ` try { return componentsCache[${idx}] ??= await import('${VIRTUAL_SLIDE_PREFIX}${no}/md') }`, ` catch (e) { console.error('slide failed to load', e); return SlideError }`, `}` ); return `{ no: ${no}, meta: f${no}, load: load${no}, component: getAsyncComponent(${idx}, load${no}) }`; }); return [ ...statements, `const data = [ ${slides.join(",\n")} ]`, `if (import.meta.hot) {`, ` import.meta.hot.data.slides ??= shallowRef()`, ` import.meta.hot.data.slides.value = data`, ` import.meta.hot.dispose(() => componentsCache.length = 0)`, ` import.meta.hot.accept()`, `}`, `export const slides = import.meta.hot ? import.meta.hot.data.slides : shallowRef(data)` ].join("\n"); } }; // node/virtual/styles.ts import { existsSync as existsSync4 } from "node:fs"; import { join as join8 } from "node:path"; var templateStyle = { id: "/@slidev/styles", async getContent({ data, clientRoot, roots }) { function resolveUrlOfClient(name) { return toAtFS(join8(clientRoot, name)); } const imports = [ `import "${resolveUrlOfClient("styles/vars.css")}"`, `import "${resolveUrlOfClient("styles/index.css")}"`, `import "${resolveUrlOfClient("styles/code.css")}"`, `import "${resolveUrlOfClient("styles/katex.css")}"`, `import "${resolveUrlOfClient("styles/transitions.css")}"` ]; for (const root of roots) { const styles = [ join8(root, "styles", "index.ts"), join8(root, "styles", "index.js"), join8(root, "styles", "index.css"), join8(root, "styles.css"), join8(root, "style.css") ]; for (const style of styles) { if (existsSync4(style)) { imports.push(`import "${toAtFS(style)}"`); continue; } } } if (data.features.katex) imports.push(`import "${await resolveImportUrl("katex/dist/katex.min.css")}"`); if (data.config.highlighter === "shiki") { imports.push( `import "${await resolveImportUrl("@shikijs/vitepress-twoslash/style.css")}"`, `import "${resolveUrlOfClient("styles/shiki-twoslash.css")}"`, `import "${await resolveImportUrl("shiki-magic-move/style.css")}"` ); } imports.unshift( `import "${await resolveImportUrl("@unocss/reset/tailwind.css")}"`, 'import "uno:preflights.css"', 'import "uno:typography.css"', 'import "uno:shortcuts.css"' ); imports.push('import "uno.css"'); return imports.join("\n"); } }; // node/virtual/titles.ts var templateTitleRendererMd = { id: "/@slidev/title-renderer.md", getContent({ data }) { const lines = data.slides.map(({ title }, i) => ``); lines.push( `` ); return lines.join("\n"); } }; var templateTitleRenderer = { id: "/@slidev/title-renderer", async getContent() { return 'export { default } from "/@slidev/title-renderer.md"'; } }; // node/virtual/index.ts var templates = [ templateShiki, templateMonacoTypes, templateMonacoRunDeps, templateConfigs, templateStyle, templateGlobalLayers, templateNavControls, templateSlides, templateLayouts, templateTitleRenderer, templateTitleRendererMd, ...templateSetups, // Deprecated templateLegacyRoutes, templateLegacyTitles ]; // node/vite/loaders.ts function renderNote(text = "") { let clickCount = 0; const html = sharedMd.render( text.replace(/\[click(?::(\d+))?\]/gi, (_, count = 1) => { clickCount += Number(count); return ``; }) ); return html; } function withRenderedNote(data) { return { ...data, noteHTML: renderNote(data?.note) }; } function createSlidesLoader(options, serverOptions) { const { data, mode, utils } = options; const hmrSlidesIndexes = /* @__PURE__ */ new Set(); let server; let skipHmr = null; let sourceIds = resolveSourceIds(data); function resolveSourceIds(data2) { const ids = { md: [], frontmatter: [] }; for (const type of ["md", "frontmatter"]) { for (let i = 0; i < data2.slides.length; i++) { ids[type].push(`${data2.slides[i].source.filepath}__slidev_${i + 1}.${type}`); } } return ids; } function updateServerWatcher() { if (!server) return; server.watcher.add(Object.keys(data.watchFiles)); } function getFrontmatter(pageNo) { return { ...data.headmatter?.defaults || {}, ...data.slides[pageNo]?.frontmatter || {} }; } return { name: "slidev:loader", enforce: "pre", configureServer(_server) { server = _server; updateServerWatcher(); server.middlewares.use(async (req, res, next) => { const match = req.url?.match(regexSlideReqPath); if (!match) return next(); const [, no] = match; const idx = Number.parseInt(no) - 1; if (req.method === "GET") { res.write(JSON.stringify(withRenderedNote(data.slides[idx]))); return res.end(); } else if (req.method === "POST") { const body = await getBodyJson(req); const slide = data.slides[idx]; if (body.content && body.content !== slide.source.content) hmrSlidesIndexes.add(idx); if (body.content) slide.content = slide.source.content = body.content; if (body.frontmatterRaw != null) { if (body.frontmatterRaw.trim() === "") { slide.source.frontmatterDoc = slide.source.frontmatterStyle = void 0; } else { const parsed = YAML2.parseDocument(body.frontmatterRaw); if (parsed.errors.length) console.error("ERROR when saving frontmatter", parsed.errors); else slide.source.frontmatterDoc = parsed; } } if (body.note) slide.note = slide.source.note = body.note; if (body.frontmatter) updateFrontmatterPatch(slide, body.frontmatter); parser2.prettifySlide(slide.source); const fileContent = await parser2.save(data.markdownFiles[slide.source.filepath]); if (body.skipHmr) { skipHmr = { filePath: slide.source.filepath, fileContent }; server?.moduleGraph.invalidateModule( server.moduleGraph.getModuleById(sourceIds.md[idx]) ); if (body.frontmatter) { server?.moduleGraph.invalidateModule( server.moduleGraph.getModuleById(sourceIds.frontmatter[idx]) ); } } res.statusCode = 200; res.write(JSON.stringify(withRenderedNote(slide))); return res.end(); } next(); }); }, async handleHotUpdate(ctx) { const forceChangedSlides = data.watchFiles[ctx.file]; if (!forceChangedSlides) return; for (const index of forceChangedSlides) { hmrSlidesIndexes.add(index); } const newData = await serverOptions.loadData?.({ [ctx.file]: await ctx.read() }); if (!newData) return []; if (skipHmr && newData.markdownFiles[skipHmr.filePath]?.raw === skipHmr.fileContent) { skipHmr = null; return []; } const moduleIds = /* @__PURE__ */ new Set(); const newSourceIds = resolveSourceIds(newData); for (const type of ["md", "frontmatter"]) { const old = sourceIds[type]; const newIds = newSourceIds[type]; for (let i = 0; i < newIds.length; i++) { if (old[i] !== newIds[i]) { moduleIds.add(`${VIRTUAL_SLIDE_PREFIX}${i + 1}/${type}`); } } } sourceIds = newSourceIds; if (data.slides.length !== newData.slides.length) { moduleIds.add(templateSlides.id); } if (!equal(data.headmatter.defaults, newData.headmatter.defaults)) { moduleIds.add(templateSlides.id); range(data.slides.length).map((i) => hmrSlidesIndexes.add(i)); } if (!equal(data.config, newData.config)) moduleIds.add(templateConfigs.id); if (!equal(data.features, newData.features)) { setTimeout(() => { ctx.server.hot.send({ type: "full-reload" }); }, 1); } const length = Math.min(data.slides.length, newData.slides.length); for (let i = 0; i < length; i++) { const a = data.slides[i]; const b = newData.slides[i]; if (!hmrSlidesIndexes.has(i) && a.content.trim() === b.content.trim() && a.title?.trim() === b.title?.trim() && equal(a.frontmatter, b.frontmatter)) { if (a.note !== b.note) { ctx.server.hot.send( "slidev:update-note", { no: i + 1, note: b.note || "", noteHTML: renderNote(b.note || "") } ); } continue; } ctx.server.hot.send( "slidev:update-slide", { no: i + 1, data: withRenderedNote(newData.slides[i]) } ); hmrSlidesIndexes.add(i); } Object.assign(data, newData); Object.assign(utils, createDataUtils(options)); if (hmrSlidesIndexes.size > 0) moduleIds.add(templateTitleRendererMd.id); const vueModules = Array.from(hmrSlidesIndexes).flatMap((idx) => { const frontmatter = ctx.server.moduleGraph.getModuleById(sourceIds.frontmatter[idx]); const main = ctx.server.moduleGraph.getModuleById(sourceIds.md[idx]); const styles = main ? [...main.clientImportedModules].find((m) => m.id?.includes(`&type=style`)) : void 0; return [ frontmatter, main, styles ]; }); hmrSlidesIndexes.clear(); const moduleEntries = [ ...ctx.modules.filter((i) => i.id === templateMonacoRunDeps.id || i.id === templateMonacoTypes.id), ...vueModules, ...Array.from(moduleIds).map((id) => ctx.server.moduleGraph.getModuleById(id)) ].filter(notNullish).filter((i) => !i.id?.startsWith("/@id/@vite-icons")); updateServerWatcher(); return moduleEntries; }, resolveId: { order: "pre", handler(id) { if (id.startsWith("/@slidev/") || id.includes("__slidev_")) return id; return null; } }, async load(id) { const template = templates.find((i) => i.id === id); if (template) { return { code: await template.getContent.call(this, options), map: { mappings: "" } }; } const matchFacade = id.match(regexSlideFacadeId); if (matchFacade) { const [, no, type] = matchFacade; const idx = +no - 1; const sourceId = JSON.stringify(sourceIds[type][idx]); return [ `export * from ${sourceId}`, `export { default } from ${sourceId}` ].join("\n"); } const matchSource = id.match(regexSlideSourceId); if (matchSource) { const [, no, type] = matchSource; const idx = +no - 1; const slide = data.slides[idx]; if (!slide) return; if (type === "md") { return { code: slide.content, map: { mappings: "" } }; } else if (type === "frontmatter") { const slideBase = { ...withRenderedNote(slide), frontmatter: void 0, source: void 0, importChain: void 0, // remove raw content in build, optimize the bundle size ...mode === "build" ? { raw: "", content: "", note: "" } : {} }; const fontmatter = getFrontmatter(idx); return { code: [ "// @unocss-include", 'import { computed, reactive, shallowReactive } from "vue"', `export const frontmatterData = ${JSON.stringify(fontmatter)}`, // handle HMR, update frontmatter with update "if (import.meta.hot) {", " const firstLoad = !import.meta.hot.data.frontmatter", " import.meta.hot.data.frontmatter ??= reactive(frontmatterData)", " import.meta.hot.accept(({ frontmatterData: update }) => {", " if (firstLoad) return", " const frontmatter = import.meta.hot.data.frontmatter", " Object.keys(frontmatter).forEach(key => {", " if (!(key in update)) delete frontmatter[key]", " })", " Object.assign(frontmatter, update)", " })", "}", "export const frontmatter = import.meta.hot ? import.meta.hot.data.frontmatter : reactive(frontmatterData)", "export default frontmatter", "export const meta = shallowReactive({", " get layout(){ return frontmatter.layout },", " get transition(){ return frontmatter.transition },", " get class(){ return frontmatter.class },", " get clicks(){ return frontmatter.clicks },", " get name(){ return frontmatter.name },", " get preload(){ return frontmatter.preload },", // No need to be reactive, as it's only used once after reload " slide: {", ` ...(${JSON.stringify(slideBase)}),`, ` frontmatter,`, ` filepath: ${JSON.stringify(mode === "dev" ? slide.source.filepath : "")},`, ` start: ${JSON.stringify(slide.source.start)},`, ` id: ${idx},`, ` no: ${no},`, " },", " __clicksContext: null,", " __preloaded: false,", "})" ].join("\n"), map: { mappings: "" } }; } } if (data.markdownFiles[id]) return ""; } }; } // node/vite/markdown.ts import MagicString from "magic-string-stack"; import Markdown from "unplugin-vue-markdown/vite"; // ../../node_modules/.pnpm/@hedgedoc+markdown-it-plugins@2.1.4_patch_hash=tuyuxytl56b2vxulpkzt2wf4o4_markdown-it@14.1.0/node_modules/@hedgedoc/markdown-it-plugins/dist/esm/image-size/specialCharacters.js var SpecialCharacters; (function(SpecialCharacters2) { SpecialCharacters2[SpecialCharacters2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK"; SpecialCharacters2[SpecialCharacters2["OPENING_BRACKET"] = 91] = "OPENING_BRACKET"; SpecialCharacters2[SpecialCharacters2["OPENING_PARENTHESIS"] = 40] = "OPENING_PARENTHESIS"; SpecialCharacters2[SpecialCharacters2["WHITESPACE"] = 32] = "WHITESPACE"; SpecialCharacters2[SpecialCharacters2["NEW_LINE"] = 10] = "NEW_LINE"; SpecialCharacters2[SpecialCharacters2["EQUALS"] = 61] = "EQUALS"; SpecialCharacters2[SpecialCharacters2["LOWER_CASE_X"] = 120] = "LOWER_CASE_X"; SpecialCharacters2[SpecialCharacters2["NUMBER_ZERO"] = 48] = "NUMBER_ZERO"; SpecialCharacters2[SpecialCharacters2["NUMBER_NINE"] = 57] = "NUMBER_NINE"; SpecialCharacters2[SpecialCharacters2["PERCENTAGE"] = 37] = "PERCENTAGE"; SpecialCharacters2[SpecialCharacters2["CLOSING_PARENTHESIS"] = 41] = "CLOSING_PARENTHESIS"; })(SpecialCharacters || (SpecialCharacters = {})); // ../../node_modules/.pnpm/@hedgedoc+markdown-it-plugins@2.1.4_patch_hash=tuyuxytl56b2vxulpkzt2wf4o4_markdown-it@14.1.0/node_modules/@hedgedoc/markdown-it-plugins/dist/esm/task-lists/index.js import Token from "markdown-it/lib/token.mjs"; var checkboxRegex = /^ *\[([\sx])] /i; function taskLists(md, options = { enabled: false, label: false, lineNumber: false }) { md.core.ruler.after("inline", "task-lists", (state) => processToken(state, options)); md.renderer.rules.taskListItemCheckbox = (tokens) => { const token = tokens[0]; const checkedAttribute = token.attrGet("checked") ? 'checked="" ' : ""; const disabledAttribute = token.attrGet("disabled") ? 'disabled="" ' : ""; const line = token.attrGet("line"); const idAttribute = `id="${token.attrGet("id")}" `; const dataLineAttribute = line && options.lineNumber ? `data-line="${line}" ` : ""; return ``; }; md.renderer.rules.taskListItemLabel_close = () => { return ""; }; md.renderer.rules.taskListItemLabel_open = (tokens) => { const token = tokens[0]; const id = token.attrGet("id"); return `