@slidev/cli 0.33.1 → 0.34.0

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