vitepress-allyouneed 0.1.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.
package/dist/vite.cjs ADDED
@@ -0,0 +1,783 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/vite.ts
31
+ var vite_exports = {};
32
+ __export(vite_exports, {
33
+ default: () => vite_default,
34
+ viteAllYouNeed: () => viteAllYouNeed
35
+ });
36
+ module.exports = __toCommonJS(vite_exports);
37
+ var import_node_fs5 = __toESM(require("fs"), 1);
38
+ var import_node_path6 = __toESM(require("path"), 1);
39
+
40
+ // src/core/slugify.ts
41
+ var import_shared = require("@mdit-vue/shared");
42
+ function defaultSlugify(text) {
43
+ return (0, import_shared.slugify)(text);
44
+ }
45
+ var CUSTOM_ID_RE = /\s*\{#([^}\s]+)\}\s*$/;
46
+ function extractCustomId(headingText) {
47
+ const m = headingText.match(CUSTOM_ID_RE);
48
+ if (!m) return { text: headingText, customId: void 0 };
49
+ return {
50
+ text: headingText.replace(CUSTOM_ID_RE, ""),
51
+ customId: m[1]
52
+ };
53
+ }
54
+
55
+ // src/core/config-bridge.ts
56
+ var DEFAULT_ASSET_EXTENSIONS = [
57
+ // 位图
58
+ "bmp",
59
+ "gif",
60
+ "jpeg",
61
+ "jpg",
62
+ "png",
63
+ "svg",
64
+ "webp",
65
+ "avif",
66
+ "ico",
67
+ // 视频
68
+ "mp4",
69
+ "webm",
70
+ "mov",
71
+ "m4v",
72
+ // 音频
73
+ "mp3",
74
+ "wav",
75
+ "ogg",
76
+ "m4a",
77
+ "flac",
78
+ // 文档
79
+ "pdf",
80
+ // Obsidian 专属
81
+ "canvas",
82
+ "excalidraw"
83
+ ];
84
+ var DEFAULT_IMAGE_EXTENSIONS = [
85
+ "bmp",
86
+ "gif",
87
+ "jpeg",
88
+ "jpg",
89
+ "png",
90
+ "svg",
91
+ "webp",
92
+ "avif",
93
+ "ico"
94
+ ];
95
+ function resolveOptions(user = {}, ctx = {}) {
96
+ const srcDir = user.srcDir ?? ctx.srcDir ?? process.cwd();
97
+ let base = user.base ?? ctx.base ?? "/";
98
+ if (!base.startsWith("/")) base = "/" + base;
99
+ if (!base.endsWith("/")) base = base + "/";
100
+ const cleanUrls = user.cleanUrls ?? ctx.cleanUrls ?? false;
101
+ const slugify = user.slugify ?? ctx.externalSlugify ?? defaultSlugify;
102
+ const wikilinksUser = user.wikilinks ?? {};
103
+ const embedsUser = user.embeds ?? {};
104
+ const scanUser = user.scan ?? {};
105
+ const assetsUser = user.assets ?? {};
106
+ const modulesUser = user.modules ?? {};
107
+ const wikilinksHtmlAttrs = wikilinksUser.htmlAttributes ?? {};
108
+ const embedsHtmlAttrs = embedsUser.htmlAttributes ?? {};
109
+ return {
110
+ srcDir,
111
+ base,
112
+ cleanUrls,
113
+ caseSensitive: user.caseSensitive ?? false,
114
+ deadLink: user.deadLink ?? "warn",
115
+ onConflict: user.onConflict ?? "shortest",
116
+ onAliasConflict: user.onAliasConflict ?? "first",
117
+ scan: {
118
+ include: scanUser.include ?? ["**/*.md", "**/*.markdown"],
119
+ exclude: scanUser.exclude ?? [],
120
+ followSymlinks: scanUser.followSymlinks ?? false,
121
+ respectGitignore: scanUser.respectGitignore ?? true,
122
+ assetExtensions: scanUser.assetExtensions ?? DEFAULT_ASSET_EXTENSIONS
123
+ },
124
+ assets: {
125
+ mode: assetsUser.mode ?? "auto",
126
+ preserveAssetPaths: assetsUser.preserveAssetPaths ?? false,
127
+ outputDir: assetsUser.outputDir ?? "_assets"
128
+ },
129
+ wikilinks: {
130
+ postProcessLinkTarget: wikilinksUser.postProcessLinkTarget ?? ((t) => t.trim()),
131
+ postProcessLinkLabel: wikilinksUser.postProcessLinkLabel ?? ((l) => l.trim()),
132
+ allowLinkLabelFormatting: wikilinksUser.allowLinkLabelFormatting ?? false,
133
+ linkText: wikilinksUser.linkText ?? "basename",
134
+ htmlAttributes: wikilinksHtmlAttrs
135
+ },
136
+ embeds: {
137
+ imageFileExt: embedsUser.imageFileExt ?? DEFAULT_IMAGE_EXTENSIONS,
138
+ defaultAltText: embedsUser.defaultAltText ?? false,
139
+ postProcessImageTarget: embedsUser.postProcessImageTarget ?? ((t) => t.trim()),
140
+ postProcessAltText: embedsUser.postProcessAltText ?? ((a) => a.trim()),
141
+ uriSuffix: embedsUser.uriSuffix ?? "",
142
+ transclusionMaxDepth: embedsUser.transclusionMaxDepth ?? 8,
143
+ htmlAttributes: embedsHtmlAttrs
144
+ },
145
+ modules: {
146
+ wikilinks: modulesUser.wikilinks ?? true,
147
+ embeds: modulesUser.embeds ?? true
148
+ },
149
+ slugify
150
+ };
151
+ }
152
+
153
+ // src/core/vault/index.ts
154
+ var import_node_fs3 = __toESM(require("fs"), 1);
155
+ var import_node_path4 = __toESM(require("path"), 1);
156
+
157
+ // src/utils/path.ts
158
+ var import_node_path = __toESM(require("path"), 1);
159
+ function toPosix(p) {
160
+ return p.replace(/\\/g, "/");
161
+ }
162
+ function relative(from, to) {
163
+ return toPosix(import_node_path.default.relative(from, to));
164
+ }
165
+ function basename(p, stripExt = false) {
166
+ const idx = p.lastIndexOf("/");
167
+ const file = idx === -1 ? p : p.slice(idx + 1);
168
+ if (!stripExt) return file;
169
+ const dot = file.lastIndexOf(".");
170
+ return dot <= 0 ? file : file.slice(0, dot);
171
+ }
172
+ function extname(p) {
173
+ const file = basename(p);
174
+ const dot = file.lastIndexOf(".");
175
+ if (dot <= 0) return "";
176
+ return file.slice(dot + 1).toLowerCase();
177
+ }
178
+
179
+ // src/utils/url.ts
180
+ function encodePath(s) {
181
+ return encodeURI(s);
182
+ }
183
+ function buildUrl(base, pathSegments, anchor) {
184
+ let normBase = base || "/";
185
+ if (!normBase.startsWith("/")) normBase = "/" + normBase;
186
+ if (!normBase.endsWith("/")) normBase = normBase + "/";
187
+ const joined = pathSegments.map((s) => s.replace(/^\/+|\/+$/g, "")).filter(Boolean).join("/");
188
+ let url = normBase + joined;
189
+ url = url.replace(/\/{2,}/g, "/");
190
+ url = encodePath(url);
191
+ if (anchor) {
192
+ url += "#" + encodeURIComponent(anchor).replace(/%2F/g, "/");
193
+ }
194
+ return url;
195
+ }
196
+ function applyCleanUrls(path, cleanUrls) {
197
+ if (cleanUrls) return path;
198
+ if (/\.html$/i.test(path)) return path;
199
+ if (path.endsWith("/")) return path + "index.html";
200
+ return path + ".html";
201
+ }
202
+
203
+ // src/core/vault/scan.ts
204
+ var import_node_fs = __toESM(require("fs"), 1);
205
+ var import_node_path2 = __toESM(require("path"), 1);
206
+ function walk(srcDir, isIgnored, followSymlinks) {
207
+ const out = [];
208
+ const seenInodes = /* @__PURE__ */ new Set();
209
+ function visit(dir) {
210
+ let entries;
211
+ try {
212
+ entries = import_node_fs.default.readdirSync(dir, { withFileTypes: true });
213
+ } catch {
214
+ return;
215
+ }
216
+ for (const ent of entries) {
217
+ const full = import_node_path2.default.join(dir, ent.name);
218
+ const posix = toPosix(full);
219
+ if (isIgnored(posix)) continue;
220
+ let isDir = ent.isDirectory();
221
+ let isFile = ent.isFile();
222
+ if (ent.isSymbolicLink()) {
223
+ if (!followSymlinks) continue;
224
+ try {
225
+ const stat = import_node_fs.default.statSync(full);
226
+ isDir = stat.isDirectory();
227
+ isFile = stat.isFile();
228
+ } catch {
229
+ continue;
230
+ }
231
+ }
232
+ if (isDir) {
233
+ if (followSymlinks) {
234
+ try {
235
+ const stat = import_node_fs.default.statSync(full);
236
+ const key = `${stat.dev}:${stat.ino}`;
237
+ if (seenInodes.has(key)) continue;
238
+ seenInodes.add(key);
239
+ } catch {
240
+ continue;
241
+ }
242
+ }
243
+ visit(full);
244
+ } else if (isFile) {
245
+ try {
246
+ const stat = import_node_fs.default.statSync(full);
247
+ out.push({
248
+ absolutePath: posix,
249
+ size: stat.size,
250
+ mtime: stat.mtimeMs,
251
+ extension: extname(posix)
252
+ });
253
+ } catch {
254
+ }
255
+ }
256
+ }
257
+ }
258
+ visit(srcDir);
259
+ return out;
260
+ }
261
+
262
+ // src/core/vault/ignore.ts
263
+ var import_node_fs2 = __toESM(require("fs"), 1);
264
+ var import_node_path3 = __toESM(require("path"), 1);
265
+ var import_picomatch = __toESM(require("picomatch"), 1);
266
+ var HARD_IGNORE_DIRS = /* @__PURE__ */ new Set([
267
+ "node_modules",
268
+ ".git",
269
+ ".svn",
270
+ ".hg",
271
+ ".obsidian",
272
+ ".trash",
273
+ ".vitepress",
274
+ ".next",
275
+ ".nuxt",
276
+ ".cache",
277
+ ".idea",
278
+ ".vscode",
279
+ "dist",
280
+ "build"
281
+ ]);
282
+ function buildIgnorer(srcDir, userExclude, respectGitignore) {
283
+ const patterns = [...userExclude];
284
+ if (respectGitignore) {
285
+ const gitignore = import_node_path3.default.join(srcDir, ".gitignore");
286
+ try {
287
+ const content = import_node_fs2.default.readFileSync(gitignore, "utf8");
288
+ for (const line of content.split(/\r?\n/)) {
289
+ const trimmed = line.trim();
290
+ if (!trimmed || trimmed.startsWith("#")) continue;
291
+ patterns.push(trimmed.endsWith("/") ? trimmed + "**" : trimmed);
292
+ }
293
+ } catch {
294
+ }
295
+ }
296
+ const matchers = patterns.map(
297
+ (p) => (0, import_picomatch.default)(p, { dot: true, nocase: false })
298
+ );
299
+ return (absPath) => {
300
+ const rel = toPosix(relative(srcDir, absPath));
301
+ if (!rel || rel.startsWith("..")) return true;
302
+ for (const seg of rel.split("/")) {
303
+ if (HARD_IGNORE_DIRS.has(seg)) return true;
304
+ }
305
+ for (const m of matchers) {
306
+ if (m(rel)) return true;
307
+ }
308
+ return false;
309
+ };
310
+ }
311
+
312
+ // src/core/vault/frontmatter.ts
313
+ var import_gray_matter = __toESM(require("gray-matter"), 1);
314
+ function parseFrontmatter(raw) {
315
+ try {
316
+ const { data, content } = (0, import_gray_matter.default)(raw);
317
+ return { data: data ?? {}, content };
318
+ } catch (err) {
319
+ return {
320
+ data: {},
321
+ content: raw,
322
+ error: err instanceof Error ? err.message : String(err)
323
+ };
324
+ }
325
+ }
326
+ function normalizeAliases(raw) {
327
+ if (raw == null) return [];
328
+ if (typeof raw === "string") return raw.trim() ? [raw.trim()] : [];
329
+ if (Array.isArray(raw)) {
330
+ return raw.filter((v) => typeof v === "string").map((s) => s.trim()).filter(Boolean);
331
+ }
332
+ return [];
333
+ }
334
+ function normalizeTags(raw) {
335
+ if (raw == null) return [];
336
+ if (typeof raw === "string") {
337
+ return raw.split(/[,\s]+/).map((s) => s.trim().replace(/^#/, "")).filter(Boolean);
338
+ }
339
+ if (Array.isArray(raw)) {
340
+ return raw.filter((v) => typeof v === "string").map((s) => s.trim().replace(/^#/, "")).filter(Boolean);
341
+ }
342
+ return [];
343
+ }
344
+
345
+ // src/core/vault/headings.ts
346
+ var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
347
+ var FENCE_RE = /^(`{3,}|~{3,})/;
348
+ function collectHeadings(content, slugify) {
349
+ const lines = content.split(/\r?\n/);
350
+ const out = [];
351
+ let inFence = false;
352
+ let fenceMarker = "";
353
+ for (let i = 0; i < lines.length; i++) {
354
+ const line = lines[i];
355
+ const fenceMatch = line.match(FENCE_RE);
356
+ if (fenceMatch) {
357
+ if (!inFence) {
358
+ inFence = true;
359
+ fenceMarker = fenceMatch[1];
360
+ } else if (line.startsWith(fenceMarker)) {
361
+ inFence = false;
362
+ fenceMarker = "";
363
+ }
364
+ continue;
365
+ }
366
+ if (inFence) continue;
367
+ const m = line.match(HEADING_RE);
368
+ if (!m) continue;
369
+ const level = m[1].length;
370
+ const rawText = m[2];
371
+ const { text, customId } = extractCustomId(rawText);
372
+ const slug = customId ?? slugify(text);
373
+ out.push({ level, text, slug, line: i });
374
+ }
375
+ return out;
376
+ }
377
+
378
+ // src/core/vault/index.ts
379
+ var MD_EXTENSIONS = /* @__PURE__ */ new Set(["md", "markdown"]);
380
+ function createEmptyIndex(srcDir = "", base = "/", cleanUrls = false) {
381
+ return {
382
+ files: /* @__PURE__ */ new Map(),
383
+ assets: /* @__PURE__ */ new Map(),
384
+ byBasename: /* @__PURE__ */ new Map(),
385
+ byBasenameLower: /* @__PURE__ */ new Map(),
386
+ byAlias: /* @__PURE__ */ new Map(),
387
+ byRelativePath: /* @__PURE__ */ new Map(),
388
+ byUrl: /* @__PURE__ */ new Map(),
389
+ assetsByBasename: /* @__PURE__ */ new Map(),
390
+ assetsByBasenameLower: /* @__PURE__ */ new Map(),
391
+ assetsByRelativePath: /* @__PURE__ */ new Map(),
392
+ tags: /* @__PURE__ */ new Map(),
393
+ backlinks: /* @__PURE__ */ new Map(),
394
+ headings: /* @__PURE__ */ new Map(),
395
+ srcDir,
396
+ base,
397
+ cleanUrls,
398
+ scannedAt: Date.now(),
399
+ warnings: []
400
+ };
401
+ }
402
+ function scanVault(options) {
403
+ const srcDir = toPosix(import_node_path4.default.resolve(options.srcDir));
404
+ const index = createEmptyIndex(srcDir, options.base, options.cleanUrls);
405
+ const isIgnored = buildIgnorer(
406
+ srcDir,
407
+ options.scan.exclude,
408
+ options.scan.respectGitignore
409
+ );
410
+ const assetExtSet = new Set(
411
+ options.scan.assetExtensions.map((e) => e.toLowerCase())
412
+ );
413
+ const entries = walk(srcDir, isIgnored, options.scan.followSymlinks);
414
+ for (const ent of entries) {
415
+ const ext = ent.extension;
416
+ if (MD_EXTENSIONS.has(ext)) {
417
+ ingestMarkdown(index, ent.absolutePath, ent.size, ent.mtime, options);
418
+ } else if (assetExtSet.has(ext)) {
419
+ ingestAsset(index, ent.absolutePath, ent.size, ent.mtime, ext);
420
+ }
421
+ }
422
+ index.scannedAt = Date.now();
423
+ return index;
424
+ }
425
+ function ingestMarkdown(index, absPath, size, mtime, options) {
426
+ let raw;
427
+ try {
428
+ raw = import_node_fs3.default.readFileSync(absPath, "utf8");
429
+ } catch (err) {
430
+ index.warnings.push({
431
+ kind: "unreadable-file",
432
+ message: `\u65E0\u6CD5\u8BFB\u53D6\u6587\u4EF6: ${absPath} (${err instanceof Error ? err.message : String(err)})`,
433
+ affected: [absPath]
434
+ });
435
+ return;
436
+ }
437
+ const { data, content, error } = parseFrontmatter(raw);
438
+ if (error) {
439
+ index.warnings.push({
440
+ kind: "invalid-frontmatter",
441
+ message: `frontmatter \u89E3\u6790\u5931\u8D25 (${absPath}): ${error}`,
442
+ affected: [absPath]
443
+ });
444
+ }
445
+ const aliases = normalizeAliases(data.aliases);
446
+ const tags = normalizeTags(data.tags);
447
+ const headings = collectHeadings(content, options.slugify);
448
+ const rel = relative(index.srcDir, absPath);
449
+ const base = basename(absPath, true);
450
+ const ext = extname(absPath);
451
+ const url = computeUrl(rel, options);
452
+ const entry = {
453
+ absolutePath: absPath,
454
+ relativePath: rel,
455
+ basename: base,
456
+ extension: ext,
457
+ url,
458
+ frontmatter: data,
459
+ aliases,
460
+ tags,
461
+ headings,
462
+ mtime,
463
+ size,
464
+ content
465
+ };
466
+ registerFileEntry(index, entry, options);
467
+ }
468
+ function ingestAsset(index, absPath, size, mtime, ext) {
469
+ const rel = relative(index.srcDir, absPath);
470
+ const base = basename(absPath);
471
+ const entry = {
472
+ absolutePath: absPath,
473
+ relativePath: rel,
474
+ basename: base,
475
+ extension: ext,
476
+ mtime,
477
+ size,
478
+ referencedBy: /* @__PURE__ */ new Set()
479
+ };
480
+ index.assets.set(absPath, entry);
481
+ index.assetsByRelativePath.set(rel, entry);
482
+ pushToArrayMap(index.assetsByBasename, base, entry);
483
+ pushToArrayMap(index.assetsByBasenameLower, base.toLowerCase(), entry);
484
+ }
485
+ function registerFileEntry(index, entry, options) {
486
+ index.files.set(entry.absolutePath, entry);
487
+ index.byRelativePath.set(entry.relativePath, entry);
488
+ const existingAtUrl = index.byUrl.get(entry.url);
489
+ if (existingAtUrl && existingAtUrl.absolutePath !== entry.absolutePath) {
490
+ index.warnings.push({
491
+ kind: "unknown",
492
+ message: `URL \u51B2\u7A81:\u6587\u4EF6 "${entry.relativePath}" \u548C "${existingAtUrl.relativePath}" \u90FD\u8DEF\u7531\u5230 "${entry.url}"\u3002VitePress \u4F1A\u8BA9\u5176\u4E2D\u4E00\u4E2A 404\u3002\u5EFA\u8BAE\u5728 .vitepress/config \u52A0 srcExclude: ['${entry.relativePath}'](\u6216\u53E6\u4E00\u4E2A)\u3002`,
493
+ affected: [existingAtUrl.absolutePath, entry.absolutePath]
494
+ });
495
+ }
496
+ index.byUrl.set(entry.url, entry);
497
+ index.headings.set(entry.absolutePath, entry.headings);
498
+ pushToArrayMap(index.byBasename, entry.basename, entry);
499
+ pushToArrayMap(index.byBasenameLower, entry.basename.toLowerCase(), entry);
500
+ for (const alias of entry.aliases) {
501
+ const key = options.caseSensitive ? alias : alias.toLowerCase();
502
+ if (index.byAlias.has(key)) {
503
+ index.warnings.push({
504
+ kind: "duplicate-alias",
505
+ message: `alias "${alias}" \u540C\u65F6\u88AB\u591A\u4E2A\u6587\u4EF6\u58F0\u660E,\u6309 onAliasConflict='${options.onAliasConflict}' \u5904\u7406`,
506
+ affected: [index.byAlias.get(key).absolutePath, entry.absolutePath]
507
+ });
508
+ if (options.onAliasConflict === "first") continue;
509
+ }
510
+ index.byAlias.set(key, entry);
511
+ }
512
+ for (const tag of entry.tags) {
513
+ pushToArrayMap(index.tags, tag, entry);
514
+ }
515
+ }
516
+ function computeUrl(rel, options) {
517
+ const noExt = rel.replace(/\.(md|markdown)$/i, "");
518
+ const isIndex = /(^|\/)(index|README)$/i.test(noExt);
519
+ const pathPart = isIndex ? noExt.replace(/(^|\/)(index|README)$/i, "$1") : noExt;
520
+ const segments = pathPart.split("/").filter(Boolean);
521
+ if (segments.length === 0) {
522
+ return options.base;
523
+ }
524
+ const last = segments[segments.length - 1];
525
+ if (!isIndex) {
526
+ segments[segments.length - 1] = applyCleanUrls(last, options.cleanUrls);
527
+ } else if (!options.cleanUrls) {
528
+ segments.push("index.html");
529
+ }
530
+ return buildUrl(options.base, segments);
531
+ }
532
+ function pushToArrayMap(m, k, v) {
533
+ const arr = m.get(k);
534
+ if (arr) arr.push(v);
535
+ else m.set(k, [v]);
536
+ }
537
+ function updateFile(index, absPath, options) {
538
+ const posix = toPosix(absPath);
539
+ removeFile(index, posix, options);
540
+ let stat;
541
+ try {
542
+ stat = import_node_fs3.default.statSync(posix);
543
+ } catch {
544
+ return;
545
+ }
546
+ const ext = extname(posix);
547
+ if (MD_EXTENSIONS.has(ext)) {
548
+ ingestMarkdown(index, posix, stat.size, stat.mtimeMs, options);
549
+ } else if (new Set(options.scan.assetExtensions.map((e) => e.toLowerCase())).has(ext)) {
550
+ ingestAsset(index, posix, stat.size, stat.mtimeMs, ext);
551
+ }
552
+ }
553
+ function removeFile(index, absPath, options) {
554
+ const posix = toPosix(absPath);
555
+ const file = index.files.get(posix);
556
+ if (file) {
557
+ index.files.delete(posix);
558
+ index.byRelativePath.delete(file.relativePath);
559
+ index.byUrl.delete(file.url);
560
+ index.headings.delete(posix);
561
+ removeFromArrayMap(index.byBasename, file.basename, file);
562
+ removeFromArrayMap(
563
+ index.byBasenameLower,
564
+ file.basename.toLowerCase(),
565
+ file
566
+ );
567
+ for (const alias of file.aliases) {
568
+ const key = options.caseSensitive ? alias : alias.toLowerCase();
569
+ if (index.byAlias.get(key) === file) index.byAlias.delete(key);
570
+ }
571
+ for (const tag of file.tags) {
572
+ removeFromArrayMap(index.tags, tag, file);
573
+ }
574
+ return;
575
+ }
576
+ const asset = index.assets.get(posix);
577
+ if (asset) {
578
+ index.assets.delete(posix);
579
+ index.assetsByRelativePath.delete(asset.relativePath);
580
+ removeFromArrayMap(index.assetsByBasename, asset.basename, asset);
581
+ removeFromArrayMap(
582
+ index.assetsByBasenameLower,
583
+ asset.basename.toLowerCase(),
584
+ asset
585
+ );
586
+ }
587
+ }
588
+ function removeFromArrayMap(m, k, v) {
589
+ const arr = m.get(k);
590
+ if (!arr) return;
591
+ const idx = arr.indexOf(v);
592
+ if (idx >= 0) arr.splice(idx, 1);
593
+ if (arr.length === 0) m.delete(k);
594
+ }
595
+
596
+ // src/core/asset-pipeline/dev-middleware.ts
597
+ var import_node_fs4 = __toESM(require("fs"), 1);
598
+ var import_node_path5 = __toESM(require("path"), 1);
599
+ function createDevMiddleware(index, options) {
600
+ return (req, res, next) => {
601
+ if (!req.url) return next();
602
+ const cleanPath = req.url.split("?")[0].split("#")[0];
603
+ let inSiteUrl = cleanPath;
604
+ if (options.base !== "/" && cleanPath.startsWith(options.base)) {
605
+ inSiteUrl = "/" + cleanPath.slice(options.base.length);
606
+ }
607
+ let decoded;
608
+ try {
609
+ decoded = decodeURIComponent(inSiteUrl);
610
+ } catch {
611
+ return next();
612
+ }
613
+ if (!/\.[a-zA-Z0-9]+$/.test(decoded)) return next();
614
+ const relCandidate = decoded.replace(/^\/+/, "");
615
+ let asset = index.assetsByRelativePath.get(relCandidate);
616
+ if (!asset) {
617
+ const bn = basename(decoded);
618
+ const map = options.caseSensitive ? index.assetsByBasename : index.assetsByBasenameLower;
619
+ const key = options.caseSensitive ? bn : bn.toLowerCase();
620
+ const candidates = map.get(key);
621
+ if (candidates && candidates.length > 0) asset = candidates[0];
622
+ }
623
+ if (!asset) return next();
624
+ let stat;
625
+ try {
626
+ stat = import_node_fs4.default.statSync(asset.absolutePath);
627
+ } catch {
628
+ return next();
629
+ }
630
+ res.statusCode = 200;
631
+ res.setHeader("Content-Type", guessMime(asset.extension));
632
+ res.setHeader("Content-Length", String(stat.size));
633
+ res.setHeader("Cache-Control", "no-cache");
634
+ import_node_fs4.default.createReadStream(asset.absolutePath).on("error", () => next()).pipe(res);
635
+ };
636
+ }
637
+ var MIME = {
638
+ png: "image/png",
639
+ jpg: "image/jpeg",
640
+ jpeg: "image/jpeg",
641
+ gif: "image/gif",
642
+ webp: "image/webp",
643
+ svg: "image/svg+xml",
644
+ bmp: "image/bmp",
645
+ avif: "image/avif",
646
+ ico: "image/x-icon",
647
+ mp4: "video/mp4",
648
+ webm: "video/webm",
649
+ mov: "video/quicktime",
650
+ m4v: "video/x-m4v",
651
+ mp3: "audio/mpeg",
652
+ wav: "audio/wav",
653
+ ogg: "audio/ogg",
654
+ m4a: "audio/mp4",
655
+ flac: "audio/flac",
656
+ pdf: "application/pdf",
657
+ canvas: "application/json",
658
+ excalidraw: "application/json"
659
+ };
660
+ function guessMime(ext) {
661
+ return MIME[ext.toLowerCase()] ?? "application/octet-stream";
662
+ }
663
+
664
+ // src/core/asset-pipeline/build-emit.ts
665
+ var ASSET_PLACEHOLDER_PREFIX = "/__ayn_asset__/";
666
+
667
+ // src/vite.ts
668
+ function stripQueryAndHash(id) {
669
+ return id.split("?")[0].split("#")[0];
670
+ }
671
+ function viteAllYouNeed(userOptions = {}) {
672
+ let resolved;
673
+ let index;
674
+ let viteConfig;
675
+ const plugin = {
676
+ name: "vitepress-allyouneed",
677
+ /**
678
+ * 在 Vite 配置定型前扩 server.fs.allow,让我们的 vault srcDir 可被 Vite
679
+ * 服务(即便 srcDir 不在项目根下)。
680
+ */
681
+ config(_userViteConfig, _envCtx) {
682
+ const srcDirOpt = userOptions.srcDir;
683
+ if (!srcDirOpt) return void 0;
684
+ const abs = toPosix(import_node_path6.default.resolve(srcDirOpt));
685
+ return {
686
+ server: {
687
+ fs: {
688
+ allow: [abs]
689
+ }
690
+ }
691
+ };
692
+ },
693
+ configResolved(cfg) {
694
+ viteConfig = cfg;
695
+ resolved = resolveOptions(userOptions, {
696
+ srcDir: userOptions.srcDir ?? cfg.root,
697
+ base: userOptions.base ?? cfg.base,
698
+ cleanUrls: userOptions.cleanUrls
699
+ });
700
+ try {
701
+ index = scanVault(resolved);
702
+ if (index.warnings.length > 0) {
703
+ const top = index.warnings.slice(0, 10);
704
+ for (const w of top) {
705
+ cfg.logger.warn(`[vitepress-allyouneed] ${w.message}`);
706
+ }
707
+ if (index.warnings.length > top.length) {
708
+ cfg.logger.warn(
709
+ `[vitepress-allyouneed] (...\u8FD8\u6709 ${index.warnings.length - top.length} \u6761\u544A\u8B66)`
710
+ );
711
+ }
712
+ }
713
+ } catch (err) {
714
+ cfg.logger.error(
715
+ `[vitepress-allyouneed] vault \u626B\u63CF\u5931\u8D25: ${err instanceof Error ? err.message : String(err)}`
716
+ );
717
+ index = void 0;
718
+ }
719
+ },
720
+ configureServer(server) {
721
+ if (!index) return;
722
+ const mw = createDevMiddleware(index, resolved);
723
+ return () => {
724
+ server.middlewares.use(mw);
725
+ };
726
+ },
727
+ handleHotUpdate(ctx) {
728
+ if (!index) return;
729
+ try {
730
+ const stat = import_node_fs5.default.statSync(ctx.file);
731
+ if (stat.isFile()) {
732
+ updateFile(index, ctx.file, resolved);
733
+ } else if (!import_node_fs5.default.existsSync(ctx.file)) {
734
+ removeFile(index, ctx.file, resolved);
735
+ }
736
+ } catch {
737
+ removeFile(index, ctx.file, resolved);
738
+ }
739
+ },
740
+ /**
741
+ * 拦截占位符 URL,**返回真实绝对文件路径**(POSIX 风格)。
742
+ *
743
+ * Vite 拿到文件路径会:
744
+ * - dev:按文件系统服务,id 经 transform 后变成 `export default '<url>'`
745
+ * - build:emit asset、Rollup 自动加 hash,导出最终 URL
746
+ */
747
+ resolveId(id) {
748
+ if (!index) return null;
749
+ const stripped = stripQueryAndHash(id);
750
+ const ph = ASSET_PLACEHOLDER_PREFIX;
751
+ const phIdx = stripped.indexOf(ph);
752
+ if (phIdx < 0) return null;
753
+ const encoded = stripped.slice(phIdx + ph.length);
754
+ let relPath;
755
+ try {
756
+ relPath = decodeURI(encoded);
757
+ } catch {
758
+ return null;
759
+ }
760
+ const asset = index.assetsByRelativePath.get(relPath);
761
+ if (!asset) return null;
762
+ const query = id.slice(stripped.length);
763
+ return asset.absolutePath + query;
764
+ },
765
+ /**
766
+ * 给 vitepress.ts wrapper 用。
767
+ */
768
+ __getOptions() {
769
+ return resolved;
770
+ },
771
+ __getIndex() {
772
+ return index;
773
+ }
774
+ };
775
+ void viteConfig;
776
+ return plugin;
777
+ }
778
+ var vite_default = viteAllYouNeed;
779
+ // Annotate the CommonJS export names for ESM import in node:
780
+ 0 && (module.exports = {
781
+ viteAllYouNeed
782
+ });
783
+ //# sourceMappingURL=vite.cjs.map