@slidev/cli 0.43.0-beta.4 → 0.43.0-beta.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1684 @@
1
+ import {
2
+ loadSetups
3
+ } from "./chunk-JDHANZ37.mjs";
4
+ import {
5
+ generateGoogleFontsUrl,
6
+ resolveGlobalImportPath,
7
+ resolveImportPath,
8
+ stringifyMarkdownTokens,
9
+ toAtFS
10
+ } from "./chunk-ZEKM4EGL.mjs";
11
+ import {
12
+ __commonJS,
13
+ __require,
14
+ __toESM
15
+ } from "./chunk-QHOBBTS4.mjs";
16
+
17
+ // ../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js
18
+ var require_fast_deep_equal = __commonJS({
19
+ "../../node_modules/.pnpm/fast-deep-equal@3.1.3/node_modules/fast-deep-equal/index.js"(exports, module) {
20
+ "use strict";
21
+ module.exports = function equal2(a, b) {
22
+ if (a === b)
23
+ return true;
24
+ if (a && b && typeof a == "object" && typeof b == "object") {
25
+ if (a.constructor !== b.constructor)
26
+ return false;
27
+ var length, i, keys;
28
+ if (Array.isArray(a)) {
29
+ length = a.length;
30
+ if (length != b.length)
31
+ return false;
32
+ for (i = length; i-- !== 0; )
33
+ if (!equal2(a[i], b[i]))
34
+ return false;
35
+ return true;
36
+ }
37
+ if (a.constructor === RegExp)
38
+ return a.source === b.source && a.flags === b.flags;
39
+ if (a.valueOf !== Object.prototype.valueOf)
40
+ return a.valueOf() === b.valueOf();
41
+ if (a.toString !== Object.prototype.toString)
42
+ return a.toString() === b.toString();
43
+ keys = Object.keys(a);
44
+ length = keys.length;
45
+ if (length !== Object.keys(b).length)
46
+ return false;
47
+ for (i = length; i-- !== 0; )
48
+ if (!Object.prototype.hasOwnProperty.call(b, keys[i]))
49
+ return false;
50
+ for (i = length; i-- !== 0; ) {
51
+ var key = keys[i];
52
+ if (!equal2(a[key], b[key]))
53
+ return false;
54
+ }
55
+ return true;
56
+ }
57
+ return a !== a && b !== b;
58
+ };
59
+ }
60
+ });
61
+
62
+ // node/common.ts
63
+ import { existsSync, promises as fs } from "node:fs";
64
+ import { join } from "node:path";
65
+ import { uniq } from "@antfu/utils";
66
+ import { loadConfigFromFile, mergeConfig } from "vite";
67
+ async function getIndexHtml({ clientRoot, themeRoots, addonRoots, data, userRoot }) {
68
+ let main = await fs.readFile(join(clientRoot, "index.html"), "utf-8");
69
+ let head = "";
70
+ let body = "";
71
+ head += `<link rel="icon" href="${data.config.favicon}">`;
72
+ const roots = uniq([
73
+ ...themeRoots,
74
+ ...addonRoots,
75
+ userRoot
76
+ ]);
77
+ for (const root of roots) {
78
+ const path = join(root, "index.html");
79
+ if (!existsSync(path))
80
+ continue;
81
+ const index = await fs.readFile(path, "utf-8");
82
+ head += `
83
+ ${(index.match(/<head>([\s\S]*?)<\/head>/im)?.[1] || "").trim()}`;
84
+ body += `
85
+ ${(index.match(/<body>([\s\S]*?)<\/body>/im)?.[1] || "").trim()}`;
86
+ }
87
+ if (data.features.tweet)
88
+ body += '\n<script async src="https://platform.twitter.com/widgets.js"></script>';
89
+ if (data.config.fonts.webfonts.length && data.config.fonts.provider !== "none")
90
+ head += `
91
+ <link rel="stylesheet" href="${generateGoogleFontsUrl(data.config.fonts)}" type="text/css">`;
92
+ main = main.replace("__ENTRY__", toAtFS(join(clientRoot, "main.ts"))).replace("<!-- head -->", head).replace("<!-- body -->", body);
93
+ return main;
94
+ }
95
+ async function mergeViteConfigs({ addonRoots, themeRoots }, viteConfig, config, command) {
96
+ const configEnv = {
97
+ mode: "development",
98
+ command
99
+ };
100
+ const files = uniq([
101
+ ...themeRoots,
102
+ ...addonRoots
103
+ ]).map((i) => join(i, "vite.config.ts"));
104
+ for await (const file of files) {
105
+ if (!existsSync(file))
106
+ continue;
107
+ const viteConfig2 = await loadConfigFromFile(configEnv, file);
108
+ if (!viteConfig2?.config)
109
+ continue;
110
+ config = mergeConfig(config, viteConfig2.config);
111
+ }
112
+ return mergeConfig(viteConfig, config);
113
+ }
114
+
115
+ // node/plugins/preset.ts
116
+ import { join as join8 } from "node:path";
117
+ import { existsSync as existsSync4 } from "node:fs";
118
+ import process3 from "node:process";
119
+ import Vue from "@vitejs/plugin-vue";
120
+ import VueJsx from "@vitejs/plugin-vue-jsx";
121
+ import Icons from "unplugin-icons/vite";
122
+ import IconsResolver from "unplugin-icons/resolver";
123
+ import Components from "unplugin-vue-components/vite";
124
+ import ServerRef from "vite-plugin-vue-server-ref";
125
+ import { notNullish as notNullish2 } from "@antfu/utils";
126
+
127
+ // node/drawings.ts
128
+ import { basename, dirname, join as join2, resolve } from "node:path";
129
+ import fs2 from "fs-extra";
130
+ import fg from "fast-glob";
131
+ function resolveDrawingsDir(options) {
132
+ return options.data.config.drawings.persist ? resolve(
133
+ dirname(options.entry),
134
+ options.data.config.drawings.persist
135
+ ) : void 0;
136
+ }
137
+ async function loadDrawings(options) {
138
+ const dir = resolveDrawingsDir(options);
139
+ if (!dir || !fs2.existsSync(dir))
140
+ return {};
141
+ const files = await fg("*.svg", {
142
+ onlyFiles: true,
143
+ cwd: dir,
144
+ absolute: true,
145
+ suppressErrors: true
146
+ });
147
+ const obj = {};
148
+ await Promise.all(files.map(async (path) => {
149
+ const num = +basename(path, ".svg");
150
+ if (Number.isNaN(num))
151
+ return;
152
+ const content = await fs2.readFile(path, "utf8");
153
+ const lines = content.split(/\n/g);
154
+ obj[num.toString()] = lines.slice(1, -1).join("\n");
155
+ }));
156
+ return obj;
157
+ }
158
+ async function writeDrawings(options, drawing) {
159
+ const dir = resolveDrawingsDir(options);
160
+ if (!dir)
161
+ return;
162
+ const width = options.data.config.canvasWidth;
163
+ const height = Math.round(width / options.data.config.aspectRatio);
164
+ const SVG_HEAD = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
165
+ await fs2.ensureDir(dir);
166
+ return Promise.all(
167
+ Object.entries(drawing).map(async ([key, value]) => {
168
+ if (!value)
169
+ return;
170
+ const svg = `${SVG_HEAD}
171
+ ${value}
172
+ </svg>`;
173
+ await fs2.writeFile(join2(dir, `${key}.svg`), svg, "utf-8");
174
+ })
175
+ );
176
+ }
177
+
178
+ // node/plugins/extendConfig.ts
179
+ import { dirname as dirname3, join as join4 } from "node:path";
180
+ import { mergeConfig as mergeConfig2 } from "vite";
181
+ import isInstalledGlobally from "is-installed-globally";
182
+ import { uniq as uniq2 } from "@antfu/utils";
183
+
184
+ // ../client/package.json
185
+ var dependencies = {
186
+ "@antfu/utils": "^0.7.6",
187
+ "@slidev/parser": "workspace:*",
188
+ "@slidev/types": "workspace:*",
189
+ "@unocss/reset": "^0.55.6",
190
+ "@vueuse/core": "^10.4.1",
191
+ "@vueuse/head": "^1.3.1",
192
+ "@vueuse/math": "^10.4.1",
193
+ "@vueuse/motion": "^2.0.0",
194
+ codemirror: "^5.65.5",
195
+ defu: "^6.1.2",
196
+ drauu: "^0.3.5",
197
+ "file-saver": "^2.0.5",
198
+ "fuse.js": "^6.6.2",
199
+ "js-base64": "^3.7.5",
200
+ "js-yaml": "^4.1.0",
201
+ katex: "^0.16.8",
202
+ mermaid: "^10.4.0",
203
+ "monaco-editor": "^0.37.1",
204
+ nanoid: "^4.0.2",
205
+ prettier: "^3.0.3",
206
+ recordrtc: "^5.6.2",
207
+ resolve: "^1.22.4",
208
+ unocss: "^0.55.6",
209
+ "vite-plugin-windicss": "^1.9.1",
210
+ vue: "^3.3.4",
211
+ "vue-router": "^4.2.4",
212
+ "vue-starport": "^0.3.0",
213
+ windicss: "^3.5.6"
214
+ };
215
+
216
+ // node/vite/searchRoot.ts
217
+ import fs3 from "node:fs";
218
+ import { dirname as dirname2, join as join3 } from "node:path";
219
+ var ROOT_FILES = [
220
+ // '.git',
221
+ // https://pnpm.js.org/workspaces/
222
+ "pnpm-workspace.yaml"
223
+ // https://rushjs.io/pages/advanced/config_files/
224
+ // 'rush.json',
225
+ // https://nx.dev/latest/react/getting-started/nx-setup
226
+ // 'workspace.json',
227
+ // 'nx.json'
228
+ ];
229
+ function hasWorkspacePackageJSON(root) {
230
+ const path = join3(root, "package.json");
231
+ try {
232
+ fs3.accessSync(path, fs3.constants.R_OK);
233
+ } catch {
234
+ return false;
235
+ }
236
+ const content = JSON.parse(fs3.readFileSync(path, "utf-8")) || {};
237
+ return !!content.workspaces;
238
+ }
239
+ function hasRootFile(root) {
240
+ return ROOT_FILES.some((file) => fs3.existsSync(join3(root, file)));
241
+ }
242
+ function hasPackageJSON(root) {
243
+ const path = join3(root, "package.json");
244
+ return fs3.existsSync(path);
245
+ }
246
+ function searchForPackageRoot(current, root = current) {
247
+ if (hasPackageJSON(current))
248
+ return current;
249
+ const dir = dirname2(current);
250
+ if (!dir || dir === current)
251
+ return root;
252
+ return searchForPackageRoot(dir, root);
253
+ }
254
+ function searchForWorkspaceRoot(current, root = searchForPackageRoot(current)) {
255
+ if (hasRootFile(current))
256
+ return current;
257
+ if (hasWorkspacePackageJSON(current))
258
+ return current;
259
+ const dir = dirname2(current);
260
+ if (!dir || dir === current)
261
+ return root;
262
+ return searchForWorkspaceRoot(dir, root);
263
+ }
264
+
265
+ // node/plugins/extendConfig.ts
266
+ var EXCLUDE = [
267
+ "@slidev/shared",
268
+ "@slidev/types",
269
+ "@slidev/client",
270
+ "@slidev/client/constants",
271
+ "@slidev/client/logic/dark",
272
+ "@vueuse/core",
273
+ "@vueuse/shared",
274
+ "@unocss/reset",
275
+ "unocss",
276
+ "mermaid",
277
+ "vite-plugin-windicss",
278
+ "vue-demi",
279
+ "vue"
280
+ ];
281
+ function createConfigPlugin(options) {
282
+ return {
283
+ name: "slidev:config",
284
+ async config(config) {
285
+ const injection = {
286
+ define: getDefine(options),
287
+ resolve: {
288
+ alias: {
289
+ "@slidev/client/": `${toAtFS(options.clientRoot)}/`
290
+ },
291
+ dedupe: ["vue"]
292
+ },
293
+ optimizeDeps: {
294
+ include: [
295
+ ...Object.keys(dependencies).filter((i) => !EXCLUDE.includes(i)),
296
+ "codemirror/mode/javascript/javascript",
297
+ "codemirror/mode/css/css",
298
+ "codemirror/mode/markdown/markdown",
299
+ "codemirror/mode/xml/xml",
300
+ "codemirror/mode/htmlmixed/htmlmixed",
301
+ "codemirror/addon/display/placeholder",
302
+ "prettier/plugins/babel",
303
+ "prettier/plugins/html",
304
+ "prettier/plugins/typescript",
305
+ "mermaid/dist/mermaid.esm.min.mjs",
306
+ "mermaid/dist/mermaid.esm.mjs",
307
+ "vite-plugin-vue-server-ref/client"
308
+ ],
309
+ exclude: EXCLUDE
310
+ },
311
+ css: options.data.config.css === "unocss" ? {
312
+ postcss: {
313
+ plugins: [
314
+ await import("postcss-nested").then((r) => (r.default || r)())
315
+ ]
316
+ }
317
+ } : {},
318
+ server: {
319
+ fs: {
320
+ strict: true,
321
+ allow: uniq2([
322
+ searchForWorkspaceRoot(options.userRoot),
323
+ searchForWorkspaceRoot(options.cliRoot),
324
+ ...isInstalledGlobally ? [dirname3(resolveGlobalImportPath("@slidev/client/package.json")), dirname3(resolveGlobalImportPath("katex/package.json"))] : []
325
+ ])
326
+ }
327
+ },
328
+ publicDir: join4(options.userRoot, "public")
329
+ };
330
+ if (isInstalledGlobally) {
331
+ injection.cacheDir = join4(options.cliRoot, "node_modules/.vite");
332
+ injection.root = options.cliRoot;
333
+ injection.resolve.alias.vue = `${resolveImportPath("vue/dist/vue.esm-browser.js", true)}`;
334
+ }
335
+ return mergeConfig2(injection, config);
336
+ },
337
+ configureServer(server) {
338
+ return () => {
339
+ server.middlewares.use(async (req, res, next) => {
340
+ if (req.url.endsWith(".html")) {
341
+ res.setHeader("Content-Type", "text/html");
342
+ res.statusCode = 200;
343
+ res.end(await getIndexHtml(options));
344
+ return;
345
+ }
346
+ next();
347
+ });
348
+ };
349
+ }
350
+ };
351
+ }
352
+ function getDefine(options) {
353
+ return {
354
+ __DEV__: options.mode === "dev" ? "true" : "false",
355
+ __SLIDEV_CLIENT_ROOT__: JSON.stringify(toAtFS(options.clientRoot)),
356
+ __SLIDEV_HASH_ROUTE__: JSON.stringify(options.data.config.routerMode === "hash"),
357
+ __SLIDEV_FEATURE_DRAWINGS__: JSON.stringify(options.data.config.drawings.enabled === true || options.data.config.drawings.enabled === options.mode),
358
+ __SLIDEV_FEATURE_EDITOR__: JSON.stringify(options.mode === "dev" && options.data.config.editor !== false),
359
+ __SLIDEV_FEATURE_DRAWINGS_PERSIST__: JSON.stringify(!!options.data.config.drawings.persist === true),
360
+ __SLIDEV_FEATURE_RECORD__: JSON.stringify(options.data.config.record === true || options.data.config.record === options.mode),
361
+ __SLIDEV_FEATURE_PRESENTER__: JSON.stringify(options.data.config.presenter === true || options.data.config.presenter === options.mode),
362
+ __SLIDEV_HAS_SERVER__: options.mode !== "build" ? "true" : "false"
363
+ };
364
+ }
365
+
366
+ // node/plugins/loaders.ts
367
+ var import_fast_deep_equal = __toESM(require_fast_deep_equal());
368
+ import { basename as basename2, join as join5 } from "node:path";
369
+ import process from "node:process";
370
+ import { isString, notNullish, objectMap, range, slash, uniq as uniq3 } from "@antfu/utils";
371
+ import fg2 from "fast-glob";
372
+ import fs4, { existsSync as existsSync2 } from "fs-extra";
373
+ import Markdown from "markdown-it";
374
+ import { bold, gray, red, yellow } from "kolorist";
375
+ import mila from "markdown-it-link-attributes";
376
+ import * as parser from "@slidev/parser/fs";
377
+ var regexId = /^\/\@slidev\/slide\/(\d+)\.(md|json)(?:\?import)?$/;
378
+ var regexIdQuery = /(\d+?)\.(md|json|frontmatter)$/;
379
+ var vueContextImports = [
380
+ 'import { inject as _vueInject, toRef as _vueToRef } from "vue"',
381
+ `import {
382
+ injectionSlidevContext as _injectionSlidevContext,
383
+ injectionClicks as _injectionClicks,
384
+ injectionCurrentPage as _injectionCurrentPage,
385
+ injectionSlideContext as _injectionSlideContext,
386
+ } from "@slidev/client/constants.ts"`.replace(/\n\s+/g, "\n"),
387
+ "const $slidev = _vueInject(_injectionSlidevContext)",
388
+ 'const $nav = _vueToRef($slidev, "nav")',
389
+ "const $clicks = _vueInject(_injectionClicks)",
390
+ "const $page = _vueInject(_injectionCurrentPage)",
391
+ "const $renderContext = _vueInject(_injectionSlideContext)"
392
+ ];
393
+ function getBodyJson(req) {
394
+ return new Promise((resolve3, reject) => {
395
+ let body = "";
396
+ req.on("data", (chunk) => body += chunk);
397
+ req.on("error", reject);
398
+ req.on("end", () => {
399
+ try {
400
+ resolve3(JSON.parse(body) || {});
401
+ } catch (e) {
402
+ reject(e);
403
+ }
404
+ });
405
+ });
406
+ }
407
+ var md = Markdown({ html: true });
408
+ md.use(mila, {
409
+ attrs: {
410
+ target: "_blank",
411
+ rel: "noopener"
412
+ }
413
+ });
414
+ function prepareSlideInfo(data) {
415
+ return {
416
+ ...data,
417
+ noteHTML: md.render(data?.note || "")
418
+ };
419
+ }
420
+ function createSlidesLoader({ data, entry, clientRoot, themeRoots, addonRoots, userRoot, roots, remote, mode }, pluginOptions, serverOptions) {
421
+ const slidePrefix = "/@slidev/slides/";
422
+ const hmrPages = /* @__PURE__ */ new Set();
423
+ let server;
424
+ let _layouts_cache_time = 0;
425
+ let _layouts_cache = {};
426
+ return [
427
+ {
428
+ name: "slidev:loader",
429
+ configureServer(_server) {
430
+ server = _server;
431
+ updateServerWatcher();
432
+ server.middlewares.use(async (req, res, next) => {
433
+ const match = req.url?.match(regexId);
434
+ if (!match)
435
+ return next();
436
+ const [, no, type] = match;
437
+ const idx = Number.parseInt(no);
438
+ if (type === "json" && req.method === "GET") {
439
+ res.write(JSON.stringify(prepareSlideInfo(data.slides[idx])));
440
+ return res.end();
441
+ }
442
+ if (type === "json" && req.method === "POST") {
443
+ const body = await getBodyJson(req);
444
+ const slide = data.slides[idx];
445
+ hmrPages.add(idx);
446
+ if (slide.source) {
447
+ Object.assign(slide.source, body);
448
+ await parser.saveExternalSlide(slide.source);
449
+ } else {
450
+ Object.assign(slide, body);
451
+ await parser.save(data, entry);
452
+ }
453
+ res.statusCode = 200;
454
+ res.write(JSON.stringify(prepareSlideInfo(slide)));
455
+ return res.end();
456
+ }
457
+ next();
458
+ });
459
+ },
460
+ async handleHotUpdate(ctx) {
461
+ if (!data.entries.some((i) => slash(i) === ctx.file))
462
+ return;
463
+ await ctx.read();
464
+ const newData = await parser.load(entry, data.themeMeta);
465
+ const moduleIds = /* @__PURE__ */ new Set();
466
+ if (data.slides.length !== newData.slides.length) {
467
+ moduleIds.add("/@slidev/routes");
468
+ range(newData.slides.length).map((i) => hmrPages.add(i));
469
+ }
470
+ if (!(0, import_fast_deep_equal.default)(data.headmatter.defaults, newData.headmatter.defaults)) {
471
+ moduleIds.add("/@slidev/routes");
472
+ range(data.slides.length).map((i) => hmrPages.add(i));
473
+ }
474
+ if (!(0, import_fast_deep_equal.default)(data.config, newData.config))
475
+ moduleIds.add("/@slidev/configs");
476
+ if (!(0, import_fast_deep_equal.default)(data.features, newData.features)) {
477
+ setTimeout(() => {
478
+ ctx.server.ws.send({ type: "full-reload" });
479
+ }, 1);
480
+ }
481
+ const length = Math.max(data.slides.length, newData.slides.length);
482
+ for (let i = 0; i < length; i++) {
483
+ const a = data.slides[i];
484
+ const b = newData.slides[i];
485
+ if (a?.content.trim() === b?.content.trim() && a?.title?.trim() === b?.title?.trim() && a?.note === b?.note && (0, import_fast_deep_equal.default)(a.frontmatter, b.frontmatter))
486
+ continue;
487
+ ctx.server.ws.send({
488
+ type: "custom",
489
+ event: "slidev-update",
490
+ data: {
491
+ id: i,
492
+ data: prepareSlideInfo(newData.slides[i])
493
+ }
494
+ });
495
+ hmrPages.add(i);
496
+ }
497
+ serverOptions.onDataReload?.(newData, data);
498
+ Object.assign(data, newData);
499
+ if (hmrPages.size > 0)
500
+ moduleIds.add("/@slidev/titles.md");
501
+ const vueModules = Array.from(hmrPages).flatMap((i) => [
502
+ ctx.server.moduleGraph.getModuleById(`${slidePrefix}${i + 1}.frontmatter`),
503
+ ctx.server.moduleGraph.getModuleById(`${slidePrefix}${i + 1}.md`)
504
+ ]);
505
+ hmrPages.clear();
506
+ const moduleEntries = [
507
+ ...vueModules,
508
+ ...Array.from(moduleIds).map((id) => ctx.server.moduleGraph.getModuleById(id))
509
+ ].filter(notNullish).filter((i) => !i.id?.startsWith("/@id/@vite-icons"));
510
+ updateServerWatcher();
511
+ return moduleEntries;
512
+ },
513
+ resolveId(id) {
514
+ if (id.startsWith(slidePrefix) || id.startsWith("/@slidev/"))
515
+ return id;
516
+ return null;
517
+ },
518
+ load(id) {
519
+ if (id === "/@slidev/routes")
520
+ return generateRoutes();
521
+ if (id === "/@slidev/layouts")
522
+ return generateLayouts();
523
+ if (id === "/@slidev/styles")
524
+ return generateUserStyles();
525
+ if (id === "/@slidev/monaco-types")
526
+ return generateMonacoTypes();
527
+ if (id === "/@slidev/configs")
528
+ return generateConfigs();
529
+ if (id === "/@slidev/global-components/top")
530
+ return generateGlobalComponents("top");
531
+ if (id === "/@slidev/global-components/bottom")
532
+ return generateGlobalComponents("bottom");
533
+ if (id === "/@slidev/custom-nav-controls")
534
+ return generateCustomNavControls();
535
+ if (id === "/@slidev/titles.md") {
536
+ return {
537
+ code: data.slides.filter(({ frontmatter }) => !frontmatter?.disabled).map(({ title }, i) => `<template ${i === 0 ? "v-if" : "v-else-if"}="+no === ${i + 1}">
538
+
539
+ ${title}
540
+
541
+ </template>`).join(""),
542
+ map: { mappings: "" }
543
+ };
544
+ }
545
+ if (id.startsWith(slidePrefix)) {
546
+ const remaning = id.slice(slidePrefix.length);
547
+ const match = remaning.match(regexIdQuery);
548
+ if (match) {
549
+ const [, no, type] = match;
550
+ const pageNo = Number.parseInt(no) - 1;
551
+ const slide = data.slides[pageNo];
552
+ if (!slide)
553
+ return;
554
+ if (type === "md") {
555
+ return {
556
+ code: slide?.content,
557
+ map: { mappings: "" }
558
+ };
559
+ } else if (type === "frontmatter") {
560
+ return {
561
+ code: [
562
+ 'import { reactive, computed } from "vue"',
563
+ `export const frontmatter = reactive(${JSON.stringify(slide.frontmatter)})`,
564
+ `export const meta = reactive({
565
+ layout: computed(() => frontmatter.layout),
566
+ transition: computed(() => frontmatter.transition),
567
+ class: computed(() => frontmatter.class),
568
+ clicks: computed(() => frontmatter.clicks),
569
+ name: computed(() => frontmatter.name),
570
+ slide: {
571
+ ...(${JSON.stringify({
572
+ ...prepareSlideInfo(slide),
573
+ frontmatter: void 0,
574
+ // remove raw content in build, optimize the bundle size
575
+ ...mode === "build" ? { raw: "", content: "", note: "" } : {}
576
+ })}),
577
+ frontmatter,
578
+ filepath: ${JSON.stringify(slide.source?.filepath || entry)},
579
+ id: ${pageNo},
580
+ no: ${no},
581
+ },
582
+ __clicksElements: [],
583
+ __preloaded: false,
584
+ })`,
585
+ "export default frontmatter",
586
+ // handle HMR, update frontmatter with update
587
+ "if (import.meta.hot) {",
588
+ " import.meta.hot.accept(({ frontmatter: update }) => {",
589
+ " if(!update) return",
590
+ " Object.keys(frontmatter).forEach(key => {",
591
+ " if (!(key in update)) delete frontmatter[key]",
592
+ " })",
593
+ " Object.assign(frontmatter, update)",
594
+ " })",
595
+ "}"
596
+ ].join("\n"),
597
+ map: { mappings: "" }
598
+ };
599
+ }
600
+ }
601
+ return {
602
+ code: "",
603
+ map: { mappings: "" }
604
+ };
605
+ }
606
+ }
607
+ },
608
+ {
609
+ name: "slidev:layout-transform:pre",
610
+ enforce: "pre",
611
+ async transform(code, id) {
612
+ if (!id.startsWith(slidePrefix))
613
+ return;
614
+ const remaning = id.slice(slidePrefix.length);
615
+ const match = remaning.match(regexIdQuery);
616
+ if (!match)
617
+ return;
618
+ const [, no, type] = match;
619
+ if (type !== "md")
620
+ return;
621
+ const pageNo = Number.parseInt(no) - 1;
622
+ return transformMarkdown(code, pageNo, data);
623
+ }
624
+ },
625
+ {
626
+ name: "slidev:context-transform:pre",
627
+ enforce: "pre",
628
+ async transform(code, id) {
629
+ if (!id.endsWith(".vue") || id.includes("/@slidev/client/") || id.includes("/packages/client/"))
630
+ return;
631
+ return transformVue(code);
632
+ }
633
+ },
634
+ {
635
+ name: "slidev:title-transform:pre",
636
+ enforce: "pre",
637
+ transform(code, id) {
638
+ if (id !== "/@slidev/titles.md")
639
+ return;
640
+ return transformTitles(code);
641
+ }
642
+ },
643
+ {
644
+ name: "slidev:slide-transform:post",
645
+ enforce: "post",
646
+ transform(code, id) {
647
+ if (!id.match(/\/@slidev\/slides\/\d+\.md($|\?)/))
648
+ return;
649
+ const replaced = code.replace("if (_rerender_only)", "if (false)");
650
+ if (replaced !== code)
651
+ return replaced;
652
+ }
653
+ }
654
+ ];
655
+ function updateServerWatcher() {
656
+ if (!server)
657
+ return;
658
+ server.watcher.add(data.entries?.map(slash) || []);
659
+ }
660
+ async function transformMarkdown(code, pageNo, data2) {
661
+ const layouts = await getLayouts();
662
+ const frontmatter = {
663
+ ...data2.headmatter?.defaults || {},
664
+ ...data2.slides[pageNo]?.frontmatter || {}
665
+ };
666
+ let layoutName = frontmatter?.layout || (pageNo === 0 ? "cover" : "default");
667
+ if (!layouts[layoutName]) {
668
+ console.error(red(`
669
+ Unknown layout "${bold(layoutName)}".${yellow(" Available layouts are:")}`) + Object.keys(layouts).map((i, idx) => (idx % 3 === 0 ? "\n " : "") + gray(i.padEnd(15, " "))).join(" "));
670
+ console.error();
671
+ layoutName = "default";
672
+ }
673
+ delete frontmatter.title;
674
+ const imports = [
675
+ ...vueContextImports,
676
+ `import InjectedLayout from "${toAtFS(layouts[layoutName])}"`,
677
+ `import frontmatter from "${toAtFS(`${slidePrefix + (pageNo + 1)}.frontmatter`)}"`,
678
+ "const $frontmatter = frontmatter",
679
+ // update frontmatter in router
680
+ ";(() => {",
681
+ " const route = $slidev.nav.rawRoutes.find(i => i.path === String($page))",
682
+ " if (route.meta.slide.frontmatter) {",
683
+ " Object.keys(route.meta.slide.frontmatter).forEach(key => {",
684
+ " if (!(key in $frontmatter)) delete route.meta.slide.frontmatter[key]",
685
+ " })",
686
+ " Object.assign(route.meta.slide.frontmatter, frontmatter)",
687
+ " }",
688
+ "})();"
689
+ ];
690
+ code = code.replace(/(<script setup.*>)/g, `$1
691
+ ${imports.join("\n")}
692
+ `);
693
+ const injectA = code.indexOf("<template>") + "<template>".length;
694
+ const injectB = code.lastIndexOf("</template>");
695
+ let body = code.slice(injectA, injectB).trim();
696
+ if (body.startsWith("<div>") && body.endsWith("</div>"))
697
+ body = body.slice(5, -6);
698
+ code = `${code.slice(0, injectA)}
699
+ <InjectedLayout v-bind="frontmatter">
700
+ ${body}
701
+ </InjectedLayout>
702
+ ${code.slice(injectB)}`;
703
+ return code;
704
+ }
705
+ function transformVue(code) {
706
+ if (code.includes("injectionSlidevContext") || code.includes("injectionClicks") || code.includes("const $slidev"))
707
+ return code;
708
+ const imports = [
709
+ ...vueContextImports
710
+ ];
711
+ const matchScript = code.match(/<script((?!setup).)*(setup)?.*>/);
712
+ if (matchScript && matchScript[2]) {
713
+ return code.replace(/(<script.*>)/g, `$1
714
+ ${imports.join("\n")}
715
+ `);
716
+ } else if (matchScript && !matchScript[2]) {
717
+ const matchExport = code.match(/export\s+default\s+{/);
718
+ if (matchExport) {
719
+ const exportIndex = (matchExport.index || 0) + matchExport[0].length;
720
+ let component = code.slice(exportIndex);
721
+ component = component.slice(0, component.indexOf("</script>"));
722
+ const scriptIndex = (matchScript.index || 0) + matchScript[0].length;
723
+ const provideImport = '\nimport { injectionSlidevContext } from "@slidev/client/constants.ts"\n';
724
+ code = `${code.slice(0, scriptIndex)}${provideImport}${code.slice(scriptIndex)}`;
725
+ let injectIndex = exportIndex + provideImport.length;
726
+ let injectObject = "$slidev: { from: injectionSlidevContext },";
727
+ const matchInject = component.match(/.*inject\s*:\s*([\[{])/);
728
+ if (matchInject) {
729
+ injectIndex += (matchInject.index || 0) + matchInject[0].length;
730
+ if (matchInject[1] === "[") {
731
+ let injects = component.slice((matchInject.index || 0) + matchInject[0].length);
732
+ const injectEndIndex = injects.indexOf("]");
733
+ injects = injects.slice(0, injectEndIndex);
734
+ injectObject += injects.split(",").map((inject) => `${inject}: {from: ${inject}}`).join(",");
735
+ return `${code.slice(0, injectIndex - 1)}{
736
+ ${injectObject}
737
+ }${code.slice(injectIndex + injectEndIndex + 1)}`;
738
+ } else {
739
+ return `${code.slice(0, injectIndex)}
740
+ ${injectObject}
741
+ ${code.slice(injectIndex)}`;
742
+ }
743
+ }
744
+ return `${code.slice(0, injectIndex)}
745
+ inject: { ${injectObject} },
746
+ ${code.slice(injectIndex)}`;
747
+ }
748
+ }
749
+ return `<script setup>
750
+ ${imports.join("\n")}
751
+ </script>
752
+ ${code}`;
753
+ }
754
+ function transformTitles(code) {
755
+ return code.replace(/<template>\s*<div>\s*<p>/, "<template>").replace(/<\/p>\s*<\/div>\s*<\/template>/, "</template>").replace(/<script\ssetup>/, `<script setup lang="ts">
756
+ defineProps<{ no: number | string }>()`);
757
+ }
758
+ async function getLayouts() {
759
+ const now = Date.now();
760
+ if (now - _layouts_cache_time < 2e3)
761
+ return _layouts_cache;
762
+ const layouts = {};
763
+ const roots2 = uniq3([
764
+ userRoot,
765
+ ...themeRoots,
766
+ ...addonRoots,
767
+ clientRoot
768
+ ]);
769
+ for (const root of roots2) {
770
+ const layoutPaths = await fg2("layouts/**/*.{vue,ts}", {
771
+ cwd: root,
772
+ absolute: true,
773
+ suppressErrors: true
774
+ });
775
+ for (const layoutPath of layoutPaths) {
776
+ const layout = basename2(layoutPath).replace(/\.\w+$/, "");
777
+ if (layouts[layout])
778
+ continue;
779
+ layouts[layout] = layoutPath;
780
+ }
781
+ }
782
+ _layouts_cache_time = now;
783
+ _layouts_cache = layouts;
784
+ return layouts;
785
+ }
786
+ async function generateUserStyles() {
787
+ const imports = [
788
+ `import "${toAtFS(join5(clientRoot, "styles/vars.css"))}"`,
789
+ `import "${toAtFS(join5(clientRoot, "styles/index.css"))}"`,
790
+ `import "${toAtFS(join5(clientRoot, "styles/code.css"))}"`,
791
+ `import "${toAtFS(join5(clientRoot, "styles/transitions.css"))}"`
792
+ ];
793
+ const roots2 = uniq3([
794
+ ...themeRoots,
795
+ ...addonRoots,
796
+ userRoot
797
+ ]);
798
+ for (const root of roots2) {
799
+ const styles = [
800
+ join5(root, "styles", "index.ts"),
801
+ join5(root, "styles", "index.js"),
802
+ join5(root, "styles", "index.css"),
803
+ join5(root, "styles.css"),
804
+ join5(root, "style.css")
805
+ ];
806
+ for (const style of styles) {
807
+ if (existsSync2(style)) {
808
+ imports.push(`import "${toAtFS(style)}"`);
809
+ continue;
810
+ }
811
+ }
812
+ }
813
+ if (data.features.katex)
814
+ imports.push(`import "${toAtFS(resolveImportPath("katex/dist/katex.min.css", true))}"`);
815
+ if (data.config.css === "unocss") {
816
+ imports.unshift(
817
+ 'import "@unocss/reset/tailwind.css"',
818
+ 'import "uno:preflights.css"',
819
+ 'import "uno:typography.css"',
820
+ 'import "uno:shortcuts.css"'
821
+ );
822
+ imports.push('import "uno.css"');
823
+ } else {
824
+ imports.unshift(
825
+ 'import "virtual:windi-components.css"',
826
+ 'import "virtual:windi-base.css"'
827
+ );
828
+ imports.push('import "virtual:windi-utilities.css"');
829
+ if (process.env.NODE_ENV !== "production")
830
+ imports.push('import "virtual:windi-devtools"');
831
+ }
832
+ return imports.join("\n");
833
+ }
834
+ async function generateMonacoTypes() {
835
+ return `void 0; ${parser.scanMonacoModules(data.raw).map((i) => `import('/@slidev-monaco-types/${i}')`).join("\n")}`;
836
+ }
837
+ async function generateLayouts() {
838
+ const imports = [];
839
+ const layouts = objectMap(
840
+ await getLayouts(),
841
+ (k, v) => {
842
+ imports.push(`import __layout_${k} from "${toAtFS(v)}"`);
843
+ return [k, `__layout_${k}`];
844
+ }
845
+ );
846
+ return [
847
+ imports.join("\n"),
848
+ `export default {
849
+ ${Object.entries(layouts).map(([k, v]) => `"${k}": ${v}`).join(",\n")}
850
+ }`
851
+ ].join("\n\n");
852
+ }
853
+ async function generateRoutes() {
854
+ const imports = [];
855
+ const redirects = [];
856
+ const layouts = await getLayouts();
857
+ imports.push(`import __layout__end from '${layouts.end}'`);
858
+ let no = 1;
859
+ const routes = data.slides.filter(({ frontmatter }) => !frontmatter?.disabled).map((i, idx) => {
860
+ imports.push(`import n${no} from '${slidePrefix}${idx + 1}.md'`);
861
+ imports.push(`import { meta as f${no} } from '${slidePrefix}${idx + 1}.frontmatter'`);
862
+ const route = `{ path: '${no}', name: 'page-${no}', component: n${no}, meta: f${no} }`;
863
+ if (i.frontmatter?.routeAlias)
864
+ redirects.push(`{ path: '${i.frontmatter?.routeAlias}', redirect: { path: '${no}' } }`);
865
+ no += 1;
866
+ return route;
867
+ });
868
+ const routesStr = `export default [
869
+ ${routes.join(",\n")}
870
+ ]`;
871
+ const redirectsStr = `export const redirects = [
872
+ ${redirects.join(",\n")}
873
+ ]`;
874
+ return [...imports, routesStr, redirectsStr].join("\n");
875
+ }
876
+ function generateConfigs() {
877
+ const config = { ...data.config, remote };
878
+ if (isString(config.title)) {
879
+ const tokens = md.parseInline(config.title, {});
880
+ config.title = stringifyMarkdownTokens(tokens);
881
+ }
882
+ if (isString(config.info))
883
+ config.info = md.render(config.info);
884
+ return `export default ${JSON.stringify(config)}`;
885
+ }
886
+ async function generateGlobalComponents(layer) {
887
+ const components = roots.flatMap((root) => {
888
+ if (layer === "top") {
889
+ return [
890
+ join5(root, "global.vue"),
891
+ join5(root, "global-top.vue"),
892
+ join5(root, "GlobalTop.vue")
893
+ ];
894
+ } else {
895
+ return [
896
+ join5(root, "global-bottom.vue"),
897
+ join5(root, "GlobalBottom.vue")
898
+ ];
899
+ }
900
+ }).filter((i) => fs4.existsSync(i));
901
+ const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
902
+ const render = components.map((i, idx) => `h(__n${idx})`).join(",");
903
+ return `
904
+ ${imports}
905
+ import { h } from 'vue'
906
+ export default {
907
+ render() {
908
+ return [${render}]
909
+ }
910
+ }
911
+ `;
912
+ }
913
+ async function generateCustomNavControls() {
914
+ const components = roots.flatMap((root) => {
915
+ return [
916
+ join5(root, "custom-nav-controls.vue"),
917
+ join5(root, "CustomNavControls.vue")
918
+ ];
919
+ }).filter((i) => fs4.existsSync(i));
920
+ const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
921
+ const render = components.map((i, idx) => `h(__n${idx})`).join(",");
922
+ return `
923
+ ${imports}
924
+ import { h } from 'vue'
925
+ export default {
926
+ render() {
927
+ return [${render}]
928
+ }
929
+ }
930
+ `;
931
+ }
932
+ }
933
+
934
+ // node/plugins/monacoTransform.ts
935
+ import { join as join6 } from "node:path";
936
+ import process2 from "node:process";
937
+ import { slash as slash2 } from "@antfu/utils";
938
+ async function getPackageData(pkg) {
939
+ const { resolvePackageData } = await eval('import("vite")');
940
+ const info = resolvePackageData(pkg, process2.cwd());
941
+ if (!info)
942
+ return;
943
+ const typePath = info.data.types || info.data.typings;
944
+ if (!typePath)
945
+ return;
946
+ return [info, typePath];
947
+ }
948
+ function createMonacoTypesLoader() {
949
+ return {
950
+ name: "slidev:monaco-types-loader",
951
+ resolveId(id) {
952
+ if (id.startsWith("/@slidev-monaco-types/"))
953
+ return id;
954
+ return null;
955
+ },
956
+ async load(id) {
957
+ const match = id.match(/^\/\@slidev-monaco-types\/(.*)$/);
958
+ if (match) {
959
+ const pkg2 = match[1];
960
+ const packageData = await getPackageData(pkg2) || await getPackageData(`@types/${pkg2}`);
961
+ if (!packageData)
962
+ return;
963
+ const [info2, typePath2] = packageData;
964
+ return [
965
+ "import * as monaco from 'monaco-editor'",
966
+ `import Type from "${slash2(join6(info2.dir, typePath2))}?raw"`,
967
+ ...Object.keys(info2.data.dependencies || {}).map((i) => `import "/@slidev-monaco-types/${i}"`),
968
+ `monaco.languages.typescript.typescriptDefaults.addExtraLib(\`declare module "${pkg2}" { \${Type} }\`)`
969
+ ].join("\n");
970
+ }
971
+ }
972
+ };
973
+ }
974
+
975
+ // node/plugins/setupClient.ts
976
+ import { existsSync as existsSync3 } from "node:fs";
977
+ import { join as join7, resolve as resolve2 } from "node:path";
978
+ import { slash as slash3, uniq as uniq4 } from "@antfu/utils";
979
+ function createClientSetupPlugin({ clientRoot, themeRoots, addonRoots, userRoot }) {
980
+ const setupEntry = slash3(resolve2(clientRoot, "setup"));
981
+ return {
982
+ name: "slidev:setup",
983
+ enforce: "pre",
984
+ async transform(code, id) {
985
+ if (id.startsWith(setupEntry)) {
986
+ let getInjections2 = function(isAwait = false, isChained = false) {
987
+ return injections.join("\n").replace(/:AWAIT:/g, isAwait ? "await " : "").replace(/(,\s*)?:LAST:/g, isChained ? "$1injection_return" : "");
988
+ };
989
+ var getInjections = getInjections2;
990
+ const name = id.slice(setupEntry.length + 1).replace(/\?.*$/, "");
991
+ const imports = [];
992
+ const injections = [];
993
+ const setups = uniq4([
994
+ ...themeRoots,
995
+ ...addonRoots,
996
+ userRoot
997
+ ]).map((i) => join7(i, "setup", name));
998
+ setups.forEach((path, idx) => {
999
+ if (!existsSync3(path))
1000
+ return;
1001
+ imports.push(`import __n${idx} from '${toAtFS(path)}'`);
1002
+ let fn = `:AWAIT:__n${idx}`;
1003
+ if (/\binjection_return\b/g.test(code))
1004
+ fn = `injection_return = ${fn}`;
1005
+ if (/\binjection_arg\b/g.test(code)) {
1006
+ fn += "(";
1007
+ const matches = Array.from(code.matchAll(/\binjection_arg(_\d+)?\b/g));
1008
+ const dedupedMatches = Array.from(new Set(matches.map((m) => m[0])));
1009
+ fn += dedupedMatches.join(", ");
1010
+ fn += ", :LAST:)";
1011
+ } else {
1012
+ fn += "(:LAST:)";
1013
+ }
1014
+ injections.push(
1015
+ `// ${path}`,
1016
+ fn
1017
+ );
1018
+ });
1019
+ code = code.replace("/* __imports__ */", imports.join("\n"));
1020
+ code = code.replace("/* __injections__ */", getInjections2());
1021
+ code = code.replace("/* __async_injections__ */", getInjections2(true));
1022
+ code = code.replace("/* __chained_injections__ */", getInjections2(false, true));
1023
+ code = code.replace("/* __chained_async_injections__ */", getInjections2(true, true));
1024
+ return code;
1025
+ }
1026
+ return null;
1027
+ }
1028
+ };
1029
+ }
1030
+
1031
+ // node/plugins/markdown.ts
1032
+ import Markdown2 from "unplugin-vue-markdown/vite";
1033
+ import * as base64 from "js-base64";
1034
+ import { slash as slash4 } from "@antfu/utils";
1035
+ import mila2 from "markdown-it-link-attributes";
1036
+ import mif from "markdown-it-footnote";
1037
+ import { taskLists } from "@hedgedoc/markdown-it-plugins";
1038
+ import { encode as encode2 } from "plantuml-encoder";
1039
+ import Mdc from "markdown-it-mdc";
1040
+
1041
+ // node/plugins/markdown-it-katex.ts
1042
+ import katex from "katex";
1043
+ function isValidDelim(state, pos) {
1044
+ const max = state.posMax;
1045
+ let can_open = true;
1046
+ let can_close = true;
1047
+ const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
1048
+ const nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1;
1049
+ if (prevChar === 32 || prevChar === 9 || /* \t */
1050
+ nextChar >= 48 && nextChar <= 57)
1051
+ can_close = false;
1052
+ if (nextChar === 32 || nextChar === 9)
1053
+ can_open = false;
1054
+ return {
1055
+ can_open,
1056
+ can_close
1057
+ };
1058
+ }
1059
+ function math_inline(state, silent) {
1060
+ let match, token, res, pos;
1061
+ if (state.src[state.pos] !== "$")
1062
+ return false;
1063
+ res = isValidDelim(state, state.pos);
1064
+ if (!res.can_open) {
1065
+ if (!silent)
1066
+ state.pending += "$";
1067
+ state.pos += 1;
1068
+ return true;
1069
+ }
1070
+ const start = state.pos + 1;
1071
+ match = start;
1072
+ while ((match = state.src.indexOf("$", match)) !== -1) {
1073
+ pos = match - 1;
1074
+ while (state.src[pos] === "\\")
1075
+ pos -= 1;
1076
+ if ((match - pos) % 2 === 1)
1077
+ break;
1078
+ match += 1;
1079
+ }
1080
+ if (match === -1) {
1081
+ if (!silent)
1082
+ state.pending += "$";
1083
+ state.pos = start;
1084
+ return true;
1085
+ }
1086
+ if (match - start === 0) {
1087
+ if (!silent)
1088
+ state.pending += "$$";
1089
+ state.pos = start + 1;
1090
+ return true;
1091
+ }
1092
+ res = isValidDelim(state, match);
1093
+ if (!res.can_close) {
1094
+ if (!silent)
1095
+ state.pending += "$";
1096
+ state.pos = start;
1097
+ return true;
1098
+ }
1099
+ if (!silent) {
1100
+ token = state.push("math_inline", "math", 0);
1101
+ token.markup = "$";
1102
+ token.content = state.src.slice(start, match);
1103
+ }
1104
+ state.pos = match + 1;
1105
+ return true;
1106
+ }
1107
+ function math_block(state, start, end, silent) {
1108
+ let firstLine;
1109
+ let lastLine;
1110
+ let next;
1111
+ let lastPos;
1112
+ let found = false;
1113
+ let pos = state.bMarks[start] + state.tShift[start];
1114
+ let max = state.eMarks[start];
1115
+ if (pos + 2 > max)
1116
+ return false;
1117
+ if (state.src.slice(pos, pos + 2) !== "$$")
1118
+ return false;
1119
+ pos += 2;
1120
+ firstLine = state.src.slice(pos, max);
1121
+ if (silent)
1122
+ return true;
1123
+ if (firstLine.trim().slice(-2) === "$$") {
1124
+ firstLine = firstLine.trim().slice(0, -2);
1125
+ found = true;
1126
+ }
1127
+ for (next = start; !found; ) {
1128
+ next++;
1129
+ if (next >= end)
1130
+ break;
1131
+ pos = state.bMarks[next] + state.tShift[next];
1132
+ max = state.eMarks[next];
1133
+ if (pos < max && state.tShift[next] < state.blkIndent) {
1134
+ break;
1135
+ }
1136
+ if (state.src.slice(pos, max).trim().slice(-2) === "$$") {
1137
+ lastPos = state.src.slice(0, max).lastIndexOf("$$");
1138
+ lastLine = state.src.slice(pos, lastPos);
1139
+ found = true;
1140
+ }
1141
+ }
1142
+ state.line = next + 1;
1143
+ const token = state.push("math_block", "math", 0);
1144
+ token.block = true;
1145
+ token.content = (firstLine && firstLine.trim() ? `${firstLine}
1146
+ ` : "") + state.getLines(start + 1, next, state.tShift[start], true) + (lastLine && lastLine.trim() ? lastLine : "");
1147
+ token.map = [start, state.line];
1148
+ token.markup = "$$";
1149
+ return true;
1150
+ }
1151
+ function math_plugin(md2, options) {
1152
+ options = options || {};
1153
+ const katexInline = function(latex) {
1154
+ options.displayMode = false;
1155
+ try {
1156
+ return katex.renderToString(latex, options);
1157
+ } catch (error) {
1158
+ if (options.throwOnError)
1159
+ console.warn(error);
1160
+ return latex;
1161
+ }
1162
+ };
1163
+ const inlineRenderer = function(tokens, idx) {
1164
+ return katexInline(tokens[idx].content);
1165
+ };
1166
+ const katexBlock = function(latex) {
1167
+ options.displayMode = true;
1168
+ try {
1169
+ return `<p>${katex.renderToString(latex, options)}</p>`;
1170
+ } catch (error) {
1171
+ if (options.throwOnError)
1172
+ console.warn(error);
1173
+ return latex;
1174
+ }
1175
+ };
1176
+ const blockRenderer = function(tokens, idx) {
1177
+ return `${katexBlock(tokens[idx].content)}
1178
+ `;
1179
+ };
1180
+ md2.inline.ruler.after("escape", "math_inline", math_inline);
1181
+ md2.block.ruler.after("blockquote", "math_block", math_block, {
1182
+ alt: ["paragraph", "reference", "blockquote", "list"]
1183
+ });
1184
+ md2.renderer.rules.math_inline = inlineRenderer;
1185
+ md2.renderer.rules.math_block = blockRenderer;
1186
+ }
1187
+
1188
+ // node/plugins/markdown-it-prism.ts
1189
+ import Prism from "prismjs";
1190
+ import loadLanguages from "prismjs/components/";
1191
+ import * as htmlparser2 from "htmlparser2";
1192
+ var Tag = class {
1193
+ constructor(tagname, attributes) {
1194
+ this.tagname = tagname;
1195
+ this.attributes = attributes;
1196
+ }
1197
+ asOpen() {
1198
+ return `<${this.tagname} ${Object.entries(this.attributes).map(([key, value]) => `${key}="${value}"`).join(" ")}>`;
1199
+ }
1200
+ asClosed() {
1201
+ return `</${this.tagname}>`;
1202
+ }
1203
+ };
1204
+ var DEFAULTS = {
1205
+ plugins: [],
1206
+ init: () => {
1207
+ },
1208
+ defaultLanguageForUnknown: void 0,
1209
+ defaultLanguageForUnspecified: void 0,
1210
+ defaultLanguage: void 0
1211
+ };
1212
+ function loadPrismLang(lang) {
1213
+ if (!lang)
1214
+ return void 0;
1215
+ let langObject = Prism.languages[lang];
1216
+ if (langObject === void 0) {
1217
+ loadLanguages([lang]);
1218
+ langObject = Prism.languages[lang];
1219
+ }
1220
+ return langObject;
1221
+ }
1222
+ function loadPrismPlugin(name) {
1223
+ try {
1224
+ __require(`prismjs/plugins/${name}/prism-${name}`);
1225
+ } catch (e) {
1226
+ throw new Error(`Cannot load Prism plugin "${name}". Please check the spelling.`);
1227
+ }
1228
+ }
1229
+ function selectLanguage(options, lang) {
1230
+ let langToUse = lang;
1231
+ if (langToUse === "" && options.defaultLanguageForUnspecified !== void 0)
1232
+ langToUse = options.defaultLanguageForUnspecified;
1233
+ let prismLang = loadPrismLang(langToUse);
1234
+ if (prismLang === void 0 && options.defaultLanguageForUnknown !== void 0) {
1235
+ langToUse = options.defaultLanguageForUnknown;
1236
+ prismLang = loadPrismLang(langToUse);
1237
+ }
1238
+ return [langToUse, prismLang];
1239
+ }
1240
+ function highlight(markdownit, options, text, lang) {
1241
+ const [langToUse, prismLang] = selectLanguage(options, lang);
1242
+ let code = text.trimEnd();
1243
+ code = prismLang ? highlightPrism(code, prismLang, langToUse) : markdownit.utils.escapeHtml(code);
1244
+ code = code.split(/\r?\n/g).map((line) => `<span class="line">${line}</span>`).join("\n");
1245
+ const classAttribute = langToUse ? ` class="slidev-code ${markdownit.options.langPrefix}${markdownit.utils.escapeHtml(langToUse)}"` : "";
1246
+ return escapeVueInCode(`<pre${classAttribute}><code>${code}</code></pre>`);
1247
+ }
1248
+ function highlightPrism(code, prismLang, langToUse) {
1249
+ const openTags = [];
1250
+ const parser2 = new htmlparser2.Parser({
1251
+ onopentag(tagname, attributes) {
1252
+ openTags.push(new Tag(tagname, attributes));
1253
+ },
1254
+ onclosetag() {
1255
+ openTags.pop();
1256
+ }
1257
+ });
1258
+ code = Prism.highlight(code, prismLang, langToUse);
1259
+ code = code.split(/\r?\n/g).map((line) => {
1260
+ const prefix = openTags.map((tag) => tag.asOpen()).join("");
1261
+ parser2.write(line);
1262
+ const postfix = openTags.reverse().map((tag) => tag.asClosed()).join("");
1263
+ return prefix + line + postfix;
1264
+ }).join("\n");
1265
+ parser2.end();
1266
+ return code;
1267
+ }
1268
+ function checkLanguageOption(options, optionName) {
1269
+ const language = options[optionName];
1270
+ if (language !== void 0 && loadPrismLang(language) === void 0)
1271
+ throw new Error(`Bad option ${optionName}: There is no Prism language '${language}'.`);
1272
+ }
1273
+ function markdownItPrism(markdownit, useroptions) {
1274
+ const options = Object.assign({}, DEFAULTS, useroptions);
1275
+ checkLanguageOption(options, "defaultLanguage");
1276
+ checkLanguageOption(options, "defaultLanguageForUnknown");
1277
+ checkLanguageOption(options, "defaultLanguageForUnspecified");
1278
+ options.defaultLanguageForUnknown = options.defaultLanguageForUnknown || options.defaultLanguage;
1279
+ options.defaultLanguageForUnspecified = options.defaultLanguageForUnspecified || options.defaultLanguage;
1280
+ options.plugins.forEach(loadPrismPlugin);
1281
+ options.init(Prism);
1282
+ markdownit.options.highlight = (text, lang) => highlight(markdownit, options, text, lang);
1283
+ }
1284
+
1285
+ // node/plugins/markdown-it-shiki.ts
1286
+ function getThemeName(theme) {
1287
+ if (typeof theme === "string")
1288
+ return theme;
1289
+ return theme.name;
1290
+ }
1291
+ function isShikiDarkModeThemes(theme) {
1292
+ return typeof theme === "object" && ("dark" in theme || "light" in theme);
1293
+ }
1294
+ function resolveShikiOptions(options) {
1295
+ const themes = [];
1296
+ let darkModeThemes;
1297
+ if (!options.theme) {
1298
+ themes.push("nord");
1299
+ } else if (typeof options.theme === "string") {
1300
+ themes.push(options.theme);
1301
+ } else {
1302
+ if (isShikiDarkModeThemes(options.theme)) {
1303
+ darkModeThemes = options.theme;
1304
+ themes.push(options.theme.dark);
1305
+ themes.push(options.theme.light);
1306
+ } else {
1307
+ themes.push(options.theme);
1308
+ }
1309
+ }
1310
+ return {
1311
+ ...options,
1312
+ themes,
1313
+ darkModeThemes: darkModeThemes ? {
1314
+ dark: getThemeName(darkModeThemes.dark),
1315
+ light: getThemeName(darkModeThemes.light)
1316
+ } : void 0
1317
+ };
1318
+ }
1319
+ function trimEndNewLine(code) {
1320
+ return code.replace(/\n$/, "");
1321
+ }
1322
+ var MarkdownItShiki = (markdownit, options = {}) => {
1323
+ const _highlighter = options.highlighter;
1324
+ const { darkModeThemes } = resolveShikiOptions(options);
1325
+ markdownit.options.highlight = (code, lang) => {
1326
+ if (darkModeThemes) {
1327
+ const trimmed = trimEndNewLine(code);
1328
+ const dark = _highlighter.codeToHtml(trimmed, { lang: lang || "text", theme: darkModeThemes.dark }).replace('<pre class="shiki', '<pre class="slidev-code shiki shiki-dark');
1329
+ const light = _highlighter.codeToHtml(trimmed, { lang: lang || "text", theme: darkModeThemes.light }).replace('<pre class="shiki', '<pre class="slidev-code shiki shiki-light');
1330
+ return escapeVueInCode(`<pre class="shiki-container">${dark}${light}</pre>`);
1331
+ } else {
1332
+ return escapeVueInCode(
1333
+ _highlighter.codeToHtml(code, { lang: lang || "text" }).replace('<pre class="shiki"', '<pre class="slidev-code shiki"')
1334
+ );
1335
+ }
1336
+ };
1337
+ };
1338
+ var markdown_it_shiki_default = MarkdownItShiki;
1339
+
1340
+ // node/plugins/markdown.ts
1341
+ var DEFAULT_SHIKI_OPTIONS = {
1342
+ theme: {
1343
+ dark: "min-dark",
1344
+ light: "min-light"
1345
+ }
1346
+ };
1347
+ async function createMarkdownPlugin({ data: { config }, roots, mode, entry }, { markdown: mdOptions }) {
1348
+ const setups = [];
1349
+ const entryPath = slash4(entry);
1350
+ if (config.highlighter === "shiki") {
1351
+ const Shiki = await import("shiki");
1352
+ const shikiOptions = await loadSetups(roots, "shiki.ts", Shiki, DEFAULT_SHIKI_OPTIONS, false);
1353
+ const { langs, themes } = resolveShikiOptions(shikiOptions);
1354
+ shikiOptions.highlighter = await Shiki.getHighlighter({ themes, langs });
1355
+ setups.push((md2) => md2.use(markdown_it_shiki_default, shikiOptions));
1356
+ } else {
1357
+ setups.push((md2) => md2.use(markdownItPrism));
1358
+ }
1359
+ if (config.mdc)
1360
+ setups.push((md2) => md2.use(Mdc));
1361
+ const KatexOptions = await loadSetups(roots, "katex.ts", {}, { strict: false }, false);
1362
+ return Markdown2({
1363
+ include: [/\.md$/],
1364
+ wrapperClasses: "",
1365
+ headEnabled: false,
1366
+ frontmatter: false,
1367
+ markdownItOptions: {
1368
+ quotes: `""''`,
1369
+ html: true,
1370
+ xhtmlOut: true,
1371
+ linkify: true,
1372
+ ...mdOptions?.markdownItOptions
1373
+ },
1374
+ ...mdOptions,
1375
+ markdownItSetup(md2) {
1376
+ md2.use(mila2, {
1377
+ attrs: {
1378
+ target: "_blank",
1379
+ rel: "noopener"
1380
+ }
1381
+ });
1382
+ md2.use(mif);
1383
+ md2.use(taskLists, { enabled: true, lineNumber: true, label: true });
1384
+ md2.use(math_plugin, KatexOptions);
1385
+ setups.forEach((i) => i(md2));
1386
+ mdOptions?.markdownItSetup?.(md2);
1387
+ },
1388
+ transforms: {
1389
+ before(code, id) {
1390
+ if (id === entryPath)
1391
+ return "";
1392
+ const monaco = config.monaco === true || config.monaco === mode ? transformMarkdownMonaco : truncateMancoMark;
1393
+ code = transformSlotSugar(code);
1394
+ code = transformMermaid(code);
1395
+ code = transformPlantUml(code, config.plantUmlServer);
1396
+ code = monaco(code);
1397
+ code = transformHighlighter(code);
1398
+ code = transformPageCSS(code, id);
1399
+ return code;
1400
+ }
1401
+ }
1402
+ });
1403
+ }
1404
+ function transformMarkdownMonaco(md2) {
1405
+ md2 = md2.replace(/^```(\w+?)\s*{monaco-diff}\s*?({.*?})?\s*?\n([\s\S]+?)^~~~\s*?\n([\s\S]+?)^```/mg, (full, lang = "ts", options = "{}", code, diff) => {
1406
+ lang = lang.trim();
1407
+ options = options.trim() || "{}";
1408
+ const encoded = base64.encode(code, true);
1409
+ const encodedDiff = base64.encode(diff, true);
1410
+ return `<Monaco :code="'${encoded}'" :diff="'${encodedDiff}'" lang="${lang}" v-bind="${options}" />`;
1411
+ });
1412
+ md2 = md2.replace(/^```(\w+?)\s*{monaco}\s*?({.*?})?\s*?\n([\s\S]+?)^```/mg, (full, lang = "ts", options = "{}", code) => {
1413
+ lang = lang.trim();
1414
+ options = options.trim() || "{}";
1415
+ const encoded = base64.encode(code, true);
1416
+ return `<Monaco :code="'${encoded}'" lang="${lang}" v-bind="${options}" />`;
1417
+ });
1418
+ return md2;
1419
+ }
1420
+ function truncateMancoMark(md2) {
1421
+ return md2.replace(/{monaco.*?}/g, "");
1422
+ }
1423
+ function transformSlotSugar(md2) {
1424
+ const lines = md2.split(/\r?\n/g);
1425
+ let prevSlot = false;
1426
+ const { isLineInsideCodeblocks } = getCodeBlocks(md2);
1427
+ lines.forEach((line, idx) => {
1428
+ if (isLineInsideCodeblocks(idx))
1429
+ return;
1430
+ const match = line.trimEnd().match(/^::\s*(\w+)\s*::$/);
1431
+ if (match) {
1432
+ lines[idx] = `${prevSlot ? "\n\n</template>\n" : "\n"}<template v-slot:${match[1]}="slotProps">
1433
+ `;
1434
+ prevSlot = true;
1435
+ }
1436
+ });
1437
+ if (prevSlot)
1438
+ lines[lines.length - 1] += "\n\n</template>";
1439
+ return lines.join("\n");
1440
+ }
1441
+ function transformHighlighter(md2) {
1442
+ return md2.replace(/^```(\w+?)(?:\s*{([\d\w*,\|-]+)}\s*?({.*?})?\s*?)?\n([\s\S]+?)^```/mg, (full, lang = "", rangeStr = "", options = "", code) => {
1443
+ const ranges = rangeStr.split(/\|/g).map((i) => i.trim());
1444
+ code = code.trimEnd();
1445
+ options = options.trim() || "{}";
1446
+ return `
1447
+ <CodeBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1448
+
1449
+ \`\`\`${lang}
1450
+ ${code}
1451
+ \`\`\`
1452
+
1453
+ </CodeBlockWrapper>`;
1454
+ });
1455
+ }
1456
+ function getCodeBlocks(md2) {
1457
+ const codeblocks = Array.from(md2.matchAll(/^```[\s\S]*?^```/mg)).map((m) => {
1458
+ const start = m.index;
1459
+ const end = m.index + m[0].length;
1460
+ const startLine = md2.slice(0, start).match(/\n/g)?.length || 0;
1461
+ const endLine = md2.slice(0, end).match(/\n/g)?.length || 0;
1462
+ return [start, end, startLine, endLine];
1463
+ });
1464
+ return {
1465
+ codeblocks,
1466
+ isInsideCodeblocks(idx) {
1467
+ return codeblocks.some(([s, e]) => s <= idx && idx <= e);
1468
+ },
1469
+ isLineInsideCodeblocks(line) {
1470
+ return codeblocks.some(([, , s, e]) => s <= line && line <= e);
1471
+ }
1472
+ };
1473
+ }
1474
+ function transformPageCSS(md2, id) {
1475
+ const page = id.match(/(\d+)\.md$/)?.[1];
1476
+ if (!page)
1477
+ return md2;
1478
+ const { isInsideCodeblocks } = getCodeBlocks(md2);
1479
+ const result = md2.replace(
1480
+ /(\n<style[^>]*?>)([\s\S]+?)(<\/style>)/g,
1481
+ (full, start, css, end, index) => {
1482
+ if (index < 0 || isInsideCodeblocks(index))
1483
+ return full;
1484
+ if (!start.includes("scoped"))
1485
+ start = start.replace("<style", "<style scoped");
1486
+ return `${start}
1487
+ ${css}${end}`;
1488
+ }
1489
+ );
1490
+ return result;
1491
+ }
1492
+ function transformMermaid(md2) {
1493
+ return md2.replace(/^```mermaid\s*?({.*?})?\n([\s\S]+?)\n```/mg, (full, options = "", code = "") => {
1494
+ code = code.trim();
1495
+ options = options.trim() || "{}";
1496
+ const encoded = base64.encode(code, true);
1497
+ return `<Mermaid :code="'${encoded}'" v-bind="${options}" />`;
1498
+ });
1499
+ }
1500
+ function transformPlantUml(md2, server) {
1501
+ return md2.replace(/^```plantuml\s*?({.*?})?\n([\s\S]+?)\n```/mg, (full, options = "", content = "") => {
1502
+ const code = encode2(content.trim());
1503
+ options = options.trim() || "{}";
1504
+ return `<PlantUml :code="'${code}'" :server="'${server}'" v-bind="${options}" />`;
1505
+ });
1506
+ }
1507
+ function escapeVueInCode(md2) {
1508
+ return md2.replace(/{{(.*?)}}/g, "&lbrace;&lbrace;$1&rbrace;&rbrace;");
1509
+ }
1510
+
1511
+ // node/plugins/patchTransform.ts
1512
+ import { objectEntries } from "@antfu/utils";
1513
+ function createFixPlugins(options) {
1514
+ const define = objectEntries(getDefine(options));
1515
+ return [
1516
+ {
1517
+ name: "slidev:flags",
1518
+ enforce: "pre",
1519
+ transform(code, id) {
1520
+ if (id.match(/\.vue($|\?)/)) {
1521
+ const original = code;
1522
+ define.forEach(([from, to]) => {
1523
+ code = code.replace(new RegExp(from, "g"), to);
1524
+ });
1525
+ if (original !== code)
1526
+ return code;
1527
+ }
1528
+ }
1529
+ }
1530
+ ];
1531
+ }
1532
+
1533
+ // node/plugins/preset.ts
1534
+ var customElements = /* @__PURE__ */ new Set([
1535
+ // katex
1536
+ "annotation",
1537
+ "math",
1538
+ "menclose",
1539
+ "mfrac",
1540
+ "mglyph",
1541
+ "mi",
1542
+ "mlabeledtr",
1543
+ "mn",
1544
+ "mo",
1545
+ "mover",
1546
+ "mpadded",
1547
+ "mphantom",
1548
+ "mroot",
1549
+ "mrow",
1550
+ "mspace",
1551
+ "msqrt",
1552
+ "mstyle",
1553
+ "msub",
1554
+ "msubsup",
1555
+ "msup",
1556
+ "mtable",
1557
+ "mtd",
1558
+ "mtext",
1559
+ "mtr",
1560
+ "munder",
1561
+ "munderover",
1562
+ "semantics"
1563
+ ]);
1564
+ async function ViteSlidevPlugin(options, pluginOptions, serverOptions = {}) {
1565
+ const {
1566
+ vue: vueOptions = {},
1567
+ vuejsx: vuejsxOptions = {},
1568
+ components: componentsOptions = {},
1569
+ icons: iconsOptions = {},
1570
+ remoteAssets: remoteAssetsOptions = {},
1571
+ serverRef: serverRefOptions = {}
1572
+ } = pluginOptions;
1573
+ const {
1574
+ mode,
1575
+ themeRoots,
1576
+ addonRoots,
1577
+ clientRoot,
1578
+ data: { config }
1579
+ } = options;
1580
+ const VuePlugin = Vue({
1581
+ include: [/\.vue$/, /\.md$/],
1582
+ exclude: [],
1583
+ template: {
1584
+ compilerOptions: {
1585
+ isCustomElement(tag) {
1586
+ return customElements.has(tag);
1587
+ }
1588
+ },
1589
+ ...vueOptions?.template
1590
+ },
1591
+ ...vueOptions
1592
+ });
1593
+ const VueJsxPlugin = VueJsx(vuejsxOptions);
1594
+ const MarkdownPlugin = await createMarkdownPlugin(options, pluginOptions);
1595
+ const drawingData = await loadDrawings(options);
1596
+ const publicRoots = themeRoots.map((i) => join8(i, "public")).filter(existsSync4);
1597
+ const plugins = [
1598
+ MarkdownPlugin,
1599
+ VueJsxPlugin,
1600
+ VuePlugin,
1601
+ createSlidesLoader(options, pluginOptions, serverOptions),
1602
+ Components({
1603
+ extensions: ["vue", "md", "js", "ts", "jsx", "tsx"],
1604
+ dirs: [
1605
+ join8(clientRoot, "builtin"),
1606
+ join8(clientRoot, "components"),
1607
+ ...themeRoots.map((i) => join8(i, "components")),
1608
+ ...addonRoots.map((i) => join8(i, "components")),
1609
+ "src/components",
1610
+ "components"
1611
+ ],
1612
+ include: [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/, /\.md$/],
1613
+ exclude: [],
1614
+ resolvers: [
1615
+ IconsResolver({
1616
+ prefix: "",
1617
+ customCollections: Object.keys(iconsOptions.customCollections || [])
1618
+ })
1619
+ ],
1620
+ dts: false,
1621
+ ...componentsOptions
1622
+ }),
1623
+ Icons({
1624
+ defaultClass: "slidev-icon",
1625
+ autoInstall: true,
1626
+ ...iconsOptions
1627
+ }),
1628
+ config.remoteAssets === true || config.remoteAssets === mode ? import("vite-plugin-remote-assets").then((r) => r.default({
1629
+ rules: [
1630
+ ...r.DefaultRules,
1631
+ {
1632
+ match: /\b(https?:\/\/image.unsplash\.com.*?)(?=[`'")\]])/ig,
1633
+ ext: ".png"
1634
+ }
1635
+ ],
1636
+ resolveMode: (id) => id.endsWith("index.html") ? "relative" : "@fs",
1637
+ awaitDownload: mode === "build",
1638
+ ...remoteAssetsOptions
1639
+ })) : null,
1640
+ ServerRef({
1641
+ debug: process3.env.NODE_ENV === "development",
1642
+ state: {
1643
+ sync: false,
1644
+ nav: {
1645
+ page: 0,
1646
+ clicks: 0
1647
+ },
1648
+ drawings: drawingData,
1649
+ ...serverRefOptions.state
1650
+ },
1651
+ onChanged(key, data, patch, timestamp) {
1652
+ serverRefOptions.onChanged && serverRefOptions.onChanged(key, data, patch, timestamp);
1653
+ if (!options.data.config.drawings.persist)
1654
+ return;
1655
+ if (key === "drawings")
1656
+ writeDrawings(options, patch ?? data);
1657
+ }
1658
+ }),
1659
+ createConfigPlugin(options),
1660
+ createClientSetupPlugin(options),
1661
+ createMonacoTypesLoader(),
1662
+ createFixPlugins(options),
1663
+ publicRoots.length ? import("vite-plugin-static-copy").then((r) => r.viteStaticCopy({
1664
+ silent: true,
1665
+ targets: publicRoots.map((r2) => ({
1666
+ src: `${r2}/*`,
1667
+ dest: "theme"
1668
+ }))
1669
+ })) : null,
1670
+ options.inspect ? import("vite-plugin-inspect").then((r) => (r.default || r)({
1671
+ dev: true,
1672
+ build: true
1673
+ })) : null,
1674
+ config.css === "none" ? null : config.css === "windicss" ? import("./windicss-UVXCUIV4.mjs").then((r) => r.createWindiCSSPlugin(options, pluginOptions)) : import("./unocss-2UOAV4VT.mjs").then((r) => r.createUnocssPlugin(options, pluginOptions))
1675
+ ];
1676
+ return (await Promise.all(plugins)).flat().filter(notNullish2);
1677
+ }
1678
+
1679
+ export {
1680
+ getIndexHtml,
1681
+ mergeViteConfigs,
1682
+ require_fast_deep_equal,
1683
+ ViteSlidevPlugin
1684
+ };