@slidev/cli 0.49.29 → 0.50.0-beta.1

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.
@@ -11,10 +11,79 @@ import {
11
11
  resolveImportPath,
12
12
  resolveImportUrl,
13
13
  toAtFS
14
- } from "./chunk-HOVIRHCR.js";
14
+ } from "./chunk-UNQ5DBLZ.js";
15
+
16
+ // package.json
17
+ var version = "0.50.0-beta.1";
18
+
19
+ // node/integrations/themes.ts
20
+ import { join } from "node:path";
21
+ import fs from "fs-extra";
22
+ import { satisfies } from "semver";
23
+ var officialThemes = {
24
+ "none": "",
25
+ "default": "@slidev/theme-default",
26
+ "seriph": "@slidev/theme-seriph",
27
+ "apple-basic": "@slidev/theme-apple-basic",
28
+ "shibainu": "@slidev/theme-shibainu",
29
+ "bricks": "@slidev/theme-bricks"
30
+ };
31
+ var resolveTheme = createResolver("theme", officialThemes);
32
+ async function getThemeMeta(name, root) {
33
+ const path4 = join(root, "package.json");
34
+ if (!fs.existsSync(path4))
35
+ return {};
36
+ const { slidev = {}, engines = {} } = await fs.readJSON(path4);
37
+ if (engines.slidev && !satisfies(version, engines.slidev, { includePrerelease: true }))
38
+ throw new Error(`[slidev] theme "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`);
39
+ return slidev;
40
+ }
41
+
42
+ // node/parser.ts
43
+ import * as parser from "@slidev/parser/fs";
44
+
45
+ // node/options.ts
46
+ import path3 from "node:path";
47
+ import { uniq as uniq5 } from "@antfu/utils";
48
+ import Debug from "debug";
49
+ import fg4 from "fast-glob";
50
+ import mm from "micromatch";
51
+
52
+ // node/integrations/addons.ts
53
+ import { resolve } from "node:path";
54
+ import fs2 from "fs-extra";
55
+ import { satisfies as satisfies2 } from "semver";
56
+ async function resolveAddons(addonsInConfig) {
57
+ const { userRoot, userPkgJson } = await getRoots();
58
+ const resolved = [];
59
+ const resolveAddonNameAndRoot = createResolver("addon", {});
60
+ async function resolveAddon(name, parent) {
61
+ const [, pkgRoot] = await resolveAddonNameAndRoot(name, parent);
62
+ if (!pkgRoot)
63
+ return;
64
+ resolved.push(pkgRoot);
65
+ const { slidev = {}, engines = {} } = await fs2.readJSON(resolve(pkgRoot, "package.json"));
66
+ if (engines.slidev && !satisfies2(version, engines.slidev, { includePrerelease: true }))
67
+ throw new Error(`[slidev] addon "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`);
68
+ if (Array.isArray(slidev.addons))
69
+ await Promise.all(slidev.addons.map((addon) => resolveAddon(addon, pkgRoot)));
70
+ }
71
+ if (Array.isArray(addonsInConfig))
72
+ await Promise.all(addonsInConfig.map((addon) => resolveAddon(addon, userRoot)));
73
+ if (Array.isArray(userPkgJson.slidev?.addons))
74
+ await Promise.all(userPkgJson.slidev.addons.map((addon) => resolveAddon(addon, userRoot)));
75
+ return resolved;
76
+ }
77
+
78
+ // node/setups/indexHtml.ts
79
+ import { existsSync as existsSync8, readFileSync as readFileSync2 } from "node:fs";
80
+ import { join as join13 } from "node:path";
81
+ import { slash as slash4 } from "@antfu/utils";
82
+ import { white, yellow as yellow2 } from "kolorist";
83
+ import { escapeHtml } from "markdown-it/lib/common/utils.mjs";
15
84
 
16
85
  // node/commands/shared.ts
17
- import { existsSync as existsSync8 } from "node:fs";
86
+ import { existsSync as existsSync7 } from "node:fs";
18
87
  import { join as join12 } from "node:path";
19
88
  import MarkdownIt from "markdown-it";
20
89
  import { loadConfigFromFile, mergeConfig as mergeConfig2 } from "vite";
@@ -45,12 +114,12 @@ function MarkdownItLink(md) {
45
114
 
46
115
  // node/utils.ts
47
116
  import { fileURLToPath } from "node:url";
117
+ import { createJiti } from "jiti";
48
118
  import YAML from "yaml";
49
- import createJiti from "jiti";
50
119
  var jiti;
51
120
  function loadModule(absolutePath) {
52
121
  jiti ??= createJiti(fileURLToPath(import.meta.url));
53
- return jiti(absolutePath);
122
+ return jiti.import(absolutePath);
54
123
  }
55
124
  function stringifyMarkdownTokens(tokens) {
56
125
  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(" ");
@@ -94,13 +163,13 @@ function updateFrontmatterPatch(slide, frontmatter) {
94
163
  }
95
164
  }
96
165
  function getBodyJson(req) {
97
- return new Promise((resolve8, reject) => {
166
+ return new Promise((resolve9, reject) => {
98
167
  let body = "";
99
168
  req.on("data", (chunk) => body += chunk);
100
169
  req.on("error", reject);
101
170
  req.on("end", () => {
102
171
  try {
103
- resolve8(JSON.parse(body) || {});
172
+ resolve9(JSON.parse(body) || {});
104
173
  } catch (e) {
105
174
  reject(e);
106
175
  }
@@ -112,11 +181,11 @@ function getBodyJson(req) {
112
181
  import { objectEntries } from "@antfu/utils";
113
182
 
114
183
  // node/vite/extendConfig.ts
115
- import { join } from "node:path";
184
+ import { join as join2 } from "node:path";
116
185
  import { fileURLToPath as fileURLToPath2, pathToFileURL } from "node:url";
117
- import { mergeConfig } from "vite";
118
186
  import { slash, uniq } from "@antfu/utils";
119
187
  import { createResolve } from "mlly";
188
+ import { mergeConfig } from "vite";
120
189
  var INCLUDE_GLOBAL = [
121
190
  "@typescript/ata",
122
191
  "file-saver",
@@ -226,7 +295,7 @@ function createConfigPlugin(options) {
226
295
  ])
227
296
  }
228
297
  },
229
- publicDir: join(options.userRoot, "public"),
298
+ publicDir: join2(options.userRoot, "public"),
230
299
  build: {
231
300
  rollupOptions: {
232
301
  output: {
@@ -259,7 +328,7 @@ function createConfigPlugin(options) {
259
328
  return id.includes("/@slidev/") || id.includes("/slidev/packages/client/") || id.includes("/@vueuse/");
260
329
  }
261
330
  if (isInstalledGlobally.value) {
262
- injection.cacheDir = join(options.cliRoot, "node_modules/.vite");
331
+ injection.cacheDir = join2(options.cliRoot, "node_modules/.vite");
263
332
  injection.root = options.cliRoot;
264
333
  }
265
334
  return mergeConfig(injection, config);
@@ -317,15 +386,15 @@ function createVueCompilerFlagsPlugin(options) {
317
386
  }
318
387
 
319
388
  // node/vite/components.ts
320
- import { join as join2 } from "node:path";
389
+ import { join as join3 } from "node:path";
321
390
  import IconsResolver from "unplugin-icons/resolver";
322
391
  import Components from "unplugin-vue-components/vite";
323
392
  function createComponentsPlugin({ clientRoot, roots }, pluginOptions) {
324
393
  return Components({
325
394
  extensions: ["vue", "md", "js", "ts", "jsx", "tsx"],
326
395
  dirs: [
327
- join2(clientRoot, "builtin"),
328
- ...roots.map((i) => join2(i, "components"))
396
+ join3(clientRoot, "builtin"),
397
+ ...roots.map((i) => join3(i, "components"))
329
398
  ],
330
399
  include: [/\.vue$/, /\.vue\?vue/, /\.vue\?v=/, /\.md$/, /\.md\?vue/],
331
400
  exclude: [],
@@ -541,14 +610,14 @@ console.warn('/@slidev/titles.md is deprecated, import from #slidev/title-render
541
610
 
542
611
  // node/virtual/global-layers.ts
543
612
  import { existsSync } from "node:fs";
544
- import { join as join3 } from "node:path";
613
+ import { join as join4 } from "node:path";
545
614
  var templateGlobalLayers = {
546
615
  id: `/@slidev/global-layers`,
547
616
  getContent({ roots }) {
548
617
  const imports = [];
549
618
  let n = 0;
550
619
  function getComponent(names) {
551
- const components = roots.flatMap((root) => names.map((name) => join3(root, name))).filter((i) => existsSync(i));
620
+ const components = roots.flatMap((root) => names.map((name) => join4(root, name))).filter((i) => existsSync(i));
552
621
  imports.push(components.map((path4, i) => `import __n${n}_${i} from '${toAtFS(path4)}'`).join("\n"));
553
622
  const render = components.map((_, i) => `h(__n${n}_${i})`).join(",");
554
623
  n++;
@@ -569,28 +638,6 @@ var templateGlobalLayers = {
569
638
  }
570
639
  };
571
640
 
572
- // node/virtual/nav-controls.ts
573
- import { existsSync as existsSync2 } from "node:fs";
574
- import { join as join4 } from "node:path";
575
- var templateNavControls = {
576
- id: "/@slidev/custom-nav-controls",
577
- getContent({ roots }) {
578
- const components = roots.flatMap((root) => {
579
- return [
580
- join4(root, "custom-nav-controls.vue"),
581
- join4(root, "CustomNavControls.vue")
582
- ];
583
- }).filter((i) => existsSync2(i));
584
- const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
585
- const render = components.map((i, idx) => `h(__n${idx})`).join(",");
586
- return `${imports}
587
- import { h } from 'vue'
588
- export default {
589
- render: () => [${render}],
590
- }`;
591
- }
592
- };
593
-
594
641
  // node/virtual/layouts.ts
595
642
  import { objectMap } from "@antfu/utils";
596
643
  var templateLayouts = {
@@ -614,7 +661,7 @@ ${Object.entries(layouts).map(([k, v]) => `"${k}": ${v}`).join(",\n")}
614
661
  };
615
662
 
616
663
  // node/virtual/monaco-deps.ts
617
- import { resolve } from "node:path";
664
+ import { resolve as resolve2 } from "node:path";
618
665
  import { uniq as uniq2 } from "@antfu/utils";
619
666
  var templateMonacoRunDeps = {
620
667
  id: "/@slidev/monaco-run-deps",
@@ -622,7 +669,7 @@ var templateMonacoRunDeps = {
622
669
  if (!data.features.monaco)
623
670
  return "";
624
671
  const deps = uniq2(data.features.monaco.deps.concat(data.config.monacoTypesAdditionalPackages));
625
- const importerPath = resolve(userRoot, "./snippets/__importer__.ts");
672
+ const importerPath = resolve2(userRoot, "./snippets/__importer__.ts");
626
673
  let result = "";
627
674
  for (let i = 0; i < deps.length; i++) {
628
675
  const specifier = deps[i];
@@ -643,9 +690,9 @@ var templateMonacoRunDeps = {
643
690
 
644
691
  // node/virtual/monaco-types.ts
645
692
  import { builtinModules } from "node:module";
646
- import { join as join5, resolve as resolve2 } from "node:path";
647
- import fg from "fast-glob";
693
+ import { join as join5, resolve as resolve3 } from "node:path";
648
694
  import { uniq as uniq3 } from "@antfu/utils";
695
+ import fg from "fast-glob";
649
696
  var templateMonacoTypes = {
650
697
  id: "/@slidev/monaco-types",
651
698
  getContent: async ({ userRoot, data, utils }) => {
@@ -655,7 +702,7 @@ var templateMonacoTypes = {
655
702
  const files = await fg(["**/*.ts", "**/*.mts", "**/*.cts"], { cwd: typesRoot });
656
703
  let result = 'import { addFile } from "@slidev/client/setup/monaco.ts"\n';
657
704
  for (const file of files) {
658
- const url = `${toAtFS(resolve2(typesRoot, file))}?monaco-types&raw`;
705
+ const url = `${toAtFS(resolve3(typesRoot, file))}?monaco-types&raw`;
659
706
  result += `addFile(() => import(${JSON.stringify(url)}), ${JSON.stringify(file)})
660
707
  `;
661
708
  }
@@ -688,15 +735,37 @@ var templateMonacoTypes = {
688
735
  }
689
736
  };
690
737
 
738
+ // node/virtual/nav-controls.ts
739
+ import { existsSync as existsSync2 } from "node:fs";
740
+ import { join as join6 } from "node:path";
741
+ var templateNavControls = {
742
+ id: "/@slidev/custom-nav-controls",
743
+ getContent({ roots }) {
744
+ const components = roots.flatMap((root) => {
745
+ return [
746
+ join6(root, "custom-nav-controls.vue"),
747
+ join6(root, "CustomNavControls.vue")
748
+ ];
749
+ }).filter((i) => existsSync2(i));
750
+ const imports = components.map((i, idx) => `import __n${idx} from '${toAtFS(i)}'`).join("\n");
751
+ const render = components.map((i, idx) => `h(__n${idx})`).join(",");
752
+ return `${imports}
753
+ import { h } from 'vue'
754
+ export default {
755
+ render: () => [${render}],
756
+ }`;
757
+ }
758
+ };
759
+
691
760
  // node/virtual/setups.ts
692
761
  import { existsSync as existsSync3 } from "node:fs";
693
- import { join as join6 } from "node:path";
762
+ import { join as join7 } from "node:path";
694
763
  function createSetupTemplate(name) {
695
764
  return {
696
765
  id: `/@slidev/setups/${name}`,
697
766
  getContent({ roots }) {
698
767
  const setups = roots.flatMap((i) => {
699
- const path4 = join6(i, "setup", name);
768
+ const path4 = join7(i, "setup", name);
700
769
  return [".ts", ".mts", ".js", ".mjs"].map((ext) => path4 + ext);
701
770
  }).filter((i) => existsSync3(i));
702
771
  const imports = [];
@@ -820,13 +889,13 @@ ${slides.join(",\n")}
820
889
  };
821
890
 
822
891
  // node/virtual/styles.ts
823
- import { join as join7 } from "node:path";
824
892
  import { existsSync as existsSync4 } from "node:fs";
893
+ import { join as join8 } from "node:path";
825
894
  var templateStyle = {
826
895
  id: "/@slidev/styles",
827
896
  async getContent({ data, clientRoot, roots }) {
828
897
  function resolveUrlOfClient(name) {
829
- return toAtFS(join7(clientRoot, name));
898
+ return toAtFS(join8(clientRoot, name));
830
899
  }
831
900
  const imports = [
832
901
  `import "${resolveUrlOfClient("styles/vars.css")}"`,
@@ -837,11 +906,11 @@ var templateStyle = {
837
906
  ];
838
907
  for (const root of roots) {
839
908
  const styles = [
840
- join7(root, "styles", "index.ts"),
841
- join7(root, "styles", "index.js"),
842
- join7(root, "styles", "index.css"),
843
- join7(root, "styles.css"),
844
- join7(root, "style.css")
909
+ join8(root, "styles", "index.ts"),
910
+ join8(root, "styles", "index.js"),
911
+ join8(root, "styles", "index.css"),
912
+ join8(root, "styles.css"),
913
+ join8(root, "style.css")
845
914
  ];
846
915
  for (const style of styles) {
847
916
  if (existsSync4(style)) {
@@ -917,300 +986,40 @@ var templates = [
917
986
  templateLegacyTitles
918
987
  ];
919
988
 
920
- // node/options.ts
921
- import path from "node:path";
922
- import { uniq as uniq5 } from "@antfu/utils";
923
- import Debug from "debug";
924
- import mm from "micromatch";
925
- import fg2 from "fast-glob";
926
-
927
- // node/parser.ts
928
- import * as parser from "@slidev/parser/fs";
929
-
930
- // node/integrations/themes.ts
931
- import { join as join8 } from "node:path";
932
- import fs from "fs-extra";
933
- import { satisfies } from "semver";
934
-
935
- // package.json
936
- var version = "0.49.29";
937
-
938
- // node/integrations/themes.ts
939
- var officialThemes = {
940
- "none": "",
941
- "default": "@slidev/theme-default",
942
- "seriph": "@slidev/theme-seriph",
943
- "apple-basic": "@slidev/theme-apple-basic",
944
- "shibainu": "@slidev/theme-shibainu",
945
- "bricks": "@slidev/theme-bricks"
946
- };
947
- var resolveTheme = createResolver("theme", officialThemes);
948
- async function getThemeMeta(name, root) {
949
- const path4 = join8(root, "package.json");
950
- if (!fs.existsSync(path4))
951
- return {};
952
- const { slidev = {}, engines = {} } = await fs.readJSON(path4);
953
- if (engines.slidev && !satisfies(version, engines.slidev, { includePrerelease: true }))
954
- throw new Error(`[slidev] theme "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`);
955
- return slidev;
989
+ // node/vite/loaders.ts
990
+ function renderNote(text = "") {
991
+ let clickCount = 0;
992
+ const html = sharedMd.render(
993
+ text.replace(/\[click(?::(\d+))?\]/gi, (_, count = 1) => {
994
+ clickCount += Number(count);
995
+ return `<span class="slidev-note-click-mark" data-clicks="${clickCount}"></span>`;
996
+ })
997
+ );
998
+ return html;
956
999
  }
957
-
958
- // node/integrations/addons.ts
959
- import { resolve as resolve3 } from "node:path";
960
- import fs2 from "fs-extra";
961
- import { satisfies as satisfies2 } from "semver";
962
- async function resolveAddons(addonsInConfig) {
963
- const { userRoot, userPkgJson } = await getRoots();
964
- const resolved = [];
965
- const resolveAddonNameAndRoot = createResolver("addon", {});
966
- async function resolveAddon(name, parent) {
967
- const [, pkgRoot] = await resolveAddonNameAndRoot(name, parent);
968
- if (!pkgRoot)
969
- return;
970
- resolved.push(pkgRoot);
971
- const { slidev = {}, engines = {} } = await fs2.readJSON(resolve3(pkgRoot, "package.json"));
972
- if (engines.slidev && !satisfies2(version, engines.slidev, { includePrerelease: true }))
973
- throw new Error(`[slidev] addon "${name}" requires Slidev version range "${engines.slidev}" but found "${version}"`);
974
- if (Array.isArray(slidev.addons))
975
- await Promise.all(slidev.addons.map((addon) => resolveAddon(addon, pkgRoot)));
976
- }
977
- if (Array.isArray(addonsInConfig))
978
- await Promise.all(addonsInConfig.map((addon) => resolveAddon(addon, userRoot)));
979
- if (Array.isArray(userPkgJson.slidev?.addons))
980
- await Promise.all(userPkgJson.slidev.addons.map((addon) => resolveAddon(addon, userRoot)));
981
- return resolved;
1000
+ function withRenderedNote(data) {
1001
+ return {
1002
+ ...data,
1003
+ noteHTML: renderNote(data?.note)
1004
+ };
982
1005
  }
983
-
984
- // node/setups/shiki.ts
985
- import fs4 from "node:fs/promises";
986
- import { bundledLanguages, createHighlighter } from "shiki";
987
-
988
- // node/setups/load.ts
989
- import { resolve as resolve4 } from "node:path";
990
- import fs3 from "fs-extra";
991
- import { deepMergeWithArray } from "@antfu/utils";
992
- async function loadSetups(roots, filename, args, extraLoader) {
993
- const returns = [];
994
- for (const root of roots) {
995
- const path4 = resolve4(root, "setup", filename);
996
- if (fs3.existsSync(path4)) {
997
- const { default: setup } = loadModule(path4);
998
- const ret = await setup(...args);
999
- if (ret)
1000
- returns.push(ret);
1001
- }
1002
- if (extraLoader)
1003
- returns.push(...extraLoader(root));
1006
+ function createSlidesLoader(options, serverOptions) {
1007
+ const hmrSlidesIndexes = /* @__PURE__ */ new Set();
1008
+ let server;
1009
+ let skipHmr = null;
1010
+ const { data, mode, utils } = options;
1011
+ function getSourceId(index, type) {
1012
+ return `${data.slides[index].source.filepath}__slidev_${index + 1}.${type}`;
1004
1013
  }
1005
- return returns;
1006
- }
1007
-
1008
- // node/setups/shiki.ts
1009
- var cachedRoots;
1010
- var cachedShiki;
1011
- async function setupShiki(roots) {
1012
- if (cachedRoots === roots)
1013
- return cachedShiki;
1014
- cachedShiki?.shiki.dispose();
1015
- const options = await loadSetups(
1016
- roots,
1017
- "shiki.ts",
1018
- [{
1019
- /** @deprecated */
1020
- async loadTheme(path4) {
1021
- console.warn("[slidev] `loadTheme` in `setup/shiki.ts` is deprecated. Pass directly the theme name it's supported by Shiki. For custom themes, load it manually via `JSON.parse(fs.readFileSync(path, 'utf-8'))` and pass the raw JSON object instead.");
1022
- return JSON.parse(await fs4.readFile(path4, "utf-8"));
1023
- }
1024
- }]
1025
- );
1026
- const mergedOptions = Object.assign({}, ...options);
1027
- if ("theme" in mergedOptions && "themes" in mergedOptions)
1028
- delete mergedOptions.theme;
1029
- if (mergedOptions.theme && typeof mergedOptions.theme !== "string" && !mergedOptions.theme.name && !mergedOptions.theme.tokenColors) {
1030
- mergedOptions.themes = mergedOptions.theme;
1031
- delete mergedOptions.theme;
1014
+ function updateServerWatcher() {
1015
+ if (!server)
1016
+ return;
1017
+ server.watcher.add(Object.keys(data.watchFiles));
1032
1018
  }
1033
- if (!mergedOptions.theme && !mergedOptions.themes) {
1034
- mergedOptions.themes = {
1035
- dark: "vitesse-dark",
1036
- light: "vitesse-light"
1037
- };
1038
- }
1039
- if (mergedOptions.themes)
1040
- mergedOptions.defaultColor = false;
1041
- const shiki = await createHighlighter({
1042
- ...mergedOptions,
1043
- langs: mergedOptions.langs ?? Object.keys(bundledLanguages),
1044
- themes: "themes" in mergedOptions ? Object.values(mergedOptions.themes) : [mergedOptions.theme]
1045
- });
1046
- cachedRoots = roots;
1047
- return cachedShiki = {
1048
- shiki,
1049
- shikiOptions: mergedOptions
1050
- };
1051
- }
1052
-
1053
- // node/setups/indexHtml.ts
1054
- import { existsSync as existsSync5, readFileSync } from "node:fs";
1055
- import { join as join9 } from "node:path";
1056
- import { slash as slash2 } from "@antfu/utils";
1057
- import { white, yellow as yellow2 } from "kolorist";
1058
- import { escapeHtml } from "markdown-it/lib/common/utils.mjs";
1059
- function toAttrValue(unsafe) {
1060
- return JSON.stringify(escapeHtml(String(unsafe)));
1061
- }
1062
- function setupIndexHtml({ mode, entry, clientRoot, userRoot, roots, data }) {
1063
- let main = readFileSync(join9(clientRoot, "index.html"), "utf-8");
1064
- let head = "";
1065
- let body = "";
1066
- const { info, author, keywords } = data.headmatter;
1067
- head += [
1068
- `<meta name="slidev:version" content="${version}">`,
1069
- mode === "dev" && `<meta charset="slidev:entry" content="${slash2(entry)}">`,
1070
- `<link rel="icon" href="${data.config.favicon}">`,
1071
- `<title>${getSlideTitle(data)}</title>`,
1072
- info && `<meta name="description" content=${toAttrValue(info)}>`,
1073
- author && `<meta name="author" content=${toAttrValue(author)}>`,
1074
- keywords && `<meta name="keywords" content=${toAttrValue(Array.isArray(keywords) ? keywords.join(", ") : keywords)}>`
1075
- ].filter(Boolean).join("\n");
1076
- for (const root of roots) {
1077
- const path4 = join9(root, "index.html");
1078
- if (!existsSync5(path4))
1079
- continue;
1080
- const index = readFileSync(path4, "utf-8");
1081
- if (root === userRoot && index.includes("<!DOCTYPE")) {
1082
- console.error(yellow2(`[Slidev] Ignored provided index.html with doctype declaration. (${white(path4)})`));
1083
- console.error(yellow2("This file may be generated by Slidev, please remove it from your project."));
1084
- continue;
1085
- }
1086
- head += `
1087
- ${(index.match(/<head>([\s\S]*?)<\/head>/i)?.[1] || "").trim()}`;
1088
- body += `
1089
- ${(index.match(/<body>([\s\S]*?)<\/body>/i)?.[1] || "").trim()}`;
1090
- }
1091
- if (data.features.tweet)
1092
- body += '\n<script async src="https://platform.twitter.com/widgets.js"></script>';
1093
- if (data.config.fonts.webfonts.length && data.config.fonts.provider !== "none")
1094
- head += `
1095
- <link rel="stylesheet" href="${generateGoogleFontsUrl(data.config.fonts)}" type="text/css">`;
1096
- main = main.replace("__ENTRY__", toAtFS(join9(clientRoot, "main.ts"))).replace("<!-- head -->", head).replace("<!-- body -->", body);
1097
- return main;
1098
- }
1099
-
1100
- // node/options.ts
1101
- var debug = Debug("slidev:options");
1102
- async function resolveOptions(entryOptions, mode) {
1103
- const entry = await resolveEntry(entryOptions.entry);
1104
- const rootsInfo = await getRoots(entry);
1105
- const loaded = await parser.load(rootsInfo.userRoot, entry, void 0, mode);
1106
- let themeRaw = entryOptions.theme || loaded.headmatter.theme;
1107
- themeRaw = themeRaw === null ? "none" : themeRaw || "default";
1108
- const [theme, themeRoot] = await resolveTheme(themeRaw, entry);
1109
- const themeRoots = themeRoot ? [themeRoot] : [];
1110
- const themeMeta = themeRoot ? await getThemeMeta(theme, themeRoot) : void 0;
1111
- const config = parser.resolveConfig(loaded.headmatter, themeMeta, entryOptions.entry);
1112
- const addonRoots = await resolveAddons(config.addons);
1113
- const roots = uniq5([...themeRoots, ...addonRoots, rootsInfo.userRoot]);
1114
- debug({
1115
- ...rootsInfo,
1116
- ...entryOptions,
1117
- config,
1118
- mode,
1119
- entry,
1120
- themeRaw,
1121
- theme,
1122
- themeRoots,
1123
- addonRoots,
1124
- roots
1125
- });
1126
- const data = {
1127
- ...loaded,
1128
- config,
1129
- themeMeta
1130
- };
1131
- const resolved = {
1132
- ...rootsInfo,
1133
- ...entryOptions,
1134
- data,
1135
- mode,
1136
- entry,
1137
- themeRaw,
1138
- theme,
1139
- themeRoots,
1140
- addonRoots,
1141
- roots
1142
- };
1143
- return {
1144
- ...resolved,
1145
- utils: await createDataUtils(resolved)
1146
- };
1147
- }
1148
- async function createDataUtils(resolved) {
1149
- const monacoTypesIgnorePackagesMatches = (resolved.data.config.monacoTypesIgnorePackages || []).map((i) => mm.matcher(i));
1150
- let _layouts_cache_time = 0;
1151
- let _layouts_cache = {};
1152
- return {
1153
- ...await setupShiki(resolved.roots),
1154
- indexHtml: setupIndexHtml(resolved),
1155
- iconsResolvePath: [resolved.clientRoot, ...resolved.roots].reverse(),
1156
- isMonacoTypesIgnored: (pkg) => monacoTypesIgnorePackagesMatches.some((i) => i(pkg)),
1157
- getLayouts: () => {
1158
- const now = Date.now();
1159
- if (now - _layouts_cache_time < 2e3)
1160
- return _layouts_cache;
1161
- const layouts = {};
1162
- for (const root of [resolved.clientRoot, ...resolved.roots]) {
1163
- const layoutPaths = fg2.sync("layouts/**/*.{vue,ts}", {
1164
- cwd: root,
1165
- absolute: true,
1166
- suppressErrors: true
1167
- });
1168
- for (const layoutPath of layoutPaths) {
1169
- const layoutName = path.basename(layoutPath).replace(/\.\w+$/, "");
1170
- layouts[layoutName] = layoutPath;
1171
- }
1172
- }
1173
- _layouts_cache_time = now;
1174
- _layouts_cache = layouts;
1175
- return layouts;
1176
- }
1177
- };
1178
- }
1179
-
1180
- // node/vite/loaders.ts
1181
- function renderNote(text = "") {
1182
- let clickCount = 0;
1183
- const html = sharedMd.render(
1184
- text.replace(/\[click(?::(\d+))?\]/gi, (_, count = 1) => {
1185
- clickCount += Number(count);
1186
- return `<span class="slidev-note-click-mark" data-clicks="${clickCount}"></span>`;
1187
- })
1188
- );
1189
- return html;
1190
- }
1191
- function withRenderedNote(data) {
1192
- return {
1193
- ...data,
1194
- noteHTML: renderNote(data?.note)
1195
- };
1196
- }
1197
- function createSlidesLoader(options, serverOptions) {
1198
- const hmrSlidesIndexes = /* @__PURE__ */ new Set();
1199
- let server;
1200
- let skipHmr = null;
1201
- const { data, mode, utils } = options;
1202
- function getSourceId(index, type) {
1203
- return `${data.slides[index].source.filepath}__slidev_${index + 1}.${type}`;
1204
- }
1205
- function updateServerWatcher() {
1206
- if (!server)
1207
- return;
1208
- server.watcher.add(Object.keys(data.watchFiles));
1209
- }
1210
- function getFrontmatter(pageNo) {
1211
- return {
1212
- ...data.headmatter?.defaults || {},
1213
- ...data.slides[pageNo]?.frontmatter || {}
1019
+ function getFrontmatter(pageNo) {
1020
+ return {
1021
+ ...data.headmatter?.defaults || {},
1022
+ ...data.slides[pageNo]?.frontmatter || {}
1214
1023
  };
1215
1024
  }
1216
1025
  return {
@@ -1453,764 +1262,784 @@ function createSlidesLoader(options, serverOptions) {
1453
1262
  }
1454
1263
 
1455
1264
  // node/vite/markdown.ts
1456
- import Markdown from "unplugin-vue-markdown/vite";
1457
1265
  import MagicString from "magic-string-stack";
1266
+ import Markdown from "unplugin-vue-markdown/vite";
1458
1267
 
1459
- // node/setups/transformers.ts
1460
- async function setupTransformers(roots) {
1461
- const returns = await loadSetups(roots, "transformers.ts", []);
1462
- const result = {
1463
- pre: [],
1464
- preCodeblock: [],
1465
- postCodeblock: [],
1466
- post: []
1268
+ // ../../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
1269
+ var SpecialCharacters;
1270
+ (function(SpecialCharacters2) {
1271
+ SpecialCharacters2[SpecialCharacters2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
1272
+ SpecialCharacters2[SpecialCharacters2["OPENING_BRACKET"] = 91] = "OPENING_BRACKET";
1273
+ SpecialCharacters2[SpecialCharacters2["OPENING_PARENTHESIS"] = 40] = "OPENING_PARENTHESIS";
1274
+ SpecialCharacters2[SpecialCharacters2["WHITESPACE"] = 32] = "WHITESPACE";
1275
+ SpecialCharacters2[SpecialCharacters2["NEW_LINE"] = 10] = "NEW_LINE";
1276
+ SpecialCharacters2[SpecialCharacters2["EQUALS"] = 61] = "EQUALS";
1277
+ SpecialCharacters2[SpecialCharacters2["LOWER_CASE_X"] = 120] = "LOWER_CASE_X";
1278
+ SpecialCharacters2[SpecialCharacters2["NUMBER_ZERO"] = 48] = "NUMBER_ZERO";
1279
+ SpecialCharacters2[SpecialCharacters2["NUMBER_NINE"] = 57] = "NUMBER_NINE";
1280
+ SpecialCharacters2[SpecialCharacters2["PERCENTAGE"] = 37] = "PERCENTAGE";
1281
+ SpecialCharacters2[SpecialCharacters2["CLOSING_PARENTHESIS"] = 41] = "CLOSING_PARENTHESIS";
1282
+ })(SpecialCharacters || (SpecialCharacters = {}));
1283
+
1284
+ // ../../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
1285
+ import Token from "markdown-it/lib/token.mjs";
1286
+ var checkboxRegex = /^ *\[([\sx])] /i;
1287
+ function taskLists(md, options = { enabled: false, label: false, lineNumber: false }) {
1288
+ md.core.ruler.after("inline", "task-lists", (state) => processToken(state, options));
1289
+ md.renderer.rules.taskListItemCheckbox = (tokens) => {
1290
+ const token = tokens[0];
1291
+ const checkedAttribute = token.attrGet("checked") ? 'checked="" ' : "";
1292
+ const disabledAttribute = token.attrGet("disabled") ? 'disabled="" ' : "";
1293
+ const line = token.attrGet("line");
1294
+ const idAttribute = `id="${token.attrGet("id")}" `;
1295
+ const dataLineAttribute = line && options.lineNumber ? `data-line="${line}" ` : "";
1296
+ return `<input class="task-list-item-checkbox" type="checkbox" ${checkedAttribute}${disabledAttribute}${dataLineAttribute}${idAttribute}/>`;
1467
1297
  };
1468
- for (const r of [...returns].reverse()) {
1469
- if (r.pre)
1470
- result.pre.push(...r.pre);
1471
- if (r.preCodeblock)
1472
- result.preCodeblock.push(...r.preCodeblock);
1298
+ md.renderer.rules.taskListItemLabel_close = () => {
1299
+ return "</label>";
1300
+ };
1301
+ md.renderer.rules.taskListItemLabel_open = (tokens) => {
1302
+ const token = tokens[0];
1303
+ const id = token.attrGet("id");
1304
+ return `<label for="${id}">`;
1305
+ };
1306
+ }
1307
+ function processToken(state, options) {
1308
+ const allTokens = state.tokens;
1309
+ for (let i = 2; i < allTokens.length; i++) {
1310
+ if (!isTodoItem(allTokens, i)) {
1311
+ continue;
1312
+ }
1313
+ todoify(allTokens[i], options);
1314
+ allTokens[i - 2].attrJoin("class", `task-list-item ${options.enabled ? " enabled" : ""}`);
1315
+ const parentToken = findParentToken(allTokens, i - 2);
1316
+ if (parentToken) {
1317
+ const classes = parentToken.attrGet("class") ?? "";
1318
+ if (!classes.match(/(^| )contains-task-list/)) {
1319
+ parentToken.attrJoin("class", "contains-task-list");
1320
+ }
1321
+ }
1473
1322
  }
1474
- for (const r of returns) {
1475
- if (r.postCodeblock)
1476
- result.postCodeblock.push(...r.postCodeblock);
1477
- if (r.post)
1478
- result.post.push(...r.post);
1323
+ return false;
1324
+ }
1325
+ function findParentToken(tokens, index) {
1326
+ const targetLevel = tokens[index].level - 1;
1327
+ for (let currentTokenIndex = index - 1; currentTokenIndex >= 0; currentTokenIndex--) {
1328
+ if (tokens[currentTokenIndex].level === targetLevel) {
1329
+ return tokens[currentTokenIndex];
1330
+ }
1479
1331
  }
1480
- return result;
1332
+ return void 0;
1481
1333
  }
1482
-
1483
- // node/syntax/transform/code-wrapper.ts
1484
- var reCodeBlock = /^```([\w'-]+)?\s*(?:\{([\w*,|-]+)\}\s*?(\{[^}]*\})?([^\r\n]*))?\r?\n(\S[\s\S]*?)^```$/gm;
1485
- function transformCodeWrapper(ctx) {
1486
- ctx.s.replace(
1487
- reCodeBlock,
1488
- (full, lang = "", rangeStr = "", options = "", attrs = "", code) => {
1489
- const ranges = normalizeRangeStr(rangeStr);
1490
- code = code.trimEnd();
1491
- options = options.trim() || "{}";
1492
- return `
1493
- <CodeBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1494
-
1495
- \`\`\`${lang}${attrs}
1496
- ${code}
1497
- \`\`\`
1498
-
1499
- </CodeBlockWrapper>`;
1500
- }
1501
- );
1334
+ function isTodoItem(tokens, index) {
1335
+ return isInline(tokens[index]) && isParagraph(tokens[index - 1]) && isListItem(tokens[index - 2]) && startsWithTodoMarkdown(tokens[index]);
1502
1336
  }
1503
-
1504
- // node/syntax/transform/in-page-css.ts
1505
- function transformPageCSS(ctx) {
1506
- const codeBlocks = getCodeBlocks(ctx.s.original);
1507
- ctx.s.replace(
1508
- /(\n<style[^>]*>)([\s\S]+?)(<\/style>)/g,
1509
- (full, start, css, end, index) => {
1510
- if (codeBlocks.isInsideCodeblocks(index))
1511
- return full;
1512
- if (!start.includes("scoped"))
1513
- start = start.replace("<style", "<style scoped");
1514
- return `${start}
1515
- ${css}${end}`;
1516
- }
1517
- );
1337
+ function todoify(token, options) {
1338
+ if (token.children == null) {
1339
+ return;
1340
+ }
1341
+ const id = generateIdForToken(token);
1342
+ token.children.splice(0, 0, createCheckboxToken(token, options.enabled, id));
1343
+ token.children[1].content = token.children[1].content.replace(checkboxRegex, "");
1344
+ if (options.label) {
1345
+ token.children.splice(1, 0, createLabelBeginToken(id));
1346
+ token.children.push(createLabelEndToken());
1347
+ }
1518
1348
  }
1519
-
1520
- // node/syntax/transform/katex-wrapper.ts
1521
- function transformKaTexWrapper(ctx) {
1522
- ctx.s.replace(
1523
- /^\$\$(?:\s*\{([\w*,|-]+)\}\s*?(?:(\{[^}]*\})\s*?)?)?\n(\S[\s\S]*?)^\$\$/gm,
1524
- (full, rangeStr = "", options = "", code) => {
1525
- const ranges = !rangeStr.trim() ? [] : rangeStr.trim().split(/\|/g).map((i) => i.trim());
1526
- code = code.trimEnd();
1527
- options = options.trim() || "{}";
1528
- return `<KaTexBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1529
-
1530
- $$
1531
- ${code}
1532
- $$
1533
- </KaTexBlockWrapper>
1534
- `;
1535
- }
1536
- );
1349
+ function generateIdForToken(token) {
1350
+ if (token.map) {
1351
+ return `task-item-${token.map[0]}`;
1352
+ } else {
1353
+ return `task-item-${Math.ceil(Math.random() * (1e4 * 1e3) - 1e3)}`;
1354
+ }
1537
1355
  }
1538
-
1539
- // node/syntax/transform/magic-move.ts
1540
- import { codeToKeyedTokens } from "shiki-magic-move/core";
1541
- import lz from "lz-string";
1542
- var reMagicMoveBlock = /^````(?:md|markdown) magic-move *(\{[^}]*\})?([^ \n]*)\n([\s\S]+?)^````$/gm;
1543
- function parseLineNumbersOption(options) {
1544
- return /lines: *true/.test(options) ? true : /lines: *false/.test(options) ? false : void 0;
1356
+ function createCheckboxToken(token, enabled, id) {
1357
+ const checkbox = new Token("taskListItemCheckbox", "", 0);
1358
+ if (!enabled) {
1359
+ checkbox.attrSet("disabled", "true");
1360
+ }
1361
+ if (token.map) {
1362
+ checkbox.attrSet("line", token.map[0].toString());
1363
+ }
1364
+ checkbox.attrSet("id", id);
1365
+ const checkboxRegexResult = checkboxRegex.exec(token.content);
1366
+ const isChecked = checkboxRegexResult?.[1].toLowerCase() === "x";
1367
+ if (isChecked) {
1368
+ checkbox.attrSet("checked", "true");
1369
+ }
1370
+ return checkbox;
1545
1371
  }
1546
- function transformMagicMove(ctx) {
1547
- ctx.s.replace(
1548
- reMagicMoveBlock,
1549
- (full, options = "{}", _attrs = "", body) => {
1550
- const matches = Array.from(body.matchAll(reCodeBlock));
1551
- if (!matches.length)
1552
- throw new Error("Magic Move block must contain at least one code block");
1553
- const defaultLineNumbers = parseLineNumbersOption(options) ?? ctx.options.data.config.lineNumbers;
1554
- const ranges = matches.map((i) => normalizeRangeStr(i[2]));
1555
- const steps = matches.map((i) => {
1556
- const lineNumbers = parseLineNumbersOption(i[3]) ?? defaultLineNumbers;
1557
- return codeToKeyedTokens(ctx.options.utils.shiki, i[5].trimEnd(), {
1558
- ...ctx.options.utils.shikiOptions,
1559
- lang: i[1]
1560
- }, lineNumbers);
1561
- });
1562
- const compressed = lz.compressToBase64(JSON.stringify(steps));
1563
- return `<ShikiMagicMove v-bind="${options}" steps-lz="${compressed}" :step-ranges='${JSON.stringify(ranges)}' />`;
1564
- }
1565
- );
1372
+ function createLabelBeginToken(id) {
1373
+ const labelBeginToken = new Token("taskListItemLabel_open", "", 1);
1374
+ labelBeginToken.attrSet("id", id);
1375
+ return labelBeginToken;
1566
1376
  }
1567
-
1568
- // node/syntax/transform/mermaid.ts
1569
- import lz2 from "lz-string";
1570
- function transformMermaid(ctx) {
1571
- ctx.s.replace(
1572
- /^```mermaid *(\{[^\n]*\})?\n([\s\S]+?)\n```/gm,
1573
- (full, options = "", code = "") => {
1574
- code = code.trim();
1575
- options = options.trim() || "{}";
1576
- const encoded = lz2.compressToBase64(code);
1577
- return `<Mermaid code-lz="${encoded}" v-bind="${options}" />`;
1578
- }
1579
- );
1377
+ function createLabelEndToken() {
1378
+ return new Token("taskListItemLabel_close", "", -1);
1379
+ }
1380
+ function isInline(token) {
1381
+ return token.type === "inline";
1382
+ }
1383
+ function isParagraph(token) {
1384
+ return token.type === "paragraph_open";
1385
+ }
1386
+ function isListItem(token) {
1387
+ return token.type === "list_item_open";
1388
+ }
1389
+ function startsWithTodoMarkdown(token) {
1390
+ return checkboxRegex.test(token.content);
1580
1391
  }
1581
1392
 
1582
- // node/syntax/transform/monaco.ts
1583
- import lz3 from "lz-string";
1584
- function transformMonaco(ctx) {
1585
- const enabled = ctx.options.data.config.monaco === true || ctx.options.data.config.monaco === ctx.options.mode;
1586
- if (!enabled) {
1587
- ctx.s.replace(/\{monaco([\w:,-]*)\}/g, "");
1588
- return;
1589
- }
1590
- ctx.s.replace(
1591
- /^```(\w+) *\{monaco-diff\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^~~~ *\n([\s\S]+?)^```/gm,
1592
- (full, lang = "ts", options = "{}", code, diff) => {
1593
- lang = lang.trim();
1594
- options = options.trim() || "{}";
1595
- const encoded = lz3.compressToBase64(code);
1596
- const encodedDiff = lz3.compressToBase64(diff);
1597
- return `<Monaco code-lz="${encoded}" diff-lz="${encodedDiff}" lang="${lang}" v-bind="${options}" />`;
1598
- }
1599
- );
1600
- ctx.s.replace(
1601
- /^```(\w+) *\{monaco\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^```/gm,
1602
- (full, lang = "ts", options = "{}", code) => {
1603
- lang = lang.trim();
1604
- options = options.trim() || "{}";
1605
- const encoded = lz3.compressToBase64(code);
1606
- return `<Monaco code-lz="${encoded}" lang="${lang}" v-bind="${options}" />`;
1607
- }
1608
- );
1609
- ctx.s.replace(
1610
- /^```(\w+) *\{monaco-run\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^```/gm,
1611
- (full, lang = "ts", options = "{}", code) => {
1612
- lang = lang.trim();
1613
- options = options.trim() || "{}";
1614
- const encoded = lz3.compressToBase64(code);
1615
- return `<Monaco runnable code-lz="${encoded}" lang="${lang}" v-bind="${options}" />`;
1393
+ // node/syntax/markdown-it/index.ts
1394
+ import MarkdownItMdc from "markdown-it-mdc";
1395
+ import MarkdownItFootnote from "markdown-it-footnote";
1396
+
1397
+ // node/setups/load.ts
1398
+ import { resolve as resolve4 } from "node:path";
1399
+ import { deepMergeWithArray } from "@antfu/utils";
1400
+ import fs3 from "fs-extra";
1401
+ async function loadSetups(roots, filename, args, extraLoader) {
1402
+ const returns = [];
1403
+ for (const root of roots) {
1404
+ const path4 = resolve4(root, "setup", filename);
1405
+ if (fs3.existsSync(path4)) {
1406
+ const { default: setup } = await loadModule(path4);
1407
+ const ret = await setup(...args);
1408
+ if (ret)
1409
+ returns.push(ret);
1616
1410
  }
1617
- );
1411
+ if (extraLoader)
1412
+ returns.push(...await extraLoader(root));
1413
+ }
1414
+ return returns;
1618
1415
  }
1619
1416
 
1620
- // node/syntax/transform/plant-uml.ts
1621
- import { encode as encodePlantUml } from "plantuml-encoder";
1622
- function transformPlantUml(ctx) {
1623
- const server = ctx.options.data.config.plantUmlServer;
1624
- ctx.s.replace(
1625
- /^```plantuml[^\n{}]*(\{[^}\n]*\})?\n([\s\S]+?)\n```/gm,
1626
- (full, options = "", content = "") => {
1627
- const code = encodePlantUml(content.trim());
1628
- options = options.trim() || "{}";
1629
- return `<PlantUml :code="'${code}'" :server="'${server}'" v-bind="${options}" />`;
1630
- }
1417
+ // node/setups/katex.ts
1418
+ async function setupKatex(roots) {
1419
+ const options = await loadSetups(roots, "katex.ts", []);
1420
+ return Object.assign(
1421
+ { strict: false },
1422
+ ...options
1631
1423
  );
1632
1424
  }
1633
1425
 
1634
- // node/syntax/transform/slot-sugar.ts
1635
- function transformSlotSugar(ctx) {
1636
- const linesWithNewline = ctx.s.original.split(/(\r?\n)/g);
1637
- const codeBlocks = getCodeBlocks(ctx.s.original);
1638
- const lines = [];
1639
- for (let i = 0; i < linesWithNewline.length; i += 2) {
1640
- const line = linesWithNewline[i];
1641
- const newline = linesWithNewline[i + 1] || "";
1642
- lines.push(line + newline);
1643
- }
1644
- let prevSlot = false;
1645
- let offset = 0;
1646
- lines.forEach((line) => {
1647
- const start = offset;
1648
- offset += line.length;
1649
- if (codeBlocks.isInsideCodeblocks(offset))
1650
- return;
1651
- const match = line.match(/^::\s*([\w.\-:]+)\s*::(\s*)$/);
1652
- if (match) {
1653
- ctx.s.overwrite(start, offset - match[2].length, `${prevSlot ? "\n\n</template>\n" : "\n"}<template v-slot:${match[1]}="slotProps">
1654
- `);
1655
- prevSlot = true;
1656
- }
1657
- });
1658
- if (prevSlot)
1659
- ctx.s.append("\n\n</template>");
1426
+ // node/syntax/markdown-it/markdown-it-escape-code.ts
1427
+ function MarkdownItEscapeInlineCode(md) {
1428
+ const codeInline = md.renderer.rules.code_inline;
1429
+ md.renderer.rules.code_inline = (tokens, idx, options, env, self) => {
1430
+ const result = codeInline(tokens, idx, options, env, self);
1431
+ return result.replace(/^<code/, "<code v-pre");
1432
+ };
1660
1433
  }
1661
1434
 
1662
- // node/syntax/transform/snippet.ts
1663
- import path3 from "node:path";
1664
- import lz4 from "lz-string";
1665
- import fs6 from "fs-extra";
1666
- import { slash as slash3 } from "@antfu/utils";
1667
-
1668
- // node/vite/monacoWrite.ts
1669
- import fs5 from "node:fs/promises";
1670
- import path2 from "node:path";
1671
- var monacoWriterWhitelist = /* @__PURE__ */ new Set();
1672
- function createMonacoWriterPlugin({ userRoot }) {
1673
- return {
1674
- name: "slidev:monaco-write",
1675
- apply: "serve",
1676
- configureServer(server) {
1677
- server.ws.on("connection", (socket) => {
1678
- socket.on("message", async (data) => {
1679
- let json;
1680
- try {
1681
- json = JSON.parse(data.toString());
1682
- } catch {
1683
- return;
1684
- }
1685
- if (json.type === "custom" && json.event === "slidev:monaco-write") {
1686
- const { file, content } = json.data;
1687
- if (!monacoWriterWhitelist.has(file)) {
1688
- console.error(`[Slidev] Unauthorized file write: ${file}`);
1689
- return;
1690
- }
1691
- const filepath = path2.join(userRoot, file);
1692
- console.log("[Slidev] Writing file:", filepath);
1693
- await fs5.writeFile(filepath, content, "utf-8");
1694
- }
1695
- });
1696
- });
1697
- }
1435
+ // node/syntax/markdown-it/markdown-it-katex.ts
1436
+ import katex from "katex";
1437
+ function isValidDelim(state, pos) {
1438
+ const max = state.posMax;
1439
+ let can_open = true;
1440
+ let can_close = true;
1441
+ const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
1442
+ const nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1;
1443
+ if (prevChar === 32 || prevChar === 9 || /* \t */
1444
+ nextChar >= 48 && nextChar <= 57)
1445
+ can_close = false;
1446
+ if (nextChar === 32 || nextChar === 9)
1447
+ can_open = false;
1448
+ return {
1449
+ can_open,
1450
+ can_close
1698
1451
  };
1699
1452
  }
1700
-
1701
- // node/syntax/transform/snippet.ts
1702
- function dedent(text) {
1703
- const lines = text.split("\n");
1704
- const minIndentLength = lines.reduce((acc, line) => {
1705
- for (let i = 0; i < line.length; i++) {
1706
- if (line[i] !== " " && line[i] !== " ")
1707
- return Math.min(i, acc);
1708
- }
1709
- return acc;
1710
- }, Number.POSITIVE_INFINITY);
1711
- if (minIndentLength < Number.POSITIVE_INFINITY)
1712
- return lines.map((x) => x.slice(minIndentLength)).join("\n");
1713
- return text;
1714
- }
1715
- function testLine(line, regexp, regionName, end = false) {
1716
- const [full, tag, name] = regexp.exec(line.trim()) || [];
1717
- return full && tag && name === regionName && tag.match(end ? /^[Ee]nd ?[rR]egion$/ : /^[rR]egion$/);
1453
+ function math_inline(state, silent) {
1454
+ let match, token, res, pos;
1455
+ if (state.src[state.pos] !== "$")
1456
+ return false;
1457
+ res = isValidDelim(state, state.pos);
1458
+ if (!res.can_open) {
1459
+ if (!silent)
1460
+ state.pending += "$";
1461
+ state.pos += 1;
1462
+ return true;
1463
+ }
1464
+ const start = state.pos + 1;
1465
+ match = start;
1466
+ while ((match = state.src.indexOf("$", match)) !== -1) {
1467
+ pos = match - 1;
1468
+ while (state.src[pos] === "\\") pos -= 1;
1469
+ if ((match - pos) % 2 === 1)
1470
+ break;
1471
+ match += 1;
1472
+ }
1473
+ if (match === -1) {
1474
+ if (!silent)
1475
+ state.pending += "$";
1476
+ state.pos = start;
1477
+ return true;
1478
+ }
1479
+ if (match - start === 0) {
1480
+ if (!silent)
1481
+ state.pending += "$$";
1482
+ state.pos = start + 1;
1483
+ return true;
1484
+ }
1485
+ res = isValidDelim(state, match);
1486
+ if (!res.can_close) {
1487
+ if (!silent)
1488
+ state.pending += "$";
1489
+ state.pos = start;
1490
+ return true;
1491
+ }
1492
+ if (!silent) {
1493
+ token = state.push("math_inline", "math", 0);
1494
+ token.markup = "$";
1495
+ token.content = state.src.slice(start, match);
1496
+ }
1497
+ state.pos = match + 1;
1498
+ return true;
1718
1499
  }
1719
- function findRegion(lines, regionName) {
1720
- const regionRegexps = [
1721
- /^\/\/ ?#?((?:end)?region) ([\w*-]+)$/,
1722
- // javascript, typescript, java
1723
- /^\/\* ?#((?:end)?region) ([\w*-]+) ?\*\/$/,
1724
- // css, less, scss
1725
- /^#pragma ((?:end)?region) ([\w*-]+)$/,
1726
- // C, C++
1727
- /^<!-- #?((?:end)?region) ([\w*-]+) -->$/,
1728
- // HTML, markdown
1729
- /^#(End Region) ([\w*-]+)$/,
1730
- // Visual Basic
1731
- /^::#(endregion) ([\w*-]+)$/,
1732
- // Bat
1733
- /^# ?((?:end)?region) ([\w*-]+)$/
1734
- // C#, PHP, Powershell, Python, perl & misc
1735
- ];
1736
- let regexp = null;
1737
- let start = -1;
1738
- for (const [lineId, line] of lines.entries()) {
1739
- if (regexp === null) {
1740
- for (const reg of regionRegexps) {
1741
- if (testLine(line, reg, regionName)) {
1742
- start = lineId + 1;
1743
- regexp = reg;
1744
- break;
1745
- }
1746
- }
1747
- } else if (testLine(line, regexp, regionName, true)) {
1748
- return { start, end: lineId, regexp };
1500
+ function math_block(state, start, end, silent) {
1501
+ let firstLine;
1502
+ let lastLine;
1503
+ let next;
1504
+ let lastPos;
1505
+ let found = false;
1506
+ let pos = state.bMarks[start] + state.tShift[start];
1507
+ let max = state.eMarks[start];
1508
+ if (pos + 2 > max)
1509
+ return false;
1510
+ if (state.src.slice(pos, pos + 2) !== "$$")
1511
+ return false;
1512
+ pos += 2;
1513
+ firstLine = state.src.slice(pos, max);
1514
+ if (silent)
1515
+ return true;
1516
+ if (firstLine.trim().slice(-2) === "$$") {
1517
+ firstLine = firstLine.trim().slice(0, -2);
1518
+ found = true;
1519
+ }
1520
+ for (next = start; !found; ) {
1521
+ next++;
1522
+ if (next >= end)
1523
+ break;
1524
+ pos = state.bMarks[next] + state.tShift[next];
1525
+ max = state.eMarks[next];
1526
+ if (pos < max && state.tShift[next] < state.blkIndent) {
1527
+ break;
1528
+ }
1529
+ if (state.src.slice(pos, max).trim().slice(-2) === "$$") {
1530
+ lastPos = state.src.slice(0, max).lastIndexOf("$$");
1531
+ lastLine = state.src.slice(pos, lastPos);
1532
+ found = true;
1749
1533
  }
1750
1534
  }
1751
- return null;
1535
+ state.line = next + 1;
1536
+ const token = state.push("math_block", "math", 0);
1537
+ token.block = true;
1538
+ token.content = (firstLine && firstLine.trim() ? `${firstLine}
1539
+ ` : "") + state.getLines(start + 1, next, state.tShift[start], true) + (lastLine && lastLine.trim() ? lastLine : "");
1540
+ token.map = [start, state.line];
1541
+ token.markup = "$$";
1542
+ return true;
1752
1543
  }
1753
- function transformSnippet({ s, slide, options }) {
1754
- const watchFiles = options.data.watchFiles;
1755
- const dir = path3.dirname(slide.source?.filepath ?? options.entry ?? options.userRoot);
1756
- s.replace(
1757
- // eslint-disable-next-line regexp/no-super-linear-backtracking
1758
- /^<<<\s*(\S.*?)(#[\w-]+)?\s*(?:\s(\S+?))?\s*(\{.*)?$/gm,
1759
- (full, filepath = "", regionName = "", lang = "", meta = "") => {
1760
- const src = slash3(
1761
- /^@\//.test(filepath) ? path3.resolve(options.userRoot, filepath.slice(2)) : path3.resolve(dir, filepath)
1762
- );
1763
- watchFiles[src] ??= /* @__PURE__ */ new Set();
1764
- watchFiles[src].add(slide.index);
1765
- const isAFile = fs6.statSync(src).isFile();
1766
- if (!fs6.existsSync(src) || !isAFile) {
1767
- throw new Error(isAFile ? `Code snippet path not found: ${src}` : `Invalid code snippet option`);
1768
- }
1769
- let content = fs6.readFileSync(src, "utf8");
1770
- if (regionName) {
1771
- const lines = content.split(/\r?\n/);
1772
- const region = findRegion(lines, regionName.slice(1));
1773
- if (region) {
1774
- content = dedent(
1775
- lines.slice(region.start, region.end).filter((line) => !region.regexp.test(line.trim())).join("\n")
1776
- );
1777
- }
1778
- }
1779
- meta = meta.trim();
1780
- lang = lang.trim();
1781
- lang = lang || path3.extname(filepath).slice(1);
1782
- if (meta.match(/^\{monaco-write\}/)) {
1783
- monacoWriterWhitelist.add(filepath);
1784
- lang = lang.trim();
1785
- meta = meta.replace(/^\{monaco-write\}/, "").trim() || "{}";
1786
- const encoded = lz4.compressToBase64(content);
1787
- return `<Monaco writable=${JSON.stringify(filepath)} code-lz="${encoded}" lang="${lang}" v-bind="${meta}" />`;
1788
- }
1789
- return `\`\`\`${lang} ${meta}
1790
- ${content}
1791
- \`\`\``;
1544
+ function MarkdownItKatex(md, options) {
1545
+ const katexInline = function(latex) {
1546
+ options.displayMode = false;
1547
+ try {
1548
+ return katex.renderToString(latex, options);
1549
+ } catch (error) {
1550
+ if (options.throwOnError)
1551
+ console.warn(error);
1552
+ return latex;
1792
1553
  }
1793
- );
1794
- }
1795
-
1796
- // node/syntax/transform/index.ts
1797
- async function getMarkdownTransformers(options) {
1798
- const extras = await setupTransformers(options.roots);
1799
- return [
1800
- ...extras.pre,
1801
- transformSnippet,
1802
- options.data.config.highlighter === "shiki" && transformMagicMove,
1803
- ...extras.preCodeblock,
1804
- transformMermaid,
1805
- transformPlantUml,
1806
- options.data.features.monaco && transformMonaco,
1807
- ...extras.postCodeblock,
1808
- transformCodeWrapper,
1809
- options.data.features.katex && transformKaTexWrapper,
1810
- transformPageCSS,
1811
- transformSlotSugar,
1812
- ...extras.post
1813
- ];
1814
- }
1815
-
1816
- // ../../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
1817
- var SpecialCharacters;
1818
- (function(SpecialCharacters2) {
1819
- SpecialCharacters2[SpecialCharacters2["EXCLAMATION_MARK"] = 33] = "EXCLAMATION_MARK";
1820
- SpecialCharacters2[SpecialCharacters2["OPENING_BRACKET"] = 91] = "OPENING_BRACKET";
1821
- SpecialCharacters2[SpecialCharacters2["OPENING_PARENTHESIS"] = 40] = "OPENING_PARENTHESIS";
1822
- SpecialCharacters2[SpecialCharacters2["WHITESPACE"] = 32] = "WHITESPACE";
1823
- SpecialCharacters2[SpecialCharacters2["NEW_LINE"] = 10] = "NEW_LINE";
1824
- SpecialCharacters2[SpecialCharacters2["EQUALS"] = 61] = "EQUALS";
1825
- SpecialCharacters2[SpecialCharacters2["LOWER_CASE_X"] = 120] = "LOWER_CASE_X";
1826
- SpecialCharacters2[SpecialCharacters2["NUMBER_ZERO"] = 48] = "NUMBER_ZERO";
1827
- SpecialCharacters2[SpecialCharacters2["NUMBER_NINE"] = 57] = "NUMBER_NINE";
1828
- SpecialCharacters2[SpecialCharacters2["PERCENTAGE"] = 37] = "PERCENTAGE";
1829
- SpecialCharacters2[SpecialCharacters2["CLOSING_PARENTHESIS"] = 41] = "CLOSING_PARENTHESIS";
1830
- })(SpecialCharacters || (SpecialCharacters = {}));
1831
-
1832
- // ../../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
1833
- import Token from "markdown-it/lib/token.mjs";
1834
- var checkboxRegex = /^ *\[([\sx])] /i;
1835
- function taskLists(md, options = { enabled: false, label: false, lineNumber: false }) {
1836
- md.core.ruler.after("inline", "task-lists", (state) => processToken(state, options));
1837
- md.renderer.rules.taskListItemCheckbox = (tokens) => {
1838
- const token = tokens[0];
1839
- const checkedAttribute = token.attrGet("checked") ? 'checked="" ' : "";
1840
- const disabledAttribute = token.attrGet("disabled") ? 'disabled="" ' : "";
1841
- const line = token.attrGet("line");
1842
- const idAttribute = `id="${token.attrGet("id")}" `;
1843
- const dataLineAttribute = line && options.lineNumber ? `data-line="${line}" ` : "";
1844
- return `<input class="task-list-item-checkbox" type="checkbox" ${checkedAttribute}${disabledAttribute}${dataLineAttribute}${idAttribute}/>`;
1845
1554
  };
1846
- md.renderer.rules.taskListItemLabel_close = () => {
1847
- return "</label>";
1555
+ const inlineRenderer = function(tokens, idx) {
1556
+ return katexInline(tokens[idx].content);
1848
1557
  };
1849
- md.renderer.rules.taskListItemLabel_open = (tokens) => {
1850
- const token = tokens[0];
1851
- const id = token.attrGet("id");
1852
- return `<label for="${id}">`;
1558
+ const katexBlock = function(latex) {
1559
+ options.displayMode = true;
1560
+ try {
1561
+ return `<p>${katex.renderToString(latex, options)}</p>`;
1562
+ } catch (error) {
1563
+ if (options.throwOnError)
1564
+ console.warn(error);
1565
+ return latex;
1566
+ }
1567
+ };
1568
+ const blockRenderer = function(tokens, idx) {
1569
+ return `${katexBlock(tokens[idx].content)}
1570
+ `;
1853
1571
  };
1572
+ md.inline.ruler.after("escape", "math_inline", math_inline);
1573
+ md.block.ruler.after("blockquote", "math_block", math_block, {
1574
+ alt: ["paragraph", "reference", "blockquote", "list"]
1575
+ });
1576
+ md.renderer.rules.math_inline = inlineRenderer;
1577
+ md.renderer.rules.math_block = blockRenderer;
1854
1578
  }
1855
- function processToken(state, options) {
1856
- const allTokens = state.tokens;
1857
- for (let i = 2; i < allTokens.length; i++) {
1858
- if (!isTodoItem(allTokens, i)) {
1859
- continue;
1860
- }
1861
- todoify(allTokens[i], options);
1862
- allTokens[i - 2].attrJoin("class", `task-list-item ${options.enabled ? " enabled" : ""}`);
1863
- const parentToken = findParentToken(allTokens, i - 2);
1864
- if (parentToken) {
1865
- const classes = parentToken.attrGet("class") ?? "";
1866
- if (!classes.match(/(^| )contains-task-list/)) {
1867
- parentToken.attrJoin("class", "contains-task-list");
1579
+
1580
+ // node/syntax/markdown-it/markdown-it-shiki.ts
1581
+ import { isTruthy } from "@antfu/utils";
1582
+ import { fromHighlighter } from "@shikijs/markdown-it/core";
1583
+ async function MarkdownItShiki({ data: { config }, mode, utils }) {
1584
+ const transformers = [
1585
+ ...utils.shikiOptions.transformers || [],
1586
+ (config.twoslash === true || config.twoslash === mode) && (await import("@shikijs/vitepress-twoslash")).transformerTwoslash({
1587
+ explicitTrigger: true,
1588
+ twoslashOptions: {
1589
+ handbookOptions: {
1590
+ noErrorValidation: true
1591
+ }
1592
+ }
1593
+ }),
1594
+ {
1595
+ pre(pre) {
1596
+ this.addClassToHast(pre, "slidev-code");
1597
+ delete pre.properties.tabindex;
1598
+ },
1599
+ postprocess(code) {
1600
+ return escapeVueInCode(code);
1868
1601
  }
1869
1602
  }
1870
- }
1871
- return false;
1872
- }
1873
- function findParentToken(tokens, index) {
1874
- const targetLevel = tokens[index].level - 1;
1875
- for (let currentTokenIndex = index - 1; currentTokenIndex >= 0; currentTokenIndex--) {
1876
- if (tokens[currentTokenIndex].level === targetLevel) {
1877
- return tokens[currentTokenIndex];
1878
- }
1879
- }
1880
- return void 0;
1881
- }
1882
- function isTodoItem(tokens, index) {
1883
- return isInline(tokens[index]) && isParagraph(tokens[index - 1]) && isListItem(tokens[index - 2]) && startsWithTodoMarkdown(tokens[index]);
1603
+ ].filter(isTruthy);
1604
+ return fromHighlighter(utils.shiki, {
1605
+ ...utils.shikiOptions,
1606
+ transformers
1607
+ });
1884
1608
  }
1885
- function todoify(token, options) {
1886
- if (token.children == null) {
1887
- return;
1888
- }
1889
- const id = generateIdForToken(token);
1890
- token.children.splice(0, 0, createCheckboxToken(token, options.enabled, id));
1891
- token.children[1].content = token.children[1].content.replace(checkboxRegex, "");
1892
- if (options.label) {
1893
- token.children.splice(1, 0, createLabelBeginToken(id));
1894
- token.children.push(createLabelEndToken());
1609
+
1610
+ // node/syntax/markdown-it/markdown-it-v-drag.ts
1611
+ import { SourceMapConsumer } from "source-map-js";
1612
+ var dragComponentRegex = /<(v-?drag-?\w*)([\s>])/i;
1613
+ var dragDirectiveRegex = /(?<![</\w])v-drag(=".*?")?/i;
1614
+ function MarkdownItVDrag(md, markdownTransformMap) {
1615
+ const visited = /* @__PURE__ */ new WeakSet();
1616
+ const sourceMapConsumers = /* @__PURE__ */ new WeakMap();
1617
+ function getSourceMapConsumer(id) {
1618
+ const s = markdownTransformMap.get(id);
1619
+ if (!s)
1620
+ return void 0;
1621
+ let smc = sourceMapConsumers.get(s);
1622
+ if (smc)
1623
+ return smc;
1624
+ const sourceMap = s.generateMap();
1625
+ smc = new SourceMapConsumer({
1626
+ ...sourceMap,
1627
+ version: sourceMap.version.toString()
1628
+ });
1629
+ sourceMapConsumers.set(s, smc);
1630
+ return smc;
1895
1631
  }
1632
+ const _parse = md.parse;
1633
+ md.parse = function(src, env) {
1634
+ const smc = getSourceMapConsumer(env.id);
1635
+ const toOriginalPos = smc ? (line) => smc.originalPositionFor({ line: line + 1, column: 0 }).line - 1 : (line) => line;
1636
+ function toMarkdownSource(map, idx) {
1637
+ const start = toOriginalPos(map[0]);
1638
+ const end = toOriginalPos(map[1]);
1639
+ return `[${start},${Math.max(start + 1, end)},${idx}]`;
1640
+ }
1641
+ function replaceChildren(token, regex, replacement) {
1642
+ for (const child of token.children ?? []) {
1643
+ if (child.type === "html_block" || child.type === "html_inline") {
1644
+ child.content = child.content.replace(regex, replacement);
1645
+ }
1646
+ replaceChildren(child, regex, replacement);
1647
+ }
1648
+ }
1649
+ return _parse.call(this, src, env).map((token) => {
1650
+ if (!["html_block", "html_inline", "inline"].includes(token.type) || !token.content.includes("drag") || visited.has(token))
1651
+ return token;
1652
+ token.content = token.content.replace(dragComponentRegex, (_, tag, space, idx) => {
1653
+ const replacement = `<${tag} :markdownSource="${toMarkdownSource(token.map, idx)}"${space}`;
1654
+ replaceChildren(token, dragComponentRegex, replacement);
1655
+ return replacement;
1656
+ }).replace(dragDirectiveRegex, (_, value, idx) => {
1657
+ const replacement = `v-drag${value ?? ""} :markdownSource="${toMarkdownSource(token.map, idx)}"`;
1658
+ replaceChildren(token, dragDirectiveRegex, replacement);
1659
+ return replacement;
1660
+ });
1661
+ visited.add(token);
1662
+ return token;
1663
+ });
1664
+ };
1896
1665
  }
1897
- function generateIdForToken(token) {
1898
- if (token.map) {
1899
- return `task-item-${token.map[0]}`;
1666
+
1667
+ // node/syntax/markdown-it/index.ts
1668
+ async function useMarkdownItPlugins(md, options, markdownTransformMap) {
1669
+ const { roots, data: { features, config } } = options;
1670
+ if (config.highlighter === "shiki") {
1671
+ md.use(await MarkdownItShiki(options));
1900
1672
  } else {
1901
- return `task-item-${Math.ceil(Math.random() * (1e4 * 1e3) - 1e3)}`;
1673
+ console.warn("[Slidev] Highlighter: Prism highlighter is deprecated, and will be removed in v0.50. Refer to https://github.com/slidevjs/slidev/issues/1390");
1674
+ const { default: MarkdownItPrism } = await import("./markdown-it-prism-44L27JJK.js");
1675
+ md.use(MarkdownItPrism);
1902
1676
  }
1677
+ md.use(MarkdownItLink);
1678
+ md.use(MarkdownItEscapeInlineCode);
1679
+ md.use(MarkdownItFootnote);
1680
+ md.use(taskLists, { enabled: true, lineNumber: true, label: true });
1681
+ if (features.katex)
1682
+ md.use(MarkdownItKatex, await setupKatex(roots));
1683
+ md.use(MarkdownItVDrag, markdownTransformMap);
1684
+ if (config.mdc)
1685
+ md.use(MarkdownItMdc);
1903
1686
  }
1904
- function createCheckboxToken(token, enabled, id) {
1905
- const checkbox = new Token("taskListItemCheckbox", "", 0);
1906
- if (!enabled) {
1907
- checkbox.attrSet("disabled", "true");
1908
- }
1909
- if (token.map) {
1910
- checkbox.attrSet("line", token.map[0].toString());
1911
- }
1912
- checkbox.attrSet("id", id);
1913
- const checkboxRegexResult = checkboxRegex.exec(token.content);
1914
- const isChecked = checkboxRegexResult?.[1].toLowerCase() === "x";
1915
- if (isChecked) {
1916
- checkbox.attrSet("checked", "true");
1687
+
1688
+ // node/setups/transformers.ts
1689
+ async function setupTransformers(roots) {
1690
+ const returns = await loadSetups(roots, "transformers.ts", []);
1691
+ const result = {
1692
+ pre: [],
1693
+ preCodeblock: [],
1694
+ postCodeblock: [],
1695
+ post: []
1696
+ };
1697
+ for (const r of [...returns].reverse()) {
1698
+ if (r.pre)
1699
+ result.pre.push(...r.pre);
1700
+ if (r.preCodeblock)
1701
+ result.preCodeblock.push(...r.preCodeblock);
1917
1702
  }
1918
- return checkbox;
1919
- }
1920
- function createLabelBeginToken(id) {
1921
- const labelBeginToken = new Token("taskListItemLabel_open", "", 1);
1922
- labelBeginToken.attrSet("id", id);
1923
- return labelBeginToken;
1924
- }
1925
- function createLabelEndToken() {
1926
- return new Token("taskListItemLabel_close", "", -1);
1927
- }
1928
- function isInline(token) {
1929
- return token.type === "inline";
1930
- }
1931
- function isParagraph(token) {
1932
- return token.type === "paragraph_open";
1703
+ for (const r of returns) {
1704
+ if (r.postCodeblock)
1705
+ result.postCodeblock.push(...r.postCodeblock);
1706
+ if (r.post)
1707
+ result.post.push(...r.post);
1708
+ }
1709
+ return result;
1933
1710
  }
1934
- function isListItem(token) {
1935
- return token.type === "list_item_open";
1711
+
1712
+ // node/syntax/transform/code-wrapper.ts
1713
+ var reCodeBlock = /^```([\w'-]+)?\s*(?:\{([\w*,|-]+)\}\s*?(\{[^}]*\})?([^\r\n]*))?\r?\n(\S[\s\S]*?)^```$/gm;
1714
+ function transformCodeWrapper(ctx) {
1715
+ ctx.s.replace(
1716
+ reCodeBlock,
1717
+ (full, lang = "", rangeStr = "", options = "", attrs = "", code) => {
1718
+ const ranges = normalizeRangeStr(rangeStr);
1719
+ code = code.trimEnd();
1720
+ options = options.trim() || "{}";
1721
+ return `
1722
+ <CodeBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1723
+
1724
+ \`\`\`${lang}${attrs}
1725
+ ${code}
1726
+ \`\`\`
1727
+
1728
+ </CodeBlockWrapper>`;
1729
+ }
1730
+ );
1936
1731
  }
1937
- function startsWithTodoMarkdown(token) {
1938
- return checkboxRegex.test(token.content);
1732
+
1733
+ // node/syntax/transform/in-page-css.ts
1734
+ function transformPageCSS(ctx) {
1735
+ const codeBlocks = getCodeBlocks(ctx.s.original);
1736
+ ctx.s.replace(
1737
+ /(\n<style[^>]*>)([\s\S]+?)(<\/style>)/g,
1738
+ (full, start, css, end, index) => {
1739
+ if (codeBlocks.isInsideCodeblocks(index))
1740
+ return full;
1741
+ if (!start.includes("scoped"))
1742
+ start = start.replace("<style", "<style scoped");
1743
+ return `${start}
1744
+ ${css}${end}`;
1745
+ }
1746
+ );
1939
1747
  }
1940
1748
 
1941
- // node/syntax/markdown-it/index.ts
1942
- import MarkdownItMdc from "markdown-it-mdc";
1943
- import MarkdownItFootnote from "markdown-it-footnote";
1749
+ // node/syntax/transform/katex-wrapper.ts
1750
+ function transformKaTexWrapper(ctx) {
1751
+ ctx.s.replace(
1752
+ /^\$\$(?:\s*\{([\w*,|-]+)\}\s*?(?:(\{[^}]*\})\s*?)?)?\n(\S[\s\S]*?)^\$\$/gm,
1753
+ (full, rangeStr = "", options = "", code) => {
1754
+ const ranges = !rangeStr.trim() ? [] : rangeStr.trim().split(/\|/g).map((i) => i.trim());
1755
+ code = code.trimEnd();
1756
+ options = options.trim() || "{}";
1757
+ return `<KaTexBlockWrapper v-bind="${options}" :ranges='${JSON.stringify(ranges)}'>
1944
1758
 
1945
- // node/setups/katex.ts
1946
- async function setupKatex(roots) {
1947
- const options = await loadSetups(roots, "katex.ts", []);
1948
- return Object.assign(
1949
- { strict: false },
1950
- ...options
1759
+ $$
1760
+ ${code}
1761
+ $$
1762
+ </KaTexBlockWrapper>
1763
+ `;
1764
+ }
1951
1765
  );
1952
1766
  }
1953
1767
 
1954
- // node/syntax/markdown-it/markdown-it-katex.ts
1955
- import katex from "katex";
1956
- function isValidDelim(state, pos) {
1957
- const max = state.posMax;
1958
- let can_open = true;
1959
- let can_close = true;
1960
- const prevChar = pos > 0 ? state.src.charCodeAt(pos - 1) : -1;
1961
- const nextChar = pos + 1 <= max ? state.src.charCodeAt(pos + 1) : -1;
1962
- if (prevChar === 32 || prevChar === 9 || /* \t */
1963
- nextChar >= 48 && nextChar <= 57)
1964
- can_close = false;
1965
- if (nextChar === 32 || nextChar === 9)
1966
- can_open = false;
1967
- return {
1968
- can_open,
1969
- can_close
1970
- };
1768
+ // node/syntax/transform/magic-move.ts
1769
+ import lz from "lz-string";
1770
+ import { codeToKeyedTokens } from "shiki-magic-move/core";
1771
+ var reMagicMoveBlock = /^````(?:md|markdown) magic-move *(\{[^}]*\})?([^ \n]*)\n([\s\S]+?)^````$/gm;
1772
+ function parseLineNumbersOption(options) {
1773
+ return /lines: *true/.test(options) ? true : /lines: *false/.test(options) ? false : void 0;
1971
1774
  }
1972
- function math_inline(state, silent) {
1973
- let match, token, res, pos;
1974
- if (state.src[state.pos] !== "$")
1975
- return false;
1976
- res = isValidDelim(state, state.pos);
1977
- if (!res.can_open) {
1978
- if (!silent)
1979
- state.pending += "$";
1980
- state.pos += 1;
1981
- return true;
1982
- }
1983
- const start = state.pos + 1;
1984
- match = start;
1985
- while ((match = state.src.indexOf("$", match)) !== -1) {
1986
- pos = match - 1;
1987
- while (state.src[pos] === "\\") pos -= 1;
1988
- if ((match - pos) % 2 === 1)
1989
- break;
1990
- match += 1;
1991
- }
1992
- if (match === -1) {
1993
- if (!silent)
1994
- state.pending += "$";
1995
- state.pos = start;
1996
- return true;
1997
- }
1998
- if (match - start === 0) {
1999
- if (!silent)
2000
- state.pending += "$$";
2001
- state.pos = start + 1;
2002
- return true;
2003
- }
2004
- res = isValidDelim(state, match);
2005
- if (!res.can_close) {
2006
- if (!silent)
2007
- state.pending += "$";
2008
- state.pos = start;
2009
- return true;
2010
- }
2011
- if (!silent) {
2012
- token = state.push("math_inline", "math", 0);
2013
- token.markup = "$";
2014
- token.content = state.src.slice(start, match);
2015
- }
2016
- state.pos = match + 1;
2017
- return true;
1775
+ function transformMagicMove(ctx) {
1776
+ ctx.s.replace(
1777
+ reMagicMoveBlock,
1778
+ (full, options = "{}", _attrs = "", body) => {
1779
+ const matches = Array.from(body.matchAll(reCodeBlock));
1780
+ if (!matches.length)
1781
+ throw new Error("Magic Move block must contain at least one code block");
1782
+ const defaultLineNumbers = parseLineNumbersOption(options) ?? ctx.options.data.config.lineNumbers;
1783
+ const ranges = matches.map((i) => normalizeRangeStr(i[2]));
1784
+ const steps = matches.map((i) => {
1785
+ const lineNumbers = parseLineNumbersOption(i[3]) ?? defaultLineNumbers;
1786
+ return codeToKeyedTokens(ctx.options.utils.shiki, i[5].trimEnd(), {
1787
+ ...ctx.options.utils.shikiOptions,
1788
+ lang: i[1]
1789
+ }, lineNumbers);
1790
+ });
1791
+ const compressed = lz.compressToBase64(JSON.stringify(steps));
1792
+ return `<ShikiMagicMove v-bind="${options}" steps-lz="${compressed}" :step-ranges='${JSON.stringify(ranges)}' />`;
1793
+ }
1794
+ );
2018
1795
  }
2019
- function math_block(state, start, end, silent) {
2020
- let firstLine;
2021
- let lastLine;
2022
- let next;
2023
- let lastPos;
2024
- let found = false;
2025
- let pos = state.bMarks[start] + state.tShift[start];
2026
- let max = state.eMarks[start];
2027
- if (pos + 2 > max)
2028
- return false;
2029
- if (state.src.slice(pos, pos + 2) !== "$$")
2030
- return false;
2031
- pos += 2;
2032
- firstLine = state.src.slice(pos, max);
2033
- if (silent)
2034
- return true;
2035
- if (firstLine.trim().slice(-2) === "$$") {
2036
- firstLine = firstLine.trim().slice(0, -2);
2037
- found = true;
1796
+
1797
+ // node/syntax/transform/mermaid.ts
1798
+ import lz2 from "lz-string";
1799
+ function transformMermaid(ctx) {
1800
+ ctx.s.replace(
1801
+ /^```mermaid *(\{[^\n]*\})?\n([\s\S]+?)\n```/gm,
1802
+ (full, options = "", code = "") => {
1803
+ code = code.trim();
1804
+ options = options.trim() || "{}";
1805
+ const encoded = lz2.compressToBase64(code);
1806
+ return `<Mermaid code-lz="${encoded}" v-bind="${options}" />`;
1807
+ }
1808
+ );
1809
+ }
1810
+
1811
+ // node/syntax/transform/monaco.ts
1812
+ import lz3 from "lz-string";
1813
+ function transformMonaco(ctx) {
1814
+ const enabled = ctx.options.data.config.monaco === true || ctx.options.data.config.monaco === ctx.options.mode;
1815
+ if (!enabled) {
1816
+ ctx.s.replace(/\{monaco([\w:,-]*)\}/g, "");
1817
+ return;
2038
1818
  }
2039
- for (next = start; !found; ) {
2040
- next++;
2041
- if (next >= end)
2042
- break;
2043
- pos = state.bMarks[next] + state.tShift[next];
2044
- max = state.eMarks[next];
2045
- if (pos < max && state.tShift[next] < state.blkIndent) {
2046
- break;
1819
+ ctx.s.replace(
1820
+ /^```(\w+) *\{monaco-diff\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^~~~ *\n([\s\S]+?)^```/gm,
1821
+ (full, lang = "ts", options = "{}", code, diff) => {
1822
+ lang = lang.trim();
1823
+ options = options.trim() || "{}";
1824
+ const encoded = lz3.compressToBase64(code);
1825
+ const encodedDiff = lz3.compressToBase64(diff);
1826
+ return `<Monaco code-lz="${encoded}" diff-lz="${encodedDiff}" lang="${lang}" v-bind="${options}" />`;
2047
1827
  }
2048
- if (state.src.slice(pos, max).trim().slice(-2) === "$$") {
2049
- lastPos = state.src.slice(0, max).lastIndexOf("$$");
2050
- lastLine = state.src.slice(pos, lastPos);
2051
- found = true;
1828
+ );
1829
+ ctx.s.replace(
1830
+ /^```(\w+) *\{monaco\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^```/gm,
1831
+ (full, lang = "ts", options = "{}", code) => {
1832
+ lang = lang.trim();
1833
+ options = options.trim() || "{}";
1834
+ const encoded = lz3.compressToBase64(code);
1835
+ return `<Monaco code-lz="${encoded}" lang="${lang}" v-bind="${options}" />`;
2052
1836
  }
2053
- }
2054
- state.line = next + 1;
2055
- const token = state.push("math_block", "math", 0);
2056
- token.block = true;
2057
- token.content = (firstLine && firstLine.trim() ? `${firstLine}
2058
- ` : "") + state.getLines(start + 1, next, state.tShift[start], true) + (lastLine && lastLine.trim() ? lastLine : "");
2059
- token.map = [start, state.line];
2060
- token.markup = "$$";
2061
- return true;
1837
+ );
1838
+ ctx.s.replace(
1839
+ /^```(\w+) *\{monaco-run\} *(?:(\{[^\n]*\}) *)?\n([\s\S]+?)^```/gm,
1840
+ (full, lang = "ts", options = "{}", code) => {
1841
+ lang = lang.trim();
1842
+ options = options.trim() || "{}";
1843
+ const encoded = lz3.compressToBase64(code);
1844
+ return `<Monaco runnable code-lz="${encoded}" lang="${lang}" v-bind="${options}" />`;
1845
+ }
1846
+ );
1847
+ }
1848
+
1849
+ // node/syntax/transform/plant-uml.ts
1850
+ import { encode as encodePlantUml } from "plantuml-encoder";
1851
+ function transformPlantUml(ctx) {
1852
+ const server = ctx.options.data.config.plantUmlServer;
1853
+ ctx.s.replace(
1854
+ /^```plantuml[^\n{}]*(\{[^}\n]*\})?\n([\s\S]+?)\n```/gm,
1855
+ (full, options = "", content = "") => {
1856
+ const code = encodePlantUml(content.trim());
1857
+ options = options.trim() || "{}";
1858
+ return `<PlantUml :code="'${code}'" :server="'${server}'" v-bind="${options}" />`;
1859
+ }
1860
+ );
2062
1861
  }
2063
- function MarkdownItKatex(md, options) {
2064
- const katexInline = function(latex) {
2065
- options.displayMode = false;
2066
- try {
2067
- return katex.renderToString(latex, options);
2068
- } catch (error) {
2069
- if (options.throwOnError)
2070
- console.warn(error);
2071
- return latex;
1862
+
1863
+ // node/syntax/transform/slot-sugar.ts
1864
+ function transformSlotSugar(ctx) {
1865
+ const linesWithNewline = ctx.s.original.split(/(\r?\n)/g);
1866
+ const codeBlocks = getCodeBlocks(ctx.s.original);
1867
+ const lines = [];
1868
+ for (let i = 0; i < linesWithNewline.length; i += 2) {
1869
+ const line = linesWithNewline[i];
1870
+ const newline = linesWithNewline[i + 1] || "";
1871
+ lines.push(line + newline);
1872
+ }
1873
+ let prevSlot = false;
1874
+ let offset = 0;
1875
+ lines.forEach((line) => {
1876
+ const start = offset;
1877
+ offset += line.length;
1878
+ if (codeBlocks.isInsideCodeblocks(offset))
1879
+ return;
1880
+ const match = line.match(/^::\s*([\w.\-:]+)\s*::(\s*)$/);
1881
+ if (match) {
1882
+ ctx.s.overwrite(start, offset - match[2].length, `${prevSlot ? "\n\n</template>\n" : "\n"}<template v-slot:${match[1]}="slotProps">
1883
+ `);
1884
+ prevSlot = true;
2072
1885
  }
2073
- };
2074
- const inlineRenderer = function(tokens, idx) {
2075
- return katexInline(tokens[idx].content);
2076
- };
2077
- const katexBlock = function(latex) {
2078
- options.displayMode = true;
2079
- try {
2080
- return `<p>${katex.renderToString(latex, options)}</p>`;
2081
- } catch (error) {
2082
- if (options.throwOnError)
2083
- console.warn(error);
2084
- return latex;
1886
+ });
1887
+ if (prevSlot)
1888
+ ctx.s.append("\n\n</template>");
1889
+ }
1890
+
1891
+ // node/syntax/transform/snippet.ts
1892
+ import path2 from "node:path";
1893
+ import { slash as slash2 } from "@antfu/utils";
1894
+ import fs5 from "fs-extra";
1895
+ import lz4 from "lz-string";
1896
+
1897
+ // node/vite/monacoWrite.ts
1898
+ import fs4 from "node:fs/promises";
1899
+ import path from "node:path";
1900
+ var monacoWriterWhitelist = /* @__PURE__ */ new Set();
1901
+ function createMonacoWriterPlugin({ userRoot }) {
1902
+ return {
1903
+ name: "slidev:monaco-write",
1904
+ apply: "serve",
1905
+ configureServer(server) {
1906
+ server.ws.on("connection", (socket) => {
1907
+ socket.on("message", async (data) => {
1908
+ let json;
1909
+ try {
1910
+ json = JSON.parse(data.toString());
1911
+ } catch {
1912
+ return;
1913
+ }
1914
+ if (json.type === "custom" && json.event === "slidev:monaco-write") {
1915
+ const { file, content } = json.data;
1916
+ if (!monacoWriterWhitelist.has(file)) {
1917
+ console.error(`[Slidev] Unauthorized file write: ${file}`);
1918
+ return;
1919
+ }
1920
+ const filepath = path.join(userRoot, file);
1921
+ console.log("[Slidev] Writing file:", filepath);
1922
+ await fs4.writeFile(filepath, content, "utf-8");
1923
+ }
1924
+ });
1925
+ });
2085
1926
  }
2086
1927
  };
2087
- const blockRenderer = function(tokens, idx) {
2088
- return `${katexBlock(tokens[idx].content)}
2089
- `;
2090
- };
2091
- md.inline.ruler.after("escape", "math_inline", math_inline);
2092
- md.block.ruler.after("blockquote", "math_block", math_block, {
2093
- alt: ["paragraph", "reference", "blockquote", "list"]
2094
- });
2095
- md.renderer.rules.math_inline = inlineRenderer;
2096
- md.renderer.rules.math_block = blockRenderer;
2097
1928
  }
2098
1929
 
2099
- // node/syntax/markdown-it/markdown-it-v-drag.ts
2100
- import { SourceMapConsumer } from "source-map-js";
2101
- var dragComponentRegex = /<(v-?drag-?\w*)([\s>])/i;
2102
- var dragDirectiveRegex = /(?<![</\w])v-drag(=".*?")?/i;
2103
- function MarkdownItVDrag(md, markdownTransformMap) {
2104
- const visited = /* @__PURE__ */ new WeakSet();
2105
- const sourceMapConsumers = /* @__PURE__ */ new WeakMap();
2106
- function getSourceMapConsumer(id) {
2107
- const s = markdownTransformMap.get(id);
2108
- if (!s)
2109
- return void 0;
2110
- let smc = sourceMapConsumers.get(s);
2111
- if (smc)
2112
- return smc;
2113
- const sourceMap = s.generateMap();
2114
- smc = new SourceMapConsumer({
2115
- ...sourceMap,
2116
- version: sourceMap.version.toString()
2117
- });
2118
- sourceMapConsumers.set(s, smc);
2119
- return smc;
2120
- }
2121
- const _parse = md.parse;
2122
- md.parse = function(src, env) {
2123
- const smc = getSourceMapConsumer(env.id);
2124
- const toOriginalPos = smc ? (line) => smc.originalPositionFor({ line: line + 1, column: 0 }).line - 1 : (line) => line;
2125
- function toMarkdownSource(map, idx) {
2126
- const start = toOriginalPos(map[0]);
2127
- const end = toOriginalPos(map[1]);
2128
- return `[${start},${Math.max(start + 1, end)},${idx}]`;
1930
+ // node/syntax/transform/snippet.ts
1931
+ function dedent(text) {
1932
+ const lines = text.split("\n");
1933
+ const minIndentLength = lines.reduce((acc, line) => {
1934
+ for (let i = 0; i < line.length; i++) {
1935
+ if (line[i] !== " " && line[i] !== " ")
1936
+ return Math.min(i, acc);
2129
1937
  }
2130
- function replaceChildren(token, regex, replacement) {
2131
- for (const child of token.children ?? []) {
2132
- if (child.type === "html_block" || child.type === "html_inline") {
2133
- child.content = child.content.replace(regex, replacement);
1938
+ return acc;
1939
+ }, Number.POSITIVE_INFINITY);
1940
+ if (minIndentLength < Number.POSITIVE_INFINITY)
1941
+ return lines.map((x) => x.slice(minIndentLength)).join("\n");
1942
+ return text;
1943
+ }
1944
+ function testLine(line, regexp, regionName, end = false) {
1945
+ const [full, tag, name] = regexp.exec(line.trim()) || [];
1946
+ return full && tag && name === regionName && tag.match(end ? /^[Ee]nd ?[rR]egion$/ : /^[rR]egion$/);
1947
+ }
1948
+ function findRegion(lines, regionName) {
1949
+ const regionRegexps = [
1950
+ /^\/\/ ?#?((?:end)?region) ([\w*-]+)$/,
1951
+ // javascript, typescript, java
1952
+ /^\/\* ?#((?:end)?region) ([\w*-]+) ?\*\/$/,
1953
+ // css, less, scss
1954
+ /^#pragma ((?:end)?region) ([\w*-]+)$/,
1955
+ // C, C++
1956
+ /^<!-- #?((?:end)?region) ([\w*-]+) -->$/,
1957
+ // HTML, markdown
1958
+ /^#(End Region) ([\w*-]+)$/,
1959
+ // Visual Basic
1960
+ /^::#(endregion) ([\w*-]+)$/,
1961
+ // Bat
1962
+ /^# ?((?:end)?region) ([\w*-]+)$/
1963
+ // C#, PHP, Powershell, Python, perl & misc
1964
+ ];
1965
+ let regexp = null;
1966
+ let start = -1;
1967
+ for (const [lineId, line] of lines.entries()) {
1968
+ if (regexp === null) {
1969
+ for (const reg of regionRegexps) {
1970
+ if (testLine(line, reg, regionName)) {
1971
+ start = lineId + 1;
1972
+ regexp = reg;
1973
+ break;
2134
1974
  }
2135
- replaceChildren(child, regex, replacement);
2136
1975
  }
1976
+ } else if (testLine(line, regexp, regionName, true)) {
1977
+ return { start, end: lineId, regexp };
2137
1978
  }
2138
- return _parse.call(this, src, env).map((token) => {
2139
- if (!["html_block", "html_inline", "inline"].includes(token.type) || !token.content.includes("drag") || visited.has(token))
2140
- return token;
2141
- token.content = token.content.replace(dragComponentRegex, (_, tag, space, idx) => {
2142
- const replacement = `<${tag} :markdownSource="${toMarkdownSource(token.map, idx)}"${space}`;
2143
- replaceChildren(token, dragComponentRegex, replacement);
2144
- return replacement;
2145
- }).replace(dragDirectiveRegex, (_, value, idx) => {
2146
- const replacement = `v-drag${value ?? ""} :markdownSource="${toMarkdownSource(token.map, idx)}"`;
2147
- replaceChildren(token, dragDirectiveRegex, replacement);
2148
- return replacement;
2149
- });
2150
- visited.add(token);
2151
- return token;
2152
- });
2153
- };
1979
+ }
1980
+ return null;
2154
1981
  }
2155
-
2156
- // node/syntax/markdown-it/markdown-it-shiki.ts
2157
- import { isTruthy } from "@antfu/utils";
2158
- import { fromHighlighter } from "@shikijs/markdown-it/core";
2159
- async function MarkdownItShiki({ data: { config }, mode, utils }) {
2160
- const transformers = [
2161
- ...utils.shikiOptions.transformers || [],
2162
- (config.twoslash === true || config.twoslash === mode) && (await import("@shikijs/vitepress-twoslash")).transformerTwoslash({
2163
- explicitTrigger: true,
2164
- twoslashOptions: {
2165
- handbookOptions: {
2166
- noErrorValidation: true
1982
+ function transformSnippet({ s, slide, options }) {
1983
+ const watchFiles = options.data.watchFiles;
1984
+ const dir = path2.dirname(slide.source?.filepath ?? options.entry ?? options.userRoot);
1985
+ s.replace(
1986
+ // eslint-disable-next-line regexp/no-super-linear-backtracking
1987
+ /^<<<\s*(\S.*?)(#[\w-]+)?\s*(?:\s(\S+?))?\s*(\{.*)?$/gm,
1988
+ (full, filepath = "", regionName = "", lang = "", meta = "") => {
1989
+ const src = slash2(
1990
+ /^@\//.test(filepath) ? path2.resolve(options.userRoot, filepath.slice(2)) : path2.resolve(dir, filepath)
1991
+ );
1992
+ watchFiles[src] ??= /* @__PURE__ */ new Set();
1993
+ watchFiles[src].add(slide.index);
1994
+ const isAFile = fs5.statSync(src).isFile();
1995
+ if (!fs5.existsSync(src) || !isAFile) {
1996
+ throw new Error(isAFile ? `Code snippet path not found: ${src}` : `Invalid code snippet option`);
1997
+ }
1998
+ let content = fs5.readFileSync(src, "utf8");
1999
+ if (regionName) {
2000
+ const lines = content.split(/\r?\n/);
2001
+ const region = findRegion(lines, regionName.slice(1));
2002
+ if (region) {
2003
+ content = dedent(
2004
+ lines.slice(region.start, region.end).filter((line) => !region.regexp.test(line.trim())).join("\n")
2005
+ );
2167
2006
  }
2168
2007
  }
2169
- }),
2170
- {
2171
- pre(pre) {
2172
- this.addClassToHast(pre, "slidev-code");
2173
- delete pre.properties.tabindex;
2174
- },
2175
- postprocess(code) {
2176
- return escapeVueInCode(code);
2008
+ meta = meta.trim();
2009
+ lang = lang.trim();
2010
+ lang = lang || path2.extname(filepath).slice(1);
2011
+ if (meta.match(/^\{monaco-write\}/)) {
2012
+ monacoWriterWhitelist.add(filepath);
2013
+ lang = lang.trim();
2014
+ meta = meta.replace(/^\{monaco-write\}/, "").trim() || "{}";
2015
+ const encoded = lz4.compressToBase64(content);
2016
+ return `<Monaco writable=${JSON.stringify(filepath)} code-lz="${encoded}" lang="${lang}" v-bind="${meta}" />`;
2177
2017
  }
2178
- }
2179
- ].filter(isTruthy);
2180
- return fromHighlighter(utils.shiki, {
2181
- ...utils.shikiOptions,
2182
- transformers
2183
- });
2184
- }
2185
-
2186
- // node/syntax/markdown-it/markdown-it-escape-code.ts
2187
- function MarkdownItEscapeInlineCode(md) {
2188
- const codeInline = md.renderer.rules.code_inline;
2189
- md.renderer.rules.code_inline = (tokens, idx, options, env, self) => {
2190
- const result = codeInline(tokens, idx, options, env, self);
2191
- return result.replace(/^<code/, "<code v-pre");
2192
- };
2018
+ return `\`\`\`${lang} ${meta}
2019
+ ${content}
2020
+ \`\`\``;
2021
+ }
2022
+ );
2193
2023
  }
2194
2024
 
2195
- // node/syntax/markdown-it/index.ts
2196
- async function useMarkdownItPlugins(md, options, markdownTransformMap) {
2197
- const { roots, data: { features, config } } = options;
2198
- if (config.highlighter === "shiki") {
2199
- md.use(await MarkdownItShiki(options));
2200
- } else {
2201
- console.warn("[Slidev] Highlighter: Prism highlighter is deprecated, and will be removed in v0.50. Refer to https://github.com/slidevjs/slidev/issues/1390");
2202
- const { default: MarkdownItPrism } = await import("./markdown-it-prism-P475G4NP.js");
2203
- md.use(MarkdownItPrism);
2204
- }
2205
- md.use(MarkdownItLink);
2206
- md.use(MarkdownItEscapeInlineCode);
2207
- md.use(MarkdownItFootnote);
2208
- md.use(taskLists, { enabled: true, lineNumber: true, label: true });
2209
- if (features.katex)
2210
- md.use(MarkdownItKatex, await setupKatex(roots));
2211
- md.use(MarkdownItVDrag, markdownTransformMap);
2212
- if (config.mdc)
2213
- md.use(MarkdownItMdc);
2025
+ // node/syntax/transform/index.ts
2026
+ async function getMarkdownTransformers(options) {
2027
+ const extras = await setupTransformers(options.roots);
2028
+ return [
2029
+ ...extras.pre,
2030
+ transformSnippet,
2031
+ options.data.config.highlighter === "shiki" && transformMagicMove,
2032
+ ...extras.preCodeblock,
2033
+ transformMermaid,
2034
+ transformPlantUml,
2035
+ options.data.features.monaco && transformMonaco,
2036
+ ...extras.postCodeblock,
2037
+ transformCodeWrapper,
2038
+ options.data.features.katex && transformKaTexWrapper,
2039
+ transformPageCSS,
2040
+ transformSlotSugar,
2041
+ ...extras.post
2042
+ ];
2214
2043
  }
2215
2044
 
2216
2045
  // node/vite/markdown.ts
@@ -2265,10 +2094,10 @@ async function createMarkdownPlugin(options, { markdown: mdOptions }) {
2265
2094
  }
2266
2095
 
2267
2096
  // node/vite/monacoTypes.ts
2268
- import fs7 from "node:fs/promises";
2097
+ import fs6 from "node:fs/promises";
2269
2098
  import { dirname, resolve as resolve5 } from "node:path";
2270
- import { slash as slash4 } from "@antfu/utils";
2271
- import fg3 from "fast-glob";
2099
+ import { slash as slash3 } from "@antfu/utils";
2100
+ import fg2 from "fast-glob";
2272
2101
  import { findDepPkgJsonPath } from "vitefu";
2273
2102
  function createMonacoTypesLoader({ userRoot, utils }) {
2274
2103
  return {
@@ -2289,8 +2118,8 @@ function createMonacoTypesLoader({ userRoot, utils }) {
2289
2118
  const pkgJsonPath = await findDepPkgJsonPath(pkg, importer);
2290
2119
  if (!pkgJsonPath)
2291
2120
  throw new Error(`Package "${pkg}" not found in "${importer}"`);
2292
- const root = slash4(dirname(pkgJsonPath));
2293
- const pkgJson = JSON.parse(await fs7.readFile(pkgJsonPath, "utf-8"));
2121
+ const root = slash3(dirname(pkgJsonPath));
2122
+ const pkgJson = JSON.parse(await fs6.readFile(pkgJsonPath, "utf-8"));
2294
2123
  let deps = Object.keys(pkgJson.dependencies ?? {});
2295
2124
  deps = deps.filter((pkg2) => !utils.isMonacoTypesIgnored(pkg2));
2296
2125
  return [
@@ -2302,7 +2131,7 @@ function createMonacoTypesLoader({ userRoot, utils }) {
2302
2131
  const query = new URLSearchParams(url.search);
2303
2132
  const root = query.get("root");
2304
2133
  const name = query.get("name");
2305
- const files = await fg3(
2134
+ const files = await fg2(
2306
2135
  [
2307
2136
  "**/*.ts",
2308
2137
  "**/*.mts",
@@ -2350,9 +2179,9 @@ async function createRemoteAssetsPlugin({ data: { config }, mode }, pluginOption
2350
2179
  import ServerRef from "vite-plugin-vue-server-ref";
2351
2180
 
2352
2181
  // node/integrations/drawings.ts
2353
- import { basename, dirname as dirname2, join as join10, resolve as resolve6 } from "node:path";
2354
- import fs8 from "fs-extra";
2355
- import fg4 from "fast-glob";
2182
+ import { basename, dirname as dirname2, join as join9, resolve as resolve6 } from "node:path";
2183
+ import fg3 from "fast-glob";
2184
+ import fs7 from "fs-extra";
2356
2185
  function resolveDrawingsDir(options) {
2357
2186
  return options.data.config.drawings.persist ? resolve6(
2358
2187
  dirname2(options.entry),
@@ -2361,9 +2190,9 @@ function resolveDrawingsDir(options) {
2361
2190
  }
2362
2191
  async function loadDrawings(options) {
2363
2192
  const dir = resolveDrawingsDir(options);
2364
- if (!dir || !fs8.existsSync(dir))
2193
+ if (!dir || !fs7.existsSync(dir))
2365
2194
  return {};
2366
- const files = await fg4("*.svg", {
2195
+ const files = await fg3("*.svg", {
2367
2196
  onlyFiles: true,
2368
2197
  cwd: dir,
2369
2198
  absolute: true,
@@ -2374,7 +2203,7 @@ async function loadDrawings(options) {
2374
2203
  const num = +basename(path4, ".svg");
2375
2204
  if (Number.isNaN(num))
2376
2205
  return;
2377
- const content = await fs8.readFile(path4, "utf8");
2206
+ const content = await fs7.readFile(path4, "utf8");
2378
2207
  const lines = content.split(/\n/g);
2379
2208
  obj[num.toString()] = lines.slice(1, -1).join("\n");
2380
2209
  }));
@@ -2387,7 +2216,7 @@ async function writeDrawings(options, drawing) {
2387
2216
  const width = options.data.config.canvasWidth;
2388
2217
  const height = Math.round(width / options.data.config.aspectRatio);
2389
2218
  const SVG_HEAD = `<svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">`;
2390
- await fs8.ensureDir(dir);
2219
+ await fs7.ensureDir(dir);
2391
2220
  return Promise.all(
2392
2221
  Object.entries(drawing).map(async ([key, value]) => {
2393
2222
  if (!value)
@@ -2395,14 +2224,34 @@ async function writeDrawings(options, drawing) {
2395
2224
  const svg = `${SVG_HEAD}
2396
2225
  ${value}
2397
2226
  </svg>`;
2398
- await fs8.writeFile(join10(dir, `${key}.svg`), svg, "utf-8");
2227
+ await fs7.writeFile(join9(dir, `${key}.svg`), svg, "utf-8");
2399
2228
  })
2400
2229
  );
2401
2230
  }
2402
2231
 
2232
+ // node/integrations/snapshots.ts
2233
+ import { dirname as dirname3, join as join10, resolve as resolve7 } from "node:path";
2234
+ import fs8 from "fs-extra";
2235
+ function resolveSnapshotsDir(options) {
2236
+ return resolve7(dirname3(options.entry), ".slidev/snapshots");
2237
+ }
2238
+ async function loadSnapshots(options) {
2239
+ const dir = resolveSnapshotsDir(options);
2240
+ const file = join10(dir, "snapshots.json");
2241
+ if (!dir || !fs8.existsSync(file))
2242
+ return {};
2243
+ return JSON.parse(await fs8.readFile(file, "utf8"));
2244
+ }
2245
+ async function writeSnapshots(options, data) {
2246
+ const dir = resolveSnapshotsDir(options);
2247
+ if (!dir)
2248
+ return;
2249
+ await fs8.ensureDir(dir);
2250
+ await fs8.writeFile(join10(dir, "snapshots.json"), JSON.stringify(data, null, 2), "utf-8");
2251
+ }
2252
+
2403
2253
  // node/vite/serverRef.ts
2404
2254
  async function createServerRefPlugin(options, pluginOptions) {
2405
- const drawingData = await loadDrawings(options);
2406
2255
  return ServerRef({
2407
2256
  debug: false,
2408
2257
  // process.env.NODE_ENV === 'development',
@@ -2412,37 +2261,56 @@ async function createServerRefPlugin(options, pluginOptions) {
2412
2261
  page: 0,
2413
2262
  clicks: 0
2414
2263
  },
2415
- drawings: drawingData,
2264
+ drawings: await loadDrawings(options),
2265
+ snapshots: await loadSnapshots(options),
2416
2266
  ...pluginOptions.serverRef?.state
2417
2267
  },
2418
2268
  onChanged(key, data, patch, timestamp) {
2419
2269
  pluginOptions.serverRef?.onChanged?.(key, data, patch, timestamp);
2420
- if (!options.data.config.drawings.persist)
2421
- return;
2422
- if (key === "drawings")
2270
+ if (options.data.config.drawings.persist && key === "drawings")
2423
2271
  writeDrawings(options, patch ?? data);
2272
+ if (key === "snapshots")
2273
+ writeSnapshots(options, data);
2424
2274
  }
2425
2275
  });
2426
2276
  }
2427
2277
 
2278
+ // node/vite/staticCopy.ts
2279
+ import { existsSync as existsSync5 } from "node:fs";
2280
+ import { join as join11 } from "node:path";
2281
+ async function createStaticCopyPlugin({ themeRoots, addonRoots }, pluginOptions) {
2282
+ const publicDirs = [...themeRoots, ...addonRoots].map((i) => join11(i, "public")).filter(existsSync5);
2283
+ if (!publicDirs.length)
2284
+ return;
2285
+ const { viteStaticCopy } = await import("vite-plugin-static-copy");
2286
+ return viteStaticCopy({
2287
+ silent: true,
2288
+ targets: publicDirs.map((dir) => ({
2289
+ src: `${dir}/*`,
2290
+ dest: "theme"
2291
+ })),
2292
+ ...pluginOptions.staticCopy
2293
+ });
2294
+ }
2295
+
2428
2296
  // node/vite/unocss.ts
2429
2297
  import UnoCSS from "unocss/vite";
2430
2298
 
2431
2299
  // node/setups/unocss.ts
2432
- import { resolve as resolve7 } from "node:path";
2433
- import { existsSync as existsSync6, readFileSync as readFileSync2 } from "node:fs";
2300
+ import { existsSync as existsSync6, readFileSync } from "node:fs";
2301
+ import { resolve as resolve8 } from "node:path";
2434
2302
  import { mergeConfigs, presetIcons } from "unocss";
2435
2303
  async function setupUnocss({ clientRoot, roots, data, utils }) {
2436
- function loadFileConfigs(root) {
2437
- return [
2438
- resolve7(root, "uno.config.ts"),
2439
- resolve7(root, "unocss.config.ts")
2440
- ].map((i) => {
2304
+ async function loadFileConfigs(root) {
2305
+ return (await Promise.all([
2306
+ resolve8(root, "uno.config.ts"),
2307
+ resolve8(root, "unocss.config.ts")
2308
+ ].map(async (i) => {
2441
2309
  if (!existsSync6(i))
2442
2310
  return void 0;
2443
- const loaded = loadModule(i);
2311
+ const loaded = await loadModule(i);
2444
2312
  return "default" in loaded ? loaded.default : loaded;
2445
- });
2313
+ }))).filter((x) => !!x);
2446
2314
  }
2447
2315
  const configs = [
2448
2316
  {
@@ -2451,13 +2319,13 @@ async function setupUnocss({ clientRoot, roots, data, utils }) {
2451
2319
  collectionsNodeResolvePath: utils.iconsResolvePath,
2452
2320
  collections: {
2453
2321
  slidev: {
2454
- logo: () => readFileSync2(resolve7(clientRoot, "assets/logo.svg"), "utf-8")
2322
+ logo: () => readFileSync(resolve8(clientRoot, "assets/logo.svg"), "utf-8")
2455
2323
  }
2456
2324
  }
2457
2325
  })
2458
2326
  ]
2459
2327
  },
2460
- ...loadFileConfigs(clientRoot),
2328
+ ...await loadFileConfigs(clientRoot),
2461
2329
  ...await loadSetups(roots, "unocss.ts", [], loadFileConfigs)
2462
2330
  ].filter(Boolean);
2463
2331
  const config = mergeConfigs(configs);
@@ -2536,24 +2404,6 @@ async function createVuePlugin(_options, pluginOptions) {
2536
2404
  ];
2537
2405
  }
2538
2406
 
2539
- // node/vite/staticCopy.ts
2540
- import { existsSync as existsSync7 } from "node:fs";
2541
- import { join as join11 } from "node:path";
2542
- async function createStaticCopyPlugin({ themeRoots, addonRoots }, pluginOptions) {
2543
- const publicDirs = [...themeRoots, ...addonRoots].map((i) => join11(i, "public")).filter(existsSync7);
2544
- if (!publicDirs.length)
2545
- return;
2546
- const { viteStaticCopy } = await import("vite-plugin-static-copy");
2547
- return viteStaticCopy({
2548
- silent: true,
2549
- targets: publicDirs.map((dir) => ({
2550
- src: `${dir}/*`,
2551
- dest: "theme"
2552
- })),
2553
- ...pluginOptions.staticCopy
2554
- });
2555
- }
2556
-
2557
2407
  // node/vite/index.ts
2558
2408
  async function ViteSlidevPlugin(options, pluginOptions = {}, serverOptions = {}) {
2559
2409
  return Promise.all([
@@ -2593,7 +2443,7 @@ async function resolveViteConfigs(options, baseConfig, overrideConfigs, command,
2593
2443
  };
2594
2444
  const files = options.roots.map((i) => join12(i, "vite.config.ts"));
2595
2445
  for (const file of files) {
2596
- if (!existsSync8(file))
2446
+ if (!existsSync7(file))
2597
2447
  continue;
2598
2448
  const viteConfig = await loadConfigFromFile(configEnv, file);
2599
2449
  if (!viteConfig?.config)
@@ -2613,15 +2463,184 @@ async function resolveViteConfigs(options, baseConfig, overrideConfigs, command,
2613
2463
  return baseConfig;
2614
2464
  }
2615
2465
 
2466
+ // node/setups/indexHtml.ts
2467
+ function toAttrValue(unsafe) {
2468
+ return JSON.stringify(escapeHtml(String(unsafe)));
2469
+ }
2470
+ function setupIndexHtml({ mode, entry, clientRoot, userRoot, roots, data }) {
2471
+ let main = readFileSync2(join13(clientRoot, "index.html"), "utf-8");
2472
+ let head = "";
2473
+ let body = "";
2474
+ const { info, author, keywords } = data.headmatter;
2475
+ head += [
2476
+ `<meta name="slidev:version" content="${version}">`,
2477
+ mode === "dev" && `<meta charset="slidev:entry" content="${slash4(entry)}">`,
2478
+ `<link rel="icon" href="${data.config.favicon}">`,
2479
+ `<title>${getSlideTitle(data)}</title>`,
2480
+ info && `<meta name="description" content=${toAttrValue(info)}>`,
2481
+ author && `<meta name="author" content=${toAttrValue(author)}>`,
2482
+ keywords && `<meta name="keywords" content=${toAttrValue(Array.isArray(keywords) ? keywords.join(", ") : keywords)}>`
2483
+ ].filter(Boolean).join("\n");
2484
+ for (const root of roots) {
2485
+ const path4 = join13(root, "index.html");
2486
+ if (!existsSync8(path4))
2487
+ continue;
2488
+ const index = readFileSync2(path4, "utf-8");
2489
+ if (root === userRoot && index.includes("<!DOCTYPE")) {
2490
+ console.error(yellow2(`[Slidev] Ignored provided index.html with doctype declaration. (${white(path4)})`));
2491
+ console.error(yellow2("This file may be generated by Slidev, please remove it from your project."));
2492
+ continue;
2493
+ }
2494
+ head += `
2495
+ ${(index.match(/<head>([\s\S]*?)<\/head>/i)?.[1] || "").trim()}`;
2496
+ body += `
2497
+ ${(index.match(/<body>([\s\S]*?)<\/body>/i)?.[1] || "").trim()}`;
2498
+ }
2499
+ if (data.features.tweet)
2500
+ body += '\n<script async src="https://platform.twitter.com/widgets.js"></script>';
2501
+ if (data.config.fonts.webfonts.length && data.config.fonts.provider !== "none")
2502
+ head += `
2503
+ <link rel="stylesheet" href="${generateGoogleFontsUrl(data.config.fonts)}" type="text/css">`;
2504
+ main = main.replace("__ENTRY__", toAtFS(join13(clientRoot, "main.ts"))).replace("<!-- head -->", head).replace("<!-- body -->", body);
2505
+ return main;
2506
+ }
2507
+
2508
+ // node/setups/shiki.ts
2509
+ import fs9 from "node:fs/promises";
2510
+ import { bundledLanguages, createHighlighter } from "shiki";
2511
+ var cachedRoots;
2512
+ var cachedShiki;
2513
+ async function setupShiki(roots) {
2514
+ if (cachedRoots === roots)
2515
+ return cachedShiki;
2516
+ cachedShiki?.shiki.dispose();
2517
+ const options = await loadSetups(
2518
+ roots,
2519
+ "shiki.ts",
2520
+ [{
2521
+ /** @deprecated */
2522
+ async loadTheme(path4) {
2523
+ console.warn("[slidev] `loadTheme` in `setup/shiki.ts` is deprecated. Pass directly the theme name it's supported by Shiki. For custom themes, load it manually via `JSON.parse(fs.readFileSync(path, 'utf-8'))` and pass the raw JSON object instead.");
2524
+ return JSON.parse(await fs9.readFile(path4, "utf-8"));
2525
+ }
2526
+ }]
2527
+ );
2528
+ const mergedOptions = Object.assign({}, ...options);
2529
+ if ("theme" in mergedOptions && "themes" in mergedOptions)
2530
+ delete mergedOptions.theme;
2531
+ if (mergedOptions.theme && typeof mergedOptions.theme !== "string" && !mergedOptions.theme.name && !mergedOptions.theme.tokenColors) {
2532
+ mergedOptions.themes = mergedOptions.theme;
2533
+ delete mergedOptions.theme;
2534
+ }
2535
+ if (!mergedOptions.theme && !mergedOptions.themes) {
2536
+ mergedOptions.themes = {
2537
+ dark: "vitesse-dark",
2538
+ light: "vitesse-light"
2539
+ };
2540
+ }
2541
+ if (mergedOptions.themes)
2542
+ mergedOptions.defaultColor = false;
2543
+ const shiki = await createHighlighter({
2544
+ ...mergedOptions,
2545
+ langs: mergedOptions.langs ?? Object.keys(bundledLanguages),
2546
+ themes: "themes" in mergedOptions ? Object.values(mergedOptions.themes) : [mergedOptions.theme]
2547
+ });
2548
+ cachedRoots = roots;
2549
+ return cachedShiki = {
2550
+ shiki,
2551
+ shikiOptions: mergedOptions
2552
+ };
2553
+ }
2554
+
2555
+ // node/options.ts
2556
+ var debug = Debug("slidev:options");
2557
+ async function resolveOptions(entryOptions, mode) {
2558
+ const entry = await resolveEntry(entryOptions.entry);
2559
+ const rootsInfo = await getRoots(entry);
2560
+ const loaded = await parser.load(rootsInfo.userRoot, entry, void 0, mode);
2561
+ let themeRaw = entryOptions.theme || loaded.headmatter.theme;
2562
+ themeRaw = themeRaw === null ? "none" : themeRaw || "default";
2563
+ const [theme, themeRoot] = await resolveTheme(themeRaw, entry);
2564
+ const themeRoots = themeRoot ? [themeRoot] : [];
2565
+ const themeMeta = themeRoot ? await getThemeMeta(theme, themeRoot) : void 0;
2566
+ const config = parser.resolveConfig(loaded.headmatter, themeMeta, entryOptions.entry);
2567
+ const addonRoots = await resolveAddons(config.addons);
2568
+ const roots = uniq5([...themeRoots, ...addonRoots, rootsInfo.userRoot]);
2569
+ debug({
2570
+ ...rootsInfo,
2571
+ ...entryOptions,
2572
+ config,
2573
+ mode,
2574
+ entry,
2575
+ themeRaw,
2576
+ theme,
2577
+ themeRoots,
2578
+ addonRoots,
2579
+ roots
2580
+ });
2581
+ const data = {
2582
+ ...loaded,
2583
+ config,
2584
+ themeMeta
2585
+ };
2586
+ const resolved = {
2587
+ ...rootsInfo,
2588
+ ...entryOptions,
2589
+ data,
2590
+ mode,
2591
+ entry,
2592
+ themeRaw,
2593
+ theme,
2594
+ themeRoots,
2595
+ addonRoots,
2596
+ roots
2597
+ };
2598
+ return {
2599
+ ...resolved,
2600
+ utils: await createDataUtils(resolved)
2601
+ };
2602
+ }
2603
+ async function createDataUtils(resolved) {
2604
+ const monacoTypesIgnorePackagesMatches = (resolved.data.config.monacoTypesIgnorePackages || []).map((i) => mm.matcher(i));
2605
+ let _layouts_cache_time = 0;
2606
+ let _layouts_cache = {};
2607
+ return {
2608
+ ...await setupShiki(resolved.roots),
2609
+ indexHtml: setupIndexHtml(resolved),
2610
+ iconsResolvePath: [resolved.clientRoot, ...resolved.roots].reverse(),
2611
+ isMonacoTypesIgnored: (pkg) => monacoTypesIgnorePackagesMatches.some((i) => i(pkg)),
2612
+ getLayouts: () => {
2613
+ const now = Date.now();
2614
+ if (now - _layouts_cache_time < 2e3)
2615
+ return _layouts_cache;
2616
+ const layouts = {};
2617
+ for (const root of [resolved.clientRoot, ...resolved.roots]) {
2618
+ const layoutPaths = fg4.sync("layouts/**/*.{vue,ts}", {
2619
+ cwd: root,
2620
+ absolute: true,
2621
+ suppressErrors: true
2622
+ });
2623
+ for (const layoutPath of layoutPaths) {
2624
+ const layoutName = path3.basename(layoutPath).replace(/\.\w+$/, "");
2625
+ layouts[layoutName] = layoutPath;
2626
+ }
2627
+ }
2628
+ _layouts_cache_time = now;
2629
+ _layouts_cache = layouts;
2630
+ return layouts;
2631
+ }
2632
+ };
2633
+ }
2634
+
2616
2635
  export {
2617
- resolveViteConfigs,
2618
- parser,
2619
2636
  version,
2637
+ resolveAddons,
2620
2638
  resolveTheme,
2621
2639
  getThemeMeta,
2622
- resolveAddons,
2640
+ parser,
2623
2641
  loadSetups,
2624
2642
  resolveOptions,
2625
2643
  createDataUtils,
2626
- ViteSlidevPlugin
2644
+ ViteSlidevPlugin,
2645
+ resolveViteConfigs
2627
2646
  };