@vuepress/core 2.0.0-rc.26 → 2.0.0-rc.28

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.
Files changed (3) hide show
  1. package/dist/index.d.ts +522 -502
  2. package/dist/index.js +966 -986
  3. package/package.json +24 -30
package/dist/index.js CHANGED
@@ -1,1022 +1,1002 @@
1
- // src/app/prepare/prepareClientConfigs.ts
2
- var prepareClientConfigs = async (app) => {
3
- const clientConfigFiles = await app.pluginApi.hooks.clientConfigFile.process(app);
4
- const content = `${clientConfigFiles.map(
5
- (filePath, index) => `import * as clientConfig${index} from '${filePath}'`
6
- ).join("\n")}
1
+ import { createRequire } from "node:module";
2
+ import { ensureLeadingSlash, formatDateString, inferRoutePath, isFunction, isString, normalizeRoutePath, omit, removeLeadingSlash, resolveLocalePath } from "@vuepress/shared";
3
+ import { colors, debug, fs, hash, logger, path, sanitizeFileName, templateRenderer, tinyglobby, transformPathToFileName, warn } from "@vuepress/utils";
4
+ import { createMarkdown } from "@vuepress/markdown";
5
+ //#region src/app/prepare/prepareClientConfigs.ts
6
+ /**
7
+ * Generate client configs temp file
8
+ *
9
+ * @internal
10
+ */
11
+ const prepareClientConfigs = async (app) => {
12
+ const clientConfigFiles = await app.pluginApi.hooks.clientConfigFile.process(app);
13
+ const content = `\
14
+ ${clientConfigFiles.map((filePath, index) => `import * as clientConfig${index} from '${filePath}'`).join("\n")}
7
15
 
8
16
  export const clientConfigs = [
9
17
  ${clientConfigFiles.map((_, index) => ` clientConfig${index},`).join("\n")}
10
18
  ].map((m) => m.default).filter(Boolean)
11
19
  `;
12
- await app.writeTemp("internal/clientConfigs.js", content);
13
- };
14
-
15
- // src/app/prepare/preparePageChunk.ts
16
- var HMR_CODE = `
20
+ await app.writeTemp("internal/clientConfigs.js", content);
21
+ };
22
+ //#endregion
23
+ //#region src/page/inferPagePath.ts
24
+ /**
25
+ * Infer page path according to file path
26
+ *
27
+ * @internal
28
+ */
29
+ const inferPagePath = ({ app, filePathRelative, options }) => {
30
+ if (options.path) {
31
+ const pathLocale = resolveLocalePath(app.siteData.locales, options.path);
32
+ return {
33
+ pathInferred: filePathRelative ? inferRoutePath(ensureLeadingSlash(filePathRelative)) : null,
34
+ pathLocale
35
+ };
36
+ }
37
+ if (!filePathRelative) return {
38
+ pathInferred: null,
39
+ pathLocale: "/"
40
+ };
41
+ const pathInferred = inferRoutePath(ensureLeadingSlash(filePathRelative));
42
+ return {
43
+ pathInferred,
44
+ pathLocale: resolveLocalePath(app.siteData.locales, pathInferred)
45
+ };
46
+ };
47
+ //#endregion
48
+ //#region src/page/parsePageContent.ts
49
+ /**
50
+ * Render page content and extract related info
51
+ *
52
+ * @internal
53
+ */
54
+ const parsePageContent = ({ app, content, filePath, filePathRelative, options }) => {
55
+ const markdownEnv = {
56
+ base: app.options.base,
57
+ filePath,
58
+ filePathRelative,
59
+ frontmatter: { ...options.frontmatter }
60
+ };
61
+ const contentRendered = app.markdown.render(content, markdownEnv);
62
+ /* istanbul ignore next */
63
+ const { frontmatter = {}, headers = [], importedFiles = [], links = [], sfcBlocks = {
64
+ template: null,
65
+ script: null,
66
+ scriptSetup: null,
67
+ scripts: [],
68
+ styles: [],
69
+ customBlocks: []
70
+ }, title = "", ...extraMarkdownEnv } = markdownEnv;
71
+ return {
72
+ contentRendered,
73
+ deps: importedFiles,
74
+ frontmatter,
75
+ headers,
76
+ links,
77
+ markdownEnv: omit(extraMarkdownEnv, "base", "content", "filePath", "filePathRelative", "frontmatter"),
78
+ sfcBlocks,
79
+ title: frontmatter.title ? `${frontmatter.title}` : title
80
+ };
81
+ };
82
+ //#endregion
83
+ //#region src/page/resolvePageChunkInfo.ts
84
+ /**
85
+ * Resolve page chunk file related info
86
+ *
87
+ * @internal
88
+ */
89
+ const resolvePageChunkInfo = ({ app, filePath, filePathRelative, htmlFilePathRelative }) => {
90
+ const chunkName = transformPathToFileName(htmlFilePathRelative);
91
+ if (filePath && filePathRelative) return {
92
+ chunkFilePath: filePath,
93
+ chunkFilePathRelative: filePathRelative,
94
+ chunkName
95
+ };
96
+ const chunkFilePathRelative = path.join("pages", `${htmlFilePathRelative}.vue`);
97
+ return {
98
+ chunkFilePath: app.dir.temp(chunkFilePathRelative),
99
+ chunkFilePathRelative,
100
+ chunkName
101
+ };
102
+ };
103
+ //#endregion
104
+ //#region src/page/resolvePageContent.ts
105
+ const log$5 = debug("vuepress:core/page");
106
+ const FALLBACK_CONTENT = "";
107
+ /**
108
+ * Resolve page content according to `content` or `filePath`
109
+ *
110
+ * @internal
111
+ */
112
+ const resolvePageContent = async ({ filePath, options }) => {
113
+ if (isString(options.content)) return options.content;
114
+ if (filePath) try {
115
+ return await fs.readFile(filePath, "utf-8");
116
+ } catch (e) {
117
+ log$5(e instanceof Error ? e.message : e);
118
+ }
119
+ return FALLBACK_CONTENT;
120
+ };
121
+ //#endregion
122
+ //#region src/page/resolvePageDate.ts
123
+ const FILENAME_DATE_RE = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?-(.*)$/;
124
+ const DIRNAME_DATE_RE = /(\d{4})\/(\d{1,2})(?:\/(\d{1,2}))?(\/|$)/;
125
+ const DEFAULT_DATE = "0000-00-00";
126
+ /**
127
+ * Resolve page date according to frontmatter or file path
128
+ *
129
+ * It will be resolved as 'yyyy-MM-dd' format
130
+ *
131
+ * @internal
132
+ */
133
+ const resolvePageDate = ({ frontmatter, filePathRelative }) => {
134
+ if (frontmatter.date instanceof Date) return formatDateString([
135
+ frontmatter.date.getUTCFullYear(),
136
+ frontmatter.date.getUTCMonth() + 1,
137
+ frontmatter.date.getUTCDate()
138
+ ].join("-"), DEFAULT_DATE);
139
+ if (isString(frontmatter.date)) return formatDateString(frontmatter.date, DEFAULT_DATE);
140
+ if (filePathRelative === null) return DEFAULT_DATE;
141
+ const filename = path.parse(filePathRelative).name;
142
+ if (filename) {
143
+ const matches = filename.match(FILENAME_DATE_RE);
144
+ if (matches) return formatDateString(`${matches[1]}-${matches[2]}-${matches[3] ?? "01"}`, DEFAULT_DATE);
145
+ }
146
+ const dirname = path.dirname(filePathRelative);
147
+ if (dirname !== ".") {
148
+ const matches = dirname.match(DIRNAME_DATE_RE);
149
+ if (matches) return formatDateString(`${matches[1]}-${matches[2]}-${matches[3] ?? "01"}`, DEFAULT_DATE);
150
+ }
151
+ return DEFAULT_DATE;
152
+ };
153
+ //#endregion
154
+ //#region src/page/resolvePageFilePath.ts
155
+ /**
156
+ * Resolve absolute and relative path of page file
157
+ *
158
+ * @internal
159
+ */
160
+ const resolvePageFilePath = ({ app, options }) => {
161
+ if (!options.filePath) return {
162
+ filePath: null,
163
+ filePathRelative: null
164
+ };
165
+ if (!path.isAbsolute(options.filePath)) throw logger.createError(`filePath is not absolute file path: ${options.filePath}}`);
166
+ return {
167
+ filePath: options.filePath,
168
+ filePathRelative: path.relative(app.dir.source(), options.filePath)
169
+ };
170
+ };
171
+ //#endregion
172
+ //#region src/page/resolvePageHtmlInfo.ts
173
+ /**
174
+ * Resolve page rendered html file path
175
+ *
176
+ * @internal
177
+ */
178
+ const resolvePageHtmlInfo = ({ app, path: pagePath }) => {
179
+ const path = decodeURI(pagePath);
180
+ const htmlFilePathRelative = removeLeadingSlash(path.endsWith("/") ? `${path}index.html` : path.endsWith(".html") ? path : `${path}.html`);
181
+ return {
182
+ htmlFilePath: app.dir.dest(htmlFilePathRelative),
183
+ htmlFilePathRelative
184
+ };
185
+ };
186
+ //#endregion
187
+ //#region src/page/resolvePageLang.ts
188
+ /**
189
+ * Resolve language of page
190
+ *
191
+ * @internal
192
+ */
193
+ const resolvePageLang = ({ app, frontmatter, pathLocale }) => {
194
+ if (isString(frontmatter.lang) && frontmatter.lang) return frontmatter.lang;
195
+ return app.siteData.locales[pathLocale]?.lang ?? app.siteData.lang;
196
+ };
197
+ //#endregion
198
+ //#region src/page/resolvePagePath.ts
199
+ /**
200
+ * Resolve the final route path of a page
201
+ *
202
+ * @internal
203
+ */
204
+ const resolvePagePath = ({ permalink, pathInferred, options }) => {
205
+ const pagePath = options.path || permalink || pathInferred;
206
+ if (!pagePath) throw logger.createError(`page path is empty, page options: ${JSON.stringify(options, null, 2)}`);
207
+ return encodeURI(pagePath.split("/").map(sanitizeFileName).join("/"));
208
+ };
209
+ //#endregion
210
+ //#region src/page/resolvePagePermalink.ts
211
+ /**
212
+ * Resolve page permalink from frontmatter / options / pattern
213
+ *
214
+ * @internal
215
+ */
216
+ const resolvePagePermalink = ({ app, frontmatter, slug, date, pathInferred, pathLocale }) => {
217
+ if (frontmatter.permalink === null) return null;
218
+ if (isString(frontmatter.permalink)) return frontmatter.permalink;
219
+ if (frontmatter.permalinkPattern === null) return null;
220
+ const permalinkPattern = frontmatter.permalinkPattern || app.options.permalinkPattern;
221
+ if (!isString(permalinkPattern)) return null;
222
+ const [year, month, day] = date.split("-");
223
+ return ensureLeadingSlash(path.join(pathLocale, permalinkPattern.replace(/:year/, year).replace(/:month/, month).replace(/:day/, day).replace(/:slug/, slug).replace(/:raw/, pathInferred?.replace(/^\//, "") ?? "")));
224
+ };
225
+ //#endregion
226
+ //#region src/page/resolvePageRouteMeta.ts
227
+ /**
228
+ * Resolve page route meta
229
+ *
230
+ * @internal
231
+ */
232
+ const resolvePageRouteMeta = ({ frontmatter }) => frontmatter.routeMeta ?? {};
233
+ //#endregion
234
+ //#region src/page/resolvePageSlug.ts
235
+ const DATE_RE = /(\d{4}-\d{1,2}(-\d{1,2})?)-(.*)/;
236
+ /**
237
+ * Resolve page slug from filename
238
+ *
239
+ * @internal
240
+ */
241
+ const resolvePageSlug = ({ filePathRelative }) => {
242
+ if (!filePathRelative) return "";
243
+ const filename = path.parse(filePathRelative).name;
244
+ const match = filename.match(DATE_RE);
245
+ return match ? match[3] : filename;
246
+ };
247
+ //#endregion
248
+ //#region src/page/createPage.ts
249
+ /**
250
+ * Create vuepress page object
251
+ */
252
+ const createPage = async (app, options) => {
253
+ await app.pluginApi.hooks.extendsPageOptions.process(options, app);
254
+ const { filePath, filePathRelative } = resolvePageFilePath({
255
+ app,
256
+ options
257
+ });
258
+ const content = await resolvePageContent({
259
+ filePath,
260
+ options
261
+ });
262
+ const { contentRendered, deps, frontmatter, headers, links, markdownEnv, sfcBlocks, title } = parsePageContent({
263
+ app,
264
+ content,
265
+ filePath,
266
+ filePathRelative,
267
+ options
268
+ });
269
+ const routeMeta = resolvePageRouteMeta({ frontmatter });
270
+ const slug = resolvePageSlug({ filePathRelative });
271
+ const date = resolvePageDate({
272
+ frontmatter,
273
+ filePathRelative
274
+ });
275
+ const { pathInferred, pathLocale } = inferPagePath({
276
+ app,
277
+ filePathRelative,
278
+ options
279
+ });
280
+ const lang = resolvePageLang({
281
+ app,
282
+ frontmatter,
283
+ pathLocale
284
+ });
285
+ const permalink = resolvePagePermalink({
286
+ app,
287
+ frontmatter,
288
+ slug,
289
+ date,
290
+ pathInferred,
291
+ pathLocale
292
+ });
293
+ const path = resolvePagePath({
294
+ permalink,
295
+ pathInferred,
296
+ options
297
+ });
298
+ const { htmlFilePath, htmlFilePathRelative } = resolvePageHtmlInfo({
299
+ app,
300
+ path
301
+ });
302
+ const { chunkFilePath, chunkFilePathRelative, chunkName } = resolvePageChunkInfo({
303
+ app,
304
+ filePath,
305
+ filePathRelative,
306
+ htmlFilePathRelative
307
+ });
308
+ const page = {
309
+ data: {
310
+ path,
311
+ title,
312
+ lang,
313
+ frontmatter
314
+ },
315
+ path,
316
+ title,
317
+ lang,
318
+ frontmatter,
319
+ headers,
320
+ content,
321
+ contentRendered,
322
+ date,
323
+ deps,
324
+ links,
325
+ markdownEnv,
326
+ pathInferred,
327
+ pathLocale,
328
+ permalink,
329
+ routeMeta,
330
+ sfcBlocks,
331
+ slug,
332
+ filePath,
333
+ filePathRelative,
334
+ chunkFilePath,
335
+ chunkFilePathRelative,
336
+ chunkName,
337
+ htmlFilePath,
338
+ htmlFilePathRelative
339
+ };
340
+ await app.pluginApi.hooks.extendsPage.process(page, app);
341
+ return page;
342
+ };
343
+ //#endregion
344
+ //#region src/page/renderPageToVue.ts
345
+ const TEMPLATE_WRAPPER_TAG_OPEN = "<div>";
346
+ const TEMPLATE_WRAPPER_TAG_CLOSE = "</div>";
347
+ const SCRIPT_TAG_OPEN = "<script>";
348
+ const SCRIPT_TAG_CLOSE = "<\/script>";
349
+ const SCRIPT_TAG_OPEN_LANG_TS_REGEX = /<\s*script[^>]*\blang=['"]ts['"][^>]*/;
350
+ const SCRIPT_TAG_OPEN_LANG_TS = "<script lang=\"ts\">";
351
+ const SCRIPT_DEFAULT_EXPORT_REGEX = /((?:^|\n|;)\s*)export(\s*)default/;
352
+ const SCRIPT_DEFAULT_NAMED_EXPORT_REGEX = /((?:^|\n|;)\s*)export(.+)as(\s*)default/;
353
+ const SCRIPT_DEFAULT_EXPORT_CODE_TEMPLATE_OUTLET = "__SCRIPT_DEFAULT_EXPORT__";
354
+ const SCRIPT_DEFAULT_EXPORT_CODE_TEMPLATE = `export default { name: ${SCRIPT_DEFAULT_EXPORT_CODE_TEMPLATE_OUTLET} }`;
355
+ const PAGE_DATA_CODE_VAR_NAME = "_pageData";
356
+ const PAGE_DATA_CODE_TEMPLATE_OUTLET = "__PAGE_DATA__";
357
+ const PAGE_DATA_CODE_TEMPLATE = `export const ${PAGE_DATA_CODE_VAR_NAME} = JSON.parse(${PAGE_DATA_CODE_TEMPLATE_OUTLET})`;
358
+ const HMR_CODE$2 = `
17
359
  if (import.meta.webpackHot) {
18
360
  import.meta.webpackHot.accept()
19
- if (__VUE_HMR_RUNTIME__.updatePageData) {
20
- __VUE_HMR_RUNTIME__.updatePageData(data)
21
- }
361
+ __VUE_HMR_RUNTIME__.updatePageData?.(${PAGE_DATA_CODE_VAR_NAME})
22
362
  }
23
363
 
24
364
  if (import.meta.hot) {
25
- import.meta.hot.accept(({ data }) => {
26
- __VUE_HMR_RUNTIME__.updatePageData(data)
365
+ import.meta.hot.accept((m) => {
366
+ __VUE_HMR_RUNTIME__.updatePageData?.(m.${PAGE_DATA_CODE_VAR_NAME})
27
367
  })
28
368
  }
29
369
  `;
30
- var preparePageChunk = async (app, page) => {
31
- let content = `import comp from ${JSON.stringify(page.componentFilePath)}
32
- const data = JSON.parse(${JSON.stringify(JSON.stringify(page.data))})
33
- export { comp, data }
34
- `;
35
- if (app.env.isDev) {
36
- content += HMR_CODE;
37
- }
38
- await app.writeTemp(page.chunkFilePathRelative, content);
39
- };
40
-
41
- // src/page/inferPagePath.ts
42
- import {
43
- ensureLeadingSlash,
44
- inferRoutePath,
45
- resolveLocalePath
46
- } from "@vuepress/shared";
47
- var inferPagePath = ({
48
- app,
49
- filePathRelative
50
- }) => {
51
- if (!filePathRelative) {
52
- return {
53
- pathInferred: null,
54
- pathLocale: "/"
55
- };
56
- }
57
- const pathInferred = inferRoutePath(ensureLeadingSlash(filePathRelative));
58
- const pathLocale = resolveLocalePath(app.siteData.locales, pathInferred);
59
- return {
60
- pathInferred,
61
- pathLocale
62
- };
63
- };
64
-
65
- // src/page/parsePageContent.ts
66
- import { omit } from "@vuepress/shared";
67
- var parsePageContent = ({
68
- app,
69
- content,
70
- filePath,
71
- filePathRelative,
72
- options
73
- }) => {
74
- const markdownEnv = {
75
- base: app.options.base,
76
- filePath,
77
- filePathRelative,
78
- frontmatter: { ...options.frontmatter }
79
- };
80
- const contentRendered = app.markdown.render(content, markdownEnv);
81
- const {
82
- frontmatter = {},
83
- headers = [],
84
- importedFiles = [],
85
- links = [],
86
- sfcBlocks = {
87
- template: null,
88
- script: null,
89
- scriptSetup: null,
90
- scripts: [],
91
- styles: [],
92
- customBlocks: []
93
- },
94
- title = "",
95
- ...extraMarkdownEnv
96
- } = markdownEnv;
97
- return {
98
- contentRendered,
99
- deps: importedFiles,
100
- frontmatter,
101
- headers,
102
- links,
103
- markdownEnv: omit(
104
- extraMarkdownEnv,
105
- "base",
106
- "content",
107
- "filePath",
108
- "filePathRelative",
109
- "frontmatter"
110
- ),
111
- sfcBlocks,
112
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-template-expression -- the title from frontmatter is not guaranteed to be a string
113
- title: frontmatter.title ? `${frontmatter.title}` : title
114
- };
115
- };
116
-
117
- // src/page/resolvePageChunkInfo.ts
118
- import { path, transformPathToFileName } from "@vuepress/utils";
119
- var resolvePageChunkInfo = ({
120
- app,
121
- htmlFilePathRelative
122
- }) => {
123
- const chunkFilePathRelative = path.join("pages", `${htmlFilePathRelative}.js`);
124
- const chunkFilePath = app.dir.temp(chunkFilePathRelative);
125
- const chunkName = transformPathToFileName(htmlFilePathRelative);
126
- return {
127
- chunkFilePath,
128
- chunkFilePathRelative,
129
- chunkName
130
- };
131
- };
132
-
133
- // src/page/resolvePageComponentInfo.ts
134
- import { path as path2 } from "@vuepress/utils";
135
- var resolvePageComponentInfo = ({
136
- app,
137
- htmlFilePathRelative
138
- }) => {
139
- const componentFilePathRelative = path2.join(
140
- "pages",
141
- `${htmlFilePathRelative}.vue`
142
- );
143
- const componentFilePath = app.dir.temp(componentFilePathRelative);
144
- return {
145
- componentFilePath,
146
- componentFilePathRelative
147
- };
148
- };
149
-
150
- // src/page/resolvePageContent.ts
151
- import { isString } from "@vuepress/shared";
152
- import { debug, fs } from "@vuepress/utils";
153
- var log = debug("vuepress:core/page");
154
- var FALLBACK_CONTENT = "";
155
- var resolvePageContent = async ({
156
- filePath,
157
- options
158
- }) => {
159
- if (isString(options.content)) {
160
- return options.content;
161
- }
162
- if (filePath) {
163
- try {
164
- const content = await fs.readFile(filePath, "utf-8");
165
- return content;
166
- } catch (e) {
167
- log(e instanceof Error ? e.message : e);
168
- }
169
- }
170
- return FALLBACK_CONTENT;
171
- };
172
-
173
- // src/page/resolvePageDate.ts
174
- import { formatDateString, isString as isString2 } from "@vuepress/shared";
175
- import { path as path3 } from "@vuepress/utils";
176
- var FILENAME_DATE_RE = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?-(.*)$/;
177
- var DIRNAME_DATE_RE = /(\d{4})\/(\d{1,2})(?:\/(\d{1,2}))?(\/|$)/;
178
- var DEFAULT_DATE = "0000-00-00";
179
- var resolvePageDate = ({
180
- frontmatter,
181
- filePathRelative
182
- }) => {
183
- if (frontmatter.date instanceof Date) {
184
- return formatDateString(
185
- [
186
- frontmatter.date.getUTCFullYear(),
187
- frontmatter.date.getUTCMonth() + 1,
188
- frontmatter.date.getUTCDate()
189
- ].join("-"),
190
- DEFAULT_DATE
191
- );
192
- }
193
- if (isString2(frontmatter.date)) {
194
- return formatDateString(frontmatter.date, DEFAULT_DATE);
195
- }
196
- if (filePathRelative === null) {
197
- return DEFAULT_DATE;
198
- }
199
- const filename = path3.parse(filePathRelative).name;
200
- if (filename) {
201
- const matches = filename.match(FILENAME_DATE_RE);
202
- if (matches) {
203
- return formatDateString(
204
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- unsafe indexed access
205
- `${matches[1]}-${matches[2]}-${matches[3] ?? "01"}`,
206
- DEFAULT_DATE
207
- );
208
- }
209
- }
210
- const dirname = path3.dirname(filePathRelative);
211
- if (dirname !== ".") {
212
- const matches = dirname.match(DIRNAME_DATE_RE);
213
- if (matches) {
214
- return formatDateString(
215
- // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition -- unsafe indexed access
216
- `${matches[1]}-${matches[2]}-${matches[3] ?? "01"}`,
217
- DEFAULT_DATE
218
- );
219
- }
220
- }
221
- return DEFAULT_DATE;
222
- };
223
-
224
- // src/page/resolvePageFilePath.ts
225
- import { logger, path as path4 } from "@vuepress/utils";
226
- var resolvePageFilePath = ({
227
- app,
228
- options
229
- }) => {
230
- if (!options.filePath) {
231
- return {
232
- filePath: null,
233
- filePathRelative: null
234
- };
235
- }
236
- if (!path4.isAbsolute(options.filePath)) {
237
- throw logger.createError(
238
- `filePath is not absolute file path: ${options.filePath}}`
239
- );
240
- }
241
- return {
242
- filePath: options.filePath,
243
- filePathRelative: path4.relative(app.dir.source(), options.filePath)
244
- };
245
- };
246
-
247
- // src/page/resolvePageHtmlInfo.ts
248
- import { removeLeadingSlash } from "@vuepress/shared";
249
- var resolvePageHtmlInfo = ({
250
- app,
251
- path: pagePath
252
- }) => {
253
- const path9 = decodeURI(pagePath);
254
- const htmlFilePathRelative = removeLeadingSlash(
255
- path9.endsWith("/") ? `${path9}index.html` : path9.endsWith(".html") ? path9 : `${path9}.html`
256
- );
257
- const htmlFilePath = app.dir.dest(htmlFilePathRelative);
258
- return {
259
- htmlFilePath,
260
- htmlFilePathRelative
261
- };
262
- };
263
-
264
- // src/page/resolvePageLang.ts
265
- import { isString as isString3 } from "@vuepress/shared";
266
- var resolvePageLang = ({
267
- app,
268
- frontmatter,
269
- pathLocale
270
- }) => {
271
- if (isString3(frontmatter.lang) && frontmatter.lang) {
272
- return frontmatter.lang;
273
- }
274
- return app.siteData.locales[pathLocale]?.lang ?? app.siteData.lang;
275
- };
276
-
277
- // src/page/resolvePagePath.ts
278
- import { logger as logger2, sanitizeFileName } from "@vuepress/utils";
279
- var resolvePagePath = ({
280
- permalink,
281
- pathInferred,
282
- options
283
- }) => {
284
- const pagePath = options.path || permalink || pathInferred;
285
- if (!pagePath) {
286
- throw logger2.createError(
287
- `page path is empty, page options: ${JSON.stringify(options, null, 2)}`
288
- );
289
- }
290
- return encodeURI(pagePath.split("/").map(sanitizeFileName).join("/"));
291
- };
292
-
293
- // src/page/resolvePagePermalink.ts
294
- import { ensureLeadingSlash as ensureLeadingSlash2, isString as isString4 } from "@vuepress/shared";
295
- import { path as path5 } from "@vuepress/utils";
296
- var resolvePagePermalink = ({
297
- app,
298
- frontmatter,
299
- slug,
300
- date,
301
- pathInferred,
302
- pathLocale
303
- }) => {
304
- if (frontmatter.permalink === null) {
305
- return null;
306
- }
307
- if (isString4(frontmatter.permalink)) {
308
- return frontmatter.permalink;
309
- }
310
- if (frontmatter.permalinkPattern === null) {
311
- return null;
312
- }
313
- const permalinkPattern = frontmatter.permalinkPattern || app.options.permalinkPattern;
314
- if (!isString4(permalinkPattern)) {
315
- return null;
316
- }
317
- const [year, month, day] = date.split("-");
318
- const link = path5.join(
319
- pathLocale,
320
- permalinkPattern.replace(/:year/, year).replace(/:month/, month).replace(/:day/, day).replace(/:slug/, slug).replace(/:raw/, pathInferred?.replace(/^\//, "") ?? "")
321
- );
322
- return ensureLeadingSlash2(link);
323
- };
324
-
325
- // src/page/resolvePageRouteMeta.ts
326
- var resolvePageRouteMeta = ({
327
- frontmatter
328
- }) => frontmatter.routeMeta ?? {};
329
-
330
- // src/page/resolvePageSlug.ts
331
- import { path as path6 } from "@vuepress/utils";
332
- var DATE_RE = /(\d{4}-\d{1,2}(-\d{1,2})?)-(.*)/;
333
- var resolvePageSlug = ({
334
- filePathRelative
335
- }) => {
336
- if (!filePathRelative) {
337
- return "";
338
- }
339
- const filename = path6.parse(filePathRelative).name;
340
- const match = filename.match(DATE_RE);
341
- return match ? match[3] : filename;
342
- };
343
-
344
- // src/page/createPage.ts
345
- var createPage = async (app, options) => {
346
- await app.pluginApi.hooks.extendsPageOptions.process(options, app);
347
- const { filePath, filePathRelative } = resolvePageFilePath({
348
- app,
349
- options
350
- });
351
- const content = await resolvePageContent({ filePath, options });
352
- const {
353
- contentRendered,
354
- deps,
355
- frontmatter,
356
- headers,
357
- links,
358
- markdownEnv,
359
- sfcBlocks,
360
- title
361
- } = parsePageContent({
362
- app,
363
- content,
364
- filePath,
365
- filePathRelative,
366
- options
367
- });
368
- const routeMeta = resolvePageRouteMeta({ frontmatter });
369
- const slug = resolvePageSlug({ filePathRelative });
370
- const date = resolvePageDate({ frontmatter, filePathRelative });
371
- const { pathInferred, pathLocale } = inferPagePath({ app, filePathRelative });
372
- const lang = resolvePageLang({ app, frontmatter, pathLocale });
373
- const permalink = resolvePagePermalink({
374
- app,
375
- frontmatter,
376
- slug,
377
- date,
378
- pathInferred,
379
- pathLocale
380
- });
381
- const path9 = resolvePagePath({ permalink, pathInferred, options });
382
- const { htmlFilePath, htmlFilePathRelative } = resolvePageHtmlInfo({
383
- app,
384
- path: path9
385
- });
386
- const { componentFilePath, componentFilePathRelative } = resolvePageComponentInfo({
387
- app,
388
- htmlFilePathRelative
389
- });
390
- const { chunkFilePath, chunkFilePathRelative, chunkName } = resolvePageChunkInfo({ app, htmlFilePathRelative });
391
- const page = {
392
- // page data
393
- data: {
394
- path: path9,
395
- title,
396
- lang,
397
- frontmatter
398
- },
399
- // base fields
400
- path: path9,
401
- title,
402
- lang,
403
- frontmatter,
404
- headers,
405
- // extra fields
406
- content,
407
- contentRendered,
408
- date,
409
- deps,
410
- links,
411
- markdownEnv,
412
- pathInferred,
413
- pathLocale,
414
- permalink,
415
- routeMeta,
416
- sfcBlocks,
417
- slug,
418
- // file info
419
- filePath,
420
- filePathRelative,
421
- componentFilePath,
422
- componentFilePathRelative,
423
- chunkFilePath,
424
- chunkFilePathRelative,
425
- chunkName,
426
- htmlFilePath,
427
- htmlFilePathRelative
428
- };
429
- await app.pluginApi.hooks.extendsPage.process(page, app);
430
- return page;
431
- };
432
-
433
- // src/page/renderPageSfcBlocksToVue.ts
434
- var renderPageSfcBlocksToVue = (sfcBlocks) => [
435
- // #688: wrap the content of `<template>` with a `<div>` to avoid some potential issues of fragment component
436
- `${sfcBlocks.template?.tagOpen}<div>${sfcBlocks.template?.contentStripped}</div>${sfcBlocks.template?.tagClose}
437
- `,
438
- // hoist `<script>`, `<style>` and other custom blocks
439
- sfcBlocks.script?.content,
440
- sfcBlocks.scriptSetup?.content,
441
- ...sfcBlocks.styles.map((item) => item.content),
442
- ...sfcBlocks.customBlocks.map((item) => item.content)
443
- ].join("\n");
444
-
445
- // src/app/prepare/preparePageComponent.ts
446
- var preparePageComponent = async (app, page) => {
447
- await app.writeTemp(
448
- page.componentFilePathRelative,
449
- renderPageSfcBlocksToVue(page.sfcBlocks)
450
- );
451
- };
452
-
453
- // src/app/prepare/prepareRoutes.ts
454
- import { normalizeRoutePath } from "@vuepress/shared";
455
- var HMR_CODE2 = `
370
+ /**
371
+ * Util to resolve the open tag of script block
372
+ */
373
+ const resolveScriptTagOpen = (page) => {
374
+ if (page.sfcBlocks.script?.tagOpen) return page.sfcBlocks.script.tagOpen;
375
+ return page.sfcBlocks.scriptSetup?.tagOpen.match(SCRIPT_TAG_OPEN_LANG_TS_REGEX) ? SCRIPT_TAG_OPEN_LANG_TS : SCRIPT_TAG_OPEN;
376
+ };
377
+ /**
378
+ * Util to resolve the default export code
379
+ */
380
+ const resolveDefaultExportCode = (page) => SCRIPT_DEFAULT_EXPORT_CODE_TEMPLATE.replace(SCRIPT_DEFAULT_EXPORT_CODE_TEMPLATE_OUTLET, JSON.stringify(path.basename(page.chunkFilePath)));
381
+ /**
382
+ * Util to resolve the page data code
383
+ */
384
+ const resolvePageDataCode = (page) => PAGE_DATA_CODE_TEMPLATE.replace(PAGE_DATA_CODE_TEMPLATE_OUTLET, JSON.stringify(JSON.stringify(page.data)));
385
+ /**
386
+ * Resolve the stripped content of script block
387
+ */
388
+ const resolveScriptContentStripped = (app, page) => {
389
+ const rawContentStripped = page.sfcBlocks.script?.contentStripped;
390
+ const hasDefaultExport = rawContentStripped ? SCRIPT_DEFAULT_EXPORT_REGEX.test(rawContentStripped) || SCRIPT_DEFAULT_NAMED_EXPORT_REGEX.test(rawContentStripped) : false;
391
+ return [
392
+ rawContentStripped,
393
+ resolvePageDataCode(page),
394
+ !hasDefaultExport && resolveDefaultExportCode(page),
395
+ app.env.isDev && HMR_CODE$2
396
+ ].filter(isString).join("\n");
397
+ };
398
+ /**
399
+ * Render page to vue component
400
+ */
401
+ const renderPageToVue = (app, page) => {
402
+ const { sfcBlocks } = page;
403
+ return [
404
+ sfcBlocks.template && [
405
+ sfcBlocks.template.tagOpen,
406
+ TEMPLATE_WRAPPER_TAG_OPEN,
407
+ sfcBlocks.template.contentStripped,
408
+ TEMPLATE_WRAPPER_TAG_CLOSE,
409
+ sfcBlocks.template.tagClose
410
+ ].join(""),
411
+ [
412
+ resolveScriptTagOpen(page),
413
+ resolveScriptContentStripped(app, page),
414
+ sfcBlocks.script?.tagClose ?? SCRIPT_TAG_CLOSE
415
+ ].filter(isString).join("\n"),
416
+ sfcBlocks.scriptSetup?.content,
417
+ ...sfcBlocks.styles.map((item) => item.content),
418
+ ...sfcBlocks.customBlocks.map((item) => item.content)
419
+ ].filter(isString).join("\n");
420
+ };
421
+ //#endregion
422
+ //#region src/app/prepare/preparePageChunk.ts
423
+ /**
424
+ * Generate temp file if the page does not have a source file
425
+ */
426
+ const preparePageChunk = async (app, page) => {
427
+ if (page.filePath === null) await app.writeTemp(page.chunkFilePathRelative, renderPageToVue(app, page));
428
+ };
429
+ //#endregion
430
+ //#region src/app/prepare/prepareRoutes.ts
431
+ const ROUTES_VAR_NAME = "routes";
432
+ const REDIRECTS_VAR_NAME = "redirects";
433
+ const HMR_CODE$1 = `
456
434
  if (import.meta.webpackHot) {
457
435
  import.meta.webpackHot.accept()
458
- if (__VUE_HMR_RUNTIME__.updateRoutes) {
459
- __VUE_HMR_RUNTIME__.updateRoutes(routes)
460
- }
461
- if (__VUE_HMR_RUNTIME__.updateRedirects) {
462
- __VUE_HMR_RUNTIME__.updateRedirects(redirects)
463
- }
436
+ __VUE_HMR_RUNTIME__.updateRoutes?.(${ROUTES_VAR_NAME})
437
+ __VUE_HMR_RUNTIME__.updateRedirects?.(${REDIRECTS_VAR_NAME})
464
438
  }
465
439
 
466
440
  if (import.meta.hot) {
467
- import.meta.hot.accept(({ routes, redirects }) => {
468
- __VUE_HMR_RUNTIME__.updateRoutes(routes)
469
- __VUE_HMR_RUNTIME__.updateRedirects(redirects)
441
+ import.meta.hot.accept((m) => {
442
+ __VUE_HMR_RUNTIME__.updateRoutes?.(m.${ROUTES_VAR_NAME})
443
+ __VUE_HMR_RUNTIME__.updateRedirects?.(m.${REDIRECTS_VAR_NAME})
470
444
  })
471
445
  }
472
446
  `;
473
- var resolvePageRedirects = ({ path: path9, pathInferred }) => {
474
- const redirectsSet = /* @__PURE__ */ new Set();
475
- if (pathInferred !== null) {
476
- const normalizedPathInferred = normalizeRoutePath(pathInferred);
477
- const encodedPathInferred = encodeURI(normalizedPathInferred);
478
- if (normalizedPathInferred !== path9 && encodedPathInferred !== path9) {
479
- redirectsSet.add(encodedPathInferred);
480
- }
481
- }
482
- return Array.from(redirectsSet);
483
- };
484
- var prepareRoutes = async (app) => {
485
- let content = `export const redirects = JSON.parse(${JSON.stringify(
486
- JSON.stringify(
487
- Object.fromEntries(
488
- app.pages.flatMap(
489
- (page) => resolvePageRedirects(page).map((redirect) => [redirect, page.path])
490
- )
491
- )
492
- )
493
- )})
494
-
495
- export const routes = Object.fromEntries([
496
- ${app.pages.map(
497
- ({ chunkFilePath, chunkName, path: path9, routeMeta }) => ` [${JSON.stringify(path9)}, { loader: () => import(${chunkName ? `/* webpackChunkName: "${chunkName}" */` : ""}${JSON.stringify(chunkFilePath)}), meta: ${JSON.stringify(routeMeta)} }],`
498
- ).join("\n")}
447
+ /**
448
+ * Resolve page redirects
449
+ *
450
+ * @internal
451
+ */
452
+ const resolvePageRedirects = ({ path, pathInferred }) => {
453
+ const redirectsSet = /* @__PURE__ */ new Set();
454
+ if (pathInferred !== null) {
455
+ const normalizedPathInferred = normalizeRoutePath(pathInferred);
456
+ const encodedPathInferred = encodeURI(normalizedPathInferred);
457
+ if (normalizedPathInferred !== path && encodedPathInferred !== path) redirectsSet.add(encodedPathInferred);
458
+ }
459
+ return Array.from(redirectsSet);
460
+ };
461
+ /**
462
+ * Generate routes temp file
463
+ */
464
+ const prepareRoutes = async (app) => {
465
+ let content = `\
466
+ export const ${REDIRECTS_VAR_NAME} = JSON.parse(${JSON.stringify(JSON.stringify(Object.fromEntries(app.pages.flatMap((page) => resolvePageRedirects(page).map((redirect) => [redirect, page.path])))))})
467
+
468
+ export const ${ROUTES_VAR_NAME} = Object.fromEntries([
469
+ ${app.pages.map(({ chunkFilePath, chunkName, path, routeMeta }) => ` [${JSON.stringify(path)}, { loader: () => import(${chunkName ? `/* webpackChunkName: "${chunkName}" */` : ""}${JSON.stringify(chunkFilePath)}), meta: ${JSON.stringify(routeMeta)} }],`).join("\n")}
499
470
  ]);
500
471
  `;
501
- if (app.env.isDev) {
502
- content += HMR_CODE2;
503
- }
504
- await app.writeTemp("internal/routes.js", content);
472
+ if (app.env.isDev) content += HMR_CODE$1;
473
+ await app.writeTemp("internal/routes.js", content);
505
474
  };
506
-
507
- // src/app/prepare/prepareSiteData.ts
508
- var HMR_CODE3 = `
475
+ //#endregion
476
+ //#region src/app/prepare/prepareSiteData.ts
477
+ const SITE_DATA_VAR_NAME = "siteData";
478
+ const HMR_CODE = `
509
479
  if (import.meta.webpackHot) {
510
480
  import.meta.webpackHot.accept()
511
- if (__VUE_HMR_RUNTIME__.updateSiteData) {
512
- __VUE_HMR_RUNTIME__.updateSiteData(siteData)
513
- }
481
+ __VUE_HMR_RUNTIME__.updateSiteData?.(${SITE_DATA_VAR_NAME})
514
482
  }
515
483
 
516
484
  if (import.meta.hot) {
517
- import.meta.hot.accept(({ siteData }) => {
518
- __VUE_HMR_RUNTIME__.updateSiteData(siteData)
485
+ import.meta.hot.accept((m) => {
486
+ __VUE_HMR_RUNTIME__.updateSiteData?.(m.${SITE_DATA_VAR_NAME})
519
487
  })
520
488
  }
521
489
  `;
522
- var prepareSiteData = async (app) => {
523
- let content = `export const siteData = JSON.parse(${JSON.stringify(
524
- JSON.stringify(app.siteData)
525
- )})
490
+ /**
491
+ * Generate site data temp file
492
+ *
493
+ * @internal
494
+ */
495
+ const prepareSiteData = async (app) => {
496
+ let content = `\
497
+ export const ${SITE_DATA_VAR_NAME} = JSON.parse(${JSON.stringify(JSON.stringify(app.siteData))})
526
498
  `;
527
- if (app.env.isDev) {
528
- content += HMR_CODE3;
529
- }
530
- await app.writeTemp("internal/siteData.js", content);
531
- };
532
-
533
- // src/app/appInit.ts
534
- import { debug as debug3 } from "@vuepress/utils";
535
-
536
- // src/app/resolveAppMarkdown.ts
537
- import { createMarkdown } from "@vuepress/markdown";
538
- var resolveAppMarkdown = async (app) => {
539
- await app.pluginApi.hooks.extendsMarkdownOptions.process(
540
- app.options.markdown,
541
- app
542
- );
543
- const markdown = createMarkdown(app.options.markdown);
544
- await app.pluginApi.hooks.extendsMarkdown.process(markdown, app);
545
- return markdown;
546
- };
547
-
548
- // src/app/resolveAppPages.ts
549
- import { debug as debug2, tinyglobby } from "@vuepress/utils";
550
- var log2 = debug2("vuepress:core/app");
551
- var resolveAppPages = async (app) => {
552
- log2("resolveAppPages start");
553
- const pageFilePaths = await tinyglobby.glob(app.options.pagePatterns, {
554
- absolute: true,
555
- cwd: app.dir.source()
556
- });
557
- let hasNotFoundPage = false;
558
- const pages = await Promise.all(
559
- pageFilePaths.map(async (filePath) => {
560
- const page = await createPage(app, { filePath });
561
- if (page.path === "/404.html") {
562
- page.frontmatter.layout ??= "NotFound";
563
- hasNotFoundPage = true;
564
- }
565
- return page;
566
- })
567
- );
568
- if (!hasNotFoundPage) {
569
- pages.push(
570
- await createPage(app, {
571
- path: "/404.html",
572
- frontmatter: { layout: "NotFound" },
573
- content: "404 Not Found"
574
- })
575
- );
576
- }
577
- log2("resolveAppPages finish");
578
- return pages;
579
- };
580
-
581
- // src/app/appInit.ts
582
- var log3 = debug3("vuepress:core/app");
583
- var appInit = async (app) => {
584
- log3("init start");
585
- app.pluginApi.registerHooks();
586
- app.markdown = await resolveAppMarkdown(app);
587
- app.pages = await resolveAppPages(app);
588
- await app.pluginApi.hooks.onInitialized.process(app);
589
- log3("init finish");
590
- };
591
-
592
- // src/app/appPrepare.ts
593
- import { debug as debug4 } from "@vuepress/utils";
594
- var log4 = debug4("vuepress:core/app");
595
- var appPrepare = async (app) => {
596
- log4("prepare start");
597
- await Promise.all([
598
- ...app.pages.flatMap((page) => [
599
- preparePageComponent(app, page),
600
- preparePageChunk(app, page)
601
- ]),
602
- prepareRoutes(app),
603
- prepareSiteData(app),
604
- prepareClientConfigs(app)
605
- ]);
606
- await app.pluginApi.hooks.onPrepared.process(app);
607
- log4("prepare finish");
608
- };
609
-
610
- // src/app/appUse.ts
611
- import { colors, debug as debug5, warn } from "@vuepress/utils";
612
-
613
- // src/app/resolvePluginObject.ts
614
- import { isFunction } from "@vuepress/shared";
615
- var resolvePluginObject = (app, plugin) => isFunction(plugin) ? plugin(app) : plugin;
616
-
617
- // src/app/appUse.ts
618
- var log5 = debug5("vuepress:core/app");
619
- var appUse = (app, rawPlugin) => {
620
- const pluginObject = resolvePluginObject(app, rawPlugin);
621
- if (!pluginObject.name) {
622
- warn(`an anonymous plugin or theme was detected and ignored`);
623
- return app;
624
- }
625
- log5(`use plugin ${colors.magenta(pluginObject.name)}`);
626
- if (pluginObject.multiple !== true) {
627
- const duplicateIndex = app.pluginApi.plugins.findIndex(
628
- ({ name }) => name === pluginObject.name
629
- );
630
- if (duplicateIndex !== -1) {
631
- app.pluginApi.plugins.splice(duplicateIndex, 1);
632
- warn(
633
- `plugin ${colors.magenta(
634
- pluginObject.name
635
- )} has been used multiple times, only the last one will take effect`
636
- );
637
- }
638
- }
639
- app.pluginApi.plugins.push(pluginObject);
640
- return app;
641
- };
642
-
643
- // src/pluginApi/createHookQueue.ts
644
- import { colors as colors2, debug as debug6, logger as logger3 } from "@vuepress/utils";
645
- var log6 = debug6("vuepress:core/plugin-api");
646
- var createHookQueue = (name) => {
647
- const items = [];
648
- const hookQueue = {
649
- name,
650
- items,
651
- add: (item) => {
652
- items.push(item);
653
- },
654
- process: async (...args) => {
655
- const results = [];
656
- for (const item of items) {
657
- log6(
658
- `process ${colors2.magenta(name)} from ${colors2.magenta(
659
- item.pluginName
660
- )}`
661
- );
662
- try {
663
- const result = await item.hook(...args);
664
- if (result !== void 0) {
665
- results.push(result);
666
- }
667
- } catch (e) {
668
- logger3.error(
669
- `error in hook ${colors2.magenta(name)} from ${colors2.magenta(
670
- item.pluginName
671
- )}`
672
- );
673
- throw e;
674
- }
675
- }
676
- return results;
677
- }
678
- };
679
- return hookQueue;
680
- };
681
-
682
- // src/pluginApi/createPluginApiHooks.ts
683
- var createPluginApiHooks = () => ({
684
- // life cycle hooks
685
- onInitialized: createHookQueue("onInitialized"),
686
- onPrepared: createHookQueue("onPrepared"),
687
- onWatched: createHookQueue("onWatched"),
688
- onGenerated: createHookQueue("onGenerated"),
689
- // extends hooks
690
- extendsMarkdownOptions: createHookQueue("extendsMarkdownOptions"),
691
- extendsMarkdown: createHookQueue("extendsMarkdown"),
692
- extendsPageOptions: createHookQueue("extendsPageOptions"),
693
- extendsPage: createHookQueue("extendsPage"),
694
- extendsBundlerOptions: createHookQueue("extendsBundlerOptions"),
695
- // client config file hooks
696
- clientConfigFile: createHookQueue("clientConfigFile"),
697
- // bundler hooks
698
- alias: createHookQueue("alias"),
699
- define: createHookQueue("define")
499
+ if (app.env.isDev) content += HMR_CODE;
500
+ await app.writeTemp("internal/siteData.js", content);
501
+ };
502
+ //#endregion
503
+ //#region src/app/resolveAppMarkdown.ts
504
+ /**
505
+ * Resolve markdown-it instance for vuepress app
506
+ *
507
+ * @internal
508
+ */
509
+ const resolveAppMarkdown = async (app) => {
510
+ await app.pluginApi.hooks.extendsMarkdownOptions.process(app.options.markdown, app);
511
+ const markdown = createMarkdown(app.options.markdown);
512
+ await app.pluginApi.hooks.extendsMarkdown.process(markdown, app);
513
+ return markdown;
514
+ };
515
+ //#endregion
516
+ //#region src/constants.ts
517
+ const DEFAULT_IGNORE_PATTERNS = [
518
+ "**/node_modules",
519
+ "**/.yarn",
520
+ "**/.git",
521
+ "**/.svn",
522
+ "**/.hg"
523
+ ];
524
+ //#endregion
525
+ //#region src/app/resolveAppPages.ts
526
+ const log$4 = debug("vuepress:core/app");
527
+ /**
528
+ * Resolve pages for vuepress app
529
+ *
530
+ * @internal
531
+ */
532
+ const resolveAppPages = async (app) => {
533
+ log$4("resolveAppPages start");
534
+ const pageFilePaths = await tinyglobby.glob(app.options.pagePatterns, {
535
+ absolute: true,
536
+ cwd: app.dir.source(),
537
+ ignore: DEFAULT_IGNORE_PATTERNS
538
+ });
539
+ let hasNotFoundPage = false;
540
+ const pagesMap = {};
541
+ const pages = await Promise.all(pageFilePaths.map(async (filePath) => {
542
+ const page = await createPage(app, { filePath });
543
+ if (page.filePath) pagesMap[page.filePath] = page;
544
+ if (page.path === "/404.html") {
545
+ page.frontmatter.layout ??= "NotFound";
546
+ hasNotFoundPage = true;
547
+ }
548
+ return page;
549
+ }));
550
+ if (!hasNotFoundPage) pages.push(await createPage(app, {
551
+ path: "/404.html",
552
+ frontmatter: { layout: "NotFound" },
553
+ content: "404 Not Found"
554
+ }));
555
+ log$4("resolveAppPages finish");
556
+ return {
557
+ pages,
558
+ pagesMap
559
+ };
560
+ };
561
+ //#endregion
562
+ //#region src/app/appInit.ts
563
+ const log$3 = debug("vuepress:core/app");
564
+ /**
565
+ * Initialize a vuepress app
566
+ *
567
+ * Plugins should be used before initialization.
568
+ *
569
+ * @internal
570
+ */
571
+ const appInit = async (app) => {
572
+ log$3("init start");
573
+ app.pluginApi.registerHooks();
574
+ app.markdown = await resolveAppMarkdown(app);
575
+ const { pages, pagesMap } = await resolveAppPages(app);
576
+ app.pages = pages;
577
+ app.pagesMap = pagesMap;
578
+ await app.pluginApi.hooks.onInitialized.process(app);
579
+ log$3("init finish");
580
+ };
581
+ //#endregion
582
+ //#region src/app/appPrepare.ts
583
+ const log$2 = debug("vuepress:core/app");
584
+ /**
585
+ * Prepare files for development or build
586
+ *
587
+ * - page chunks
588
+ * - routes
589
+ * - site data
590
+ * - other files that generated by plugins
591
+ *
592
+ * @internal
593
+ */
594
+ const appPrepare = async (app) => {
595
+ log$2("prepare start");
596
+ await Promise.all([
597
+ ...app.pages.map(async (page) => preparePageChunk(app, page)),
598
+ prepareRoutes(app),
599
+ prepareSiteData(app),
600
+ prepareClientConfigs(app)
601
+ ]);
602
+ await app.pluginApi.hooks.onPrepared.process(app);
603
+ log$2("prepare finish");
604
+ };
605
+ //#endregion
606
+ //#region src/app/resolvePluginObject.ts
607
+ /**
608
+ * Resolve a plugin object according to name / path / module and config
609
+ *
610
+ * @internal
611
+ */
612
+ const resolvePluginObject = (app, plugin) => isFunction(plugin) ? plugin(app) : plugin;
613
+ //#endregion
614
+ //#region src/app/appUse.ts
615
+ const log$1 = debug("vuepress:core/app");
616
+ /**
617
+ * Use a plugin in vuepress app.
618
+ *
619
+ * Should be called before initialization.
620
+ *
621
+ * @internal
622
+ */
623
+ const appUse = (app, rawPlugin) => {
624
+ const pluginObject = resolvePluginObject(app, rawPlugin);
625
+ if (!pluginObject.name) {
626
+ warn(`an anonymous plugin or theme was detected and ignored`);
627
+ return app;
628
+ }
629
+ log$1(`use plugin ${colors.magenta(pluginObject.name)}`);
630
+ if (pluginObject.multiple !== true) {
631
+ const duplicateIndex = app.pluginApi.plugins.findIndex(({ name }) => name === pluginObject.name);
632
+ if (duplicateIndex !== -1) {
633
+ app.pluginApi.plugins.splice(duplicateIndex, 1);
634
+ warn(`plugin ${colors.magenta(pluginObject.name)} has been used multiple times, only the last one will take effect`);
635
+ }
636
+ }
637
+ app.pluginApi.plugins.push(pluginObject);
638
+ return app;
639
+ };
640
+ //#endregion
641
+ //#region src/pluginApi/createHookQueue.ts
642
+ const log = debug("vuepress:core/plugin-api");
643
+ /**
644
+ * Create hook queue for plugin system
645
+ *
646
+ * @internal
647
+ */
648
+ const createHookQueue = (name) => {
649
+ const items = [];
650
+ return {
651
+ name,
652
+ items,
653
+ add: (item) => {
654
+ items.push(item);
655
+ },
656
+ process: async (...args) => {
657
+ const results = [];
658
+ for (const item of items) {
659
+ log(`process ${colors.magenta(name)} from ${colors.magenta(item.pluginName)}`);
660
+ try {
661
+ const result = await item.hook(...args);
662
+ if (result !== void 0) results.push(result);
663
+ } catch (e) {
664
+ logger.error(`error in hook ${colors.magenta(name)} from ${colors.magenta(item.pluginName)}`);
665
+ throw e;
666
+ }
667
+ }
668
+ return results;
669
+ }
670
+ };
671
+ };
672
+ //#endregion
673
+ //#region src/pluginApi/createPluginApiHooks.ts
674
+ /**
675
+ * Create hooks for plugin api
676
+ *
677
+ * @internal
678
+ */
679
+ const createPluginApiHooks = () => ({
680
+ onInitialized: createHookQueue("onInitialized"),
681
+ onPrepared: createHookQueue("onPrepared"),
682
+ onWatched: createHookQueue("onWatched"),
683
+ onPageUpdated: createHookQueue("onPageUpdated"),
684
+ onGenerated: createHookQueue("onGenerated"),
685
+ extendsMarkdownOptions: createHookQueue("extendsMarkdownOptions"),
686
+ extendsMarkdown: createHookQueue("extendsMarkdown"),
687
+ extendsPageOptions: createHookQueue("extendsPageOptions"),
688
+ extendsPage: createHookQueue("extendsPage"),
689
+ extendsBundlerOptions: createHookQueue("extendsBundlerOptions"),
690
+ clientConfigFile: createHookQueue("clientConfigFile"),
691
+ alias: createHookQueue("alias"),
692
+ define: createHookQueue("define")
700
693
  });
701
-
702
- // src/pluginApi/normalizeAliasDefineHook.ts
703
- import { isFunction as isFunction2 } from "@vuepress/shared";
704
- var normalizeAliasDefineHook = (hook) => async (app, isServer) => isFunction2(hook) ? hook(app, isServer) : hook;
705
-
706
- // src/pluginApi/normalizeClientConfigFileHook.ts
707
- import { isFunction as isFunction3 } from "@vuepress/shared";
708
- import { fs as fs2, logger as logger4 } from "@vuepress/utils";
709
- var normalizeClientConfigFileHook = (hook) => async (app) => {
710
- const clientConfigFileResult = isFunction3(hook) ? await hook(app) : hook;
711
- const isExisted = await fs2.pathExists(clientConfigFileResult);
712
- if (!isExisted) {
713
- throw logger4.createError(
714
- `client config file does not exist: ${clientConfigFileResult}`
715
- );
716
- }
717
- return clientConfigFileResult;
718
- };
719
-
720
- // src/pluginApi/createPluginApiRegisterHooks.ts
721
- var createPluginApiRegisterHooks = (plugins, hooks) => () => {
722
- plugins.forEach(
723
- ({
724
- name: pluginName,
725
- multiple,
726
- alias,
727
- define,
728
- clientConfigFile,
729
- ...commonHooks
730
- }) => {
731
- if (alias) {
732
- hooks.alias.add({
733
- pluginName,
734
- hook: normalizeAliasDefineHook(alias)
735
- });
736
- }
737
- if (define) {
738
- hooks.define.add({
739
- pluginName,
740
- hook: normalizeAliasDefineHook(define)
741
- });
742
- }
743
- if (clientConfigFile) {
744
- hooks.clientConfigFile.add({
745
- pluginName,
746
- hook: normalizeClientConfigFileHook(clientConfigFile)
747
- });
748
- }
749
- Object.keys(commonHooks).forEach((key) => {
750
- if (hooks[key] && commonHooks[key]) {
751
- hooks[key].add({
752
- pluginName,
753
- // @ts-expect-error: the type could not be narrowed correctly
754
- hook: commonHooks[key]
755
- });
756
- }
757
- });
758
- }
759
- );
760
- };
761
-
762
- // src/pluginApi/createPluginApi.ts
763
- var createPluginApi = () => {
764
- const plugins = [];
765
- const hooks = createPluginApiHooks();
766
- const registerHooks = createPluginApiRegisterHooks(plugins, hooks);
767
- return {
768
- plugins,
769
- hooks,
770
- registerHooks
771
- };
772
- };
773
-
774
- // src/app/resolveAppDir.ts
775
- import { createRequire } from "module";
776
- import { path as path7 } from "@vuepress/utils";
777
- var require2 = createRequire(import.meta.url);
778
- var createAppDirFunction = (baseDir) => (...args) => path7.resolve(baseDir, ...args);
779
- var resolveAppDir = (options) => {
780
- const cache = createAppDirFunction(options.cache);
781
- const temp = createAppDirFunction(options.temp);
782
- const source = createAppDirFunction(options.source);
783
- const dest = createAppDirFunction(options.dest);
784
- const publicDir = createAppDirFunction(options.public);
785
- const client = createAppDirFunction(
786
- path7.resolve(require2.resolve("@vuepress/client/package.json"), "..")
787
- );
788
- return {
789
- cache,
790
- temp,
791
- source,
792
- dest,
793
- client,
794
- public: publicDir
795
- };
796
- };
797
-
798
- // src/app/resolveAppEnv.ts
799
- var resolveAppEnv = (options) => ({
800
- isBuild: false,
801
- isDev: false,
802
- isDebug: options.debug
803
- });
804
-
805
- // src/app/resolveAppOptions.ts
806
- import { createRequire as createRequire2 } from "module";
807
- import { path as path8, templateRenderer } from "@vuepress/utils";
808
- var require3 = createRequire2(import.meta.url);
809
- var resolveAppOptions = ({
810
- // site config
811
- base = "/",
812
- lang = "en-US",
813
- title = "",
814
- description = "",
815
- head = [],
816
- locales = {},
817
- // directory config
818
- source,
819
- dest = path8.resolve(source, ".vuepress/dist"),
820
- temp = path8.resolve(source, ".vuepress/.temp"),
821
- cache = path8.resolve(source, ".vuepress/.cache"),
822
- public: publicDir = path8.resolve(source, ".vuepress/public"),
823
- // dev config
824
- host = "0.0.0.0",
825
- port = 8080,
826
- open = false,
827
- templateDev = path8.normalize(
828
- require3.resolve("@vuepress/client/templates/dev.html")
829
- ),
830
- // build config
831
- shouldPreload = true,
832
- shouldPrefetch = true,
833
- templateBuild = path8.normalize(
834
- require3.resolve("@vuepress/client/templates/build.html")
835
- ),
836
- templateBuildRenderer = templateRenderer,
837
- // common config
838
- bundler,
839
- debug: debug7 = false,
840
- markdown = {},
841
- pagePatterns = ["**/*.md", "!.vuepress", "!node_modules"],
842
- permalinkPattern = null,
843
- plugins = [],
844
- theme
845
- }) => ({
846
- base,
847
- lang,
848
- title,
849
- description,
850
- head,
851
- locales,
852
- source,
853
- dest,
854
- temp,
855
- cache,
856
- public: publicDir,
857
- host,
858
- port,
859
- open,
860
- templateDev,
861
- shouldPreload,
862
- shouldPrefetch,
863
- templateBuild,
864
- templateBuildRenderer,
865
- bundler,
866
- debug: debug7,
867
- markdown,
868
- pagePatterns,
869
- permalinkPattern,
870
- plugins,
871
- theme
694
+ //#endregion
695
+ //#region src/pluginApi/normalizeAliasDefineHook.ts
696
+ /**
697
+ * Normalize alias and define hook
698
+ *
699
+ * @internal
700
+ */
701
+ const normalizeAliasDefineHook = (hook) => async (app, isServer) => isFunction(hook) ? hook(app, isServer) : hook;
702
+ //#endregion
703
+ //#region src/pluginApi/normalizeClientConfigFileHook.ts
704
+ /**
705
+ * Normalize hook for client config file
706
+ *
707
+ * @internal
708
+ */
709
+ const normalizeClientConfigFileHook = (hook) => async (app) => {
710
+ const clientConfigFileResult = isFunction(hook) ? await hook(app) : hook;
711
+ if (!await fs.pathExists(clientConfigFileResult)) throw logger.createError(`client config file does not exist: ${clientConfigFileResult}`);
712
+ return clientConfigFileResult;
713
+ };
714
+ //#endregion
715
+ //#region src/pluginApi/createPluginApiRegisterHooks.ts
716
+ /**
717
+ * Create registerHooks method for plugin api
718
+ *
719
+ * @internal
720
+ */
721
+ const createPluginApiRegisterHooks = (plugins, hooks) => () => {
722
+ plugins.forEach(({ name: pluginName, multiple, alias, define, clientConfigFile, ...commonHooks }) => {
723
+ /**
724
+ * hooks that need to be normalized
725
+ */
726
+ if (alias) hooks.alias.add({
727
+ pluginName,
728
+ hook: normalizeAliasDefineHook(alias)
729
+ });
730
+ if (define) hooks.define.add({
731
+ pluginName,
732
+ hook: normalizeAliasDefineHook(define)
733
+ });
734
+ if (clientConfigFile) hooks.clientConfigFile.add({
735
+ pluginName,
736
+ hook: normalizeClientConfigFileHook(clientConfigFile)
737
+ });
738
+ /**
739
+ * common hooks
740
+ */
741
+ Object.keys(commonHooks).forEach((key) => {
742
+ if (hooks[key] && commonHooks[key]) hooks[key].add({
743
+ pluginName,
744
+ hook: commonHooks[key]
745
+ });
746
+ });
747
+ });
748
+ };
749
+ //#endregion
750
+ //#region src/pluginApi/createPluginApi.ts
751
+ /**
752
+ * Create vuepress plugin api
753
+ *
754
+ * @internal
755
+ */
756
+ const createPluginApi = () => {
757
+ const plugins = [];
758
+ const hooks = createPluginApiHooks();
759
+ return {
760
+ plugins,
761
+ hooks,
762
+ registerHooks: createPluginApiRegisterHooks(plugins, hooks)
763
+ };
764
+ };
765
+ //#endregion
766
+ //#region src/app/resolveAppDir.ts
767
+ const require$2 = createRequire(import.meta.url);
768
+ /**
769
+ * Create directory util function
770
+ *
771
+ * @internal
772
+ */
773
+ const createAppDirFunction = (baseDir) => (...args) => path.resolve(baseDir, ...args);
774
+ /**
775
+ * Resolve directory utils for vuepress app
776
+ */
777
+ const resolveAppDir = (options) => {
778
+ const cache = createAppDirFunction(options.cache);
779
+ const temp = createAppDirFunction(options.temp);
780
+ const source = createAppDirFunction(options.source);
781
+ const dest = createAppDirFunction(options.dest);
782
+ const publicDir = createAppDirFunction(options.public);
783
+ return {
784
+ cache,
785
+ temp,
786
+ source,
787
+ dest,
788
+ client: createAppDirFunction(path.resolve(require$2.resolve("@vuepress/client/package.json"), "..")),
789
+ public: publicDir
790
+ };
791
+ };
792
+ //#endregion
793
+ //#region src/app/resolveAppEnv.ts
794
+ /**
795
+ * Resolve environment flags for vuepress app
796
+ *
797
+ * @internal
798
+ */
799
+ const resolveAppEnv = (options) => ({
800
+ isBuild: false,
801
+ isDev: false,
802
+ isDebug: options.debug
872
803
  });
873
-
874
- // src/app/resolveAppSiteData.ts
875
- var resolveAppSiteData = (options) => ({
876
- base: options.base,
877
- lang: options.lang,
878
- title: options.title,
879
- description: options.description,
880
- head: options.head,
881
- locales: options.locales
804
+ //#endregion
805
+ //#region src/app/resolveAppOptions.ts
806
+ const require$1 = createRequire(import.meta.url);
807
+ /**
808
+ * Create app options with default values
809
+ *
810
+ * @internal
811
+ */
812
+ const resolveAppOptions = ({ base = "/", lang = "en-US", title = "", description = "", head = [], locales = {}, source, dest = path.resolve(source, ".vuepress/dist"), temp = path.resolve(source, ".vuepress/.temp"), cache = path.resolve(source, ".vuepress/.cache"), public: publicDir = path.resolve(source, ".vuepress/public"), host = "0.0.0.0", port = 8080, open = false, templateDev = path.normalize(require$1.resolve("@vuepress/client/templates/dev.html")), shouldPreload = true, shouldPrefetch = true, templateBuild = path.normalize(require$1.resolve("@vuepress/client/templates/build.html")), templateBuildRenderer = templateRenderer, bundler, debug = false, markdown = {}, pagePatterns = ["**/*.md", "!.vuepress"], permalinkPattern = null, plugins = [], theme }) => {
813
+ locales["/"] ??= {
814
+ lang,
815
+ title,
816
+ description
817
+ };
818
+ return {
819
+ base,
820
+ lang,
821
+ title,
822
+ description,
823
+ head,
824
+ locales,
825
+ source,
826
+ dest,
827
+ temp,
828
+ cache,
829
+ public: publicDir,
830
+ host,
831
+ port,
832
+ open,
833
+ templateDev,
834
+ shouldPreload,
835
+ shouldPrefetch,
836
+ templateBuild,
837
+ templateBuildRenderer,
838
+ bundler,
839
+ debug,
840
+ markdown,
841
+ pagePatterns,
842
+ permalinkPattern,
843
+ plugins,
844
+ theme
845
+ };
846
+ };
847
+ //#endregion
848
+ //#region src/app/resolveAppSiteData.ts
849
+ /**
850
+ * Resolve site data for vuepress app
851
+ *
852
+ * Site data will also be used in client
853
+ *
854
+ * @internal
855
+ */
856
+ const resolveAppSiteData = (options) => ({
857
+ base: options.base,
858
+ lang: options.lang,
859
+ title: options.title,
860
+ description: options.description,
861
+ head: options.head,
862
+ locales: options.locales
882
863
  });
883
-
884
- // src/app/resolveAppVersion.ts
885
- import { createRequire as createRequire3 } from "module";
886
- import { fs as fs3 } from "@vuepress/utils";
887
- var require4 = createRequire3(import.meta.url);
888
- var resolveAppVersion = () => {
889
- const pkgJson = fs3.readJsonSync(
890
- require4.resolve("@vuepress/core/package.json")
891
- );
892
- return pkgJson.version;
893
- };
894
-
895
- // src/app/resolveAppWriteTemp.ts
896
- import { fs as fs4 } from "@vuepress/utils";
897
- var resolveAppWriteTemp = (dir) => {
898
- const writeTemp = async (file, content) => {
899
- const filePath = dir.temp(file);
900
- await fs4.outputFile(filePath, content);
901
- return filePath;
902
- };
903
- return writeTemp;
904
- };
905
-
906
- // src/app/createBaseApp.ts
907
- var createBaseApp = (config) => {
908
- const options = resolveAppOptions(config);
909
- const dir = resolveAppDir(options);
910
- const env = resolveAppEnv(options);
911
- const pluginApi = createPluginApi();
912
- const siteData = resolveAppSiteData(options);
913
- const version = resolveAppVersion();
914
- const writeTemp = resolveAppWriteTemp(dir);
915
- const app = {
916
- options,
917
- siteData,
918
- version,
919
- // utils
920
- dir,
921
- env,
922
- pluginApi,
923
- writeTemp,
924
- // methods
925
- use: (plugin) => appUse(app, plugin),
926
- init: async () => appInit(app),
927
- prepare: async () => appPrepare(app)
928
- };
929
- return app;
930
- };
931
-
932
- // src/app/resolveThemeInfo.ts
933
- var resolveThemeInfo = (app, theme) => {
934
- const themeObject = resolvePluginObject(app, theme);
935
- const themeInfo = {
936
- plugins: [...themeObject.plugins ?? [], themeObject],
937
- templateBuild: themeObject.templateBuild,
938
- templateBuildRenderer: themeObject.templateBuildRenderer,
939
- templateDev: themeObject.templateDev
940
- };
941
- if (!themeObject.extends) {
942
- return themeInfo;
943
- }
944
- const parentThemeInfo = resolveThemeInfo(app, themeObject.extends);
945
- return {
946
- plugins: [...parentThemeInfo.plugins, ...themeInfo.plugins],
947
- templateBuild: themeObject.templateBuild ?? parentThemeInfo.templateBuild,
948
- templateBuildRenderer: themeObject.templateBuildRenderer ?? parentThemeInfo.templateBuildRenderer,
949
- templateDev: themeObject.templateDev ?? parentThemeInfo.templateDev
950
- };
951
- };
952
-
953
- // src/app/setupAppThemeAndPlugins.ts
954
- var setupAppThemeAndPlugins = (app, config) => {
955
- const themeInfo = resolveThemeInfo(app, app.options.theme);
956
- app.options.templateDev = config.templateDev ?? themeInfo.templateDev ?? app.options.templateDev;
957
- app.options.templateBuild = config.templateBuild ?? themeInfo.templateBuild ?? app.options.templateBuild;
958
- app.options.templateBuildRenderer = config.templateBuildRenderer ?? themeInfo.templateBuildRenderer ?? app.options.templateBuildRenderer;
959
- [...themeInfo.plugins, ...app.options.plugins].flat().forEach((plugin) => app.use(plugin));
960
- };
961
-
962
- // src/app/createBuildApp.ts
963
- var createBuildApp = (config) => {
964
- const app = createBaseApp(config);
965
- app.env.isBuild = true;
966
- app.build = async () => app.options.bundler.build(app);
967
- setupAppThemeAndPlugins(app, config);
968
- return app;
969
- };
970
-
971
- // src/app/createDevApp.ts
972
- var createDevApp = (config) => {
973
- const app = createBaseApp(config);
974
- app.env.isDev = true;
975
- app.dev = async () => app.options.bundler.dev(app);
976
- setupAppThemeAndPlugins(app, config);
977
- return app;
978
- };
979
- export {
980
- appInit,
981
- appPrepare,
982
- appUse,
983
- createAppDirFunction,
984
- createBaseApp,
985
- createBuildApp,
986
- createDevApp,
987
- createHookQueue,
988
- createPage,
989
- createPluginApi,
990
- createPluginApiHooks,
991
- createPluginApiRegisterHooks,
992
- inferPagePath,
993
- normalizeAliasDefineHook,
994
- normalizeClientConfigFileHook,
995
- parsePageContent,
996
- prepareClientConfigs,
997
- preparePageChunk,
998
- preparePageComponent,
999
- prepareRoutes,
1000
- prepareSiteData,
1001
- renderPageSfcBlocksToVue,
1002
- resolveAppDir,
1003
- resolveAppEnv,
1004
- resolveAppOptions,
1005
- resolveAppPages,
1006
- resolveAppSiteData,
1007
- resolveAppVersion,
1008
- resolveAppWriteTemp,
1009
- resolvePageChunkInfo,
1010
- resolvePageComponentInfo,
1011
- resolvePageContent,
1012
- resolvePageDate,
1013
- resolvePageFilePath,
1014
- resolvePageHtmlInfo,
1015
- resolvePageLang,
1016
- resolvePagePath,
1017
- resolvePagePermalink,
1018
- resolvePageRouteMeta,
1019
- resolvePageSlug,
1020
- resolvePluginObject,
1021
- resolveThemeInfo
1022
- };
864
+ //#endregion
865
+ //#region src/app/resolveAppVersion.ts
866
+ const require = createRequire(import.meta.url);
867
+ /**
868
+ * Resolve version of vuepress app
869
+ *
870
+ * @internal
871
+ */
872
+ const resolveAppVersion = () => {
873
+ return fs.readJsonSync(require.resolve("@vuepress/core/package.json")).version;
874
+ };
875
+ //#endregion
876
+ //#region src/app/resolveAppWriteTemp.ts
877
+ /**
878
+ * Resolve write temp file util for vuepress app
879
+ *
880
+ * @internal
881
+ */
882
+ const resolveAppWriteTemp = (dir) => {
883
+ const cache = /* @__PURE__ */ new Map();
884
+ const writeTemp = (async (file, content) => {
885
+ const filePath = dir.temp(file);
886
+ const contentHash = hash(content);
887
+ let item = cache.get(filePath);
888
+ if (!item) cache.set(filePath, item = {});
889
+ if (item.hash === contentHash) return filePath;
890
+ item.hash = contentHash;
891
+ if (!item.current) item.current = (async () => {
892
+ await fs.outputFile(filePath, content);
893
+ item.current = item.next?.();
894
+ return item.current;
895
+ })();
896
+ else item.next = async () => {
897
+ await fs.outputFile(filePath, content);
898
+ item.next = void 0;
899
+ item.current = void 0;
900
+ };
901
+ await item.current;
902
+ return filePath;
903
+ });
904
+ writeTemp.cleanup = () => {
905
+ cache.clear();
906
+ };
907
+ return writeTemp;
908
+ };
909
+ //#endregion
910
+ //#region src/app/createBaseApp.ts
911
+ /**
912
+ * Create base vuepress app.
913
+ *
914
+ * Notice that the base app could not be used for dev nor build.
915
+ *
916
+ * It would be used for creating dev app or build app internally.
917
+ *
918
+ * @internal
919
+ */
920
+ const createBaseApp = (config) => {
921
+ const options = resolveAppOptions(config);
922
+ const dir = resolveAppDir(options);
923
+ const env = resolveAppEnv(options);
924
+ const pluginApi = createPluginApi();
925
+ const app = {
926
+ options,
927
+ siteData: resolveAppSiteData(options),
928
+ version: resolveAppVersion(),
929
+ dir,
930
+ env,
931
+ pluginApi,
932
+ writeTemp: resolveAppWriteTemp(dir),
933
+ use: (plugin) => appUse(app, plugin),
934
+ init: async () => appInit(app),
935
+ prepare: async () => appPrepare(app)
936
+ };
937
+ return app;
938
+ };
939
+ //#endregion
940
+ //#region src/app/resolveThemeInfo.ts
941
+ /**
942
+ * Resolve theme info and its parent theme info
943
+ *
944
+ * @internal
945
+ */
946
+ const resolveThemeInfo = (app, theme) => {
947
+ const themeObject = resolvePluginObject(app, theme);
948
+ const themeInfo = {
949
+ plugins: [...themeObject.plugins ?? [], themeObject],
950
+ templateBuild: themeObject.templateBuild,
951
+ templateBuildRenderer: themeObject.templateBuildRenderer,
952
+ templateDev: themeObject.templateDev
953
+ };
954
+ if (!themeObject.extends) return themeInfo;
955
+ const parentThemeInfo = resolveThemeInfo(app, themeObject.extends);
956
+ return {
957
+ plugins: [...parentThemeInfo.plugins, ...themeInfo.plugins],
958
+ templateBuild: themeObject.templateBuild ?? parentThemeInfo.templateBuild,
959
+ templateBuildRenderer: themeObject.templateBuildRenderer ?? parentThemeInfo.templateBuildRenderer,
960
+ templateDev: themeObject.templateDev ?? parentThemeInfo.templateDev
961
+ };
962
+ };
963
+ //#endregion
964
+ //#region src/app/setupAppThemeAndPlugins.ts
965
+ /**
966
+ * Setup theme and plugins for vuepress app
967
+ *
968
+ * @internal
969
+ */
970
+ const setupAppThemeAndPlugins = (app, config) => {
971
+ const themeInfo = resolveThemeInfo(app, app.options.theme);
972
+ app.options.templateDev = config.templateDev ?? themeInfo.templateDev ?? app.options.templateDev;
973
+ app.options.templateBuild = config.templateBuild ?? themeInfo.templateBuild ?? app.options.templateBuild;
974
+ app.options.templateBuildRenderer = config.templateBuildRenderer ?? themeInfo.templateBuildRenderer ?? app.options.templateBuildRenderer;
975
+ [...themeInfo.plugins, ...app.options.plugins].flat().forEach((plugin) => app.use(plugin));
976
+ };
977
+ //#endregion
978
+ //#region src/app/createBuildApp.ts
979
+ /**
980
+ * Create vuepress build app.
981
+ */
982
+ const createBuildApp = (config) => {
983
+ const app = createBaseApp(config);
984
+ app.env.isBuild = true;
985
+ app.build = async () => app.options.bundler.build(app);
986
+ setupAppThemeAndPlugins(app, config);
987
+ return app;
988
+ };
989
+ //#endregion
990
+ //#region src/app/createDevApp.ts
991
+ /**
992
+ * Create vuepress dev app.
993
+ */
994
+ const createDevApp = (config) => {
995
+ const app = createBaseApp(config);
996
+ app.env.isDev = true;
997
+ app.dev = async () => app.options.bundler.dev(app);
998
+ setupAppThemeAndPlugins(app, config);
999
+ return app;
1000
+ };
1001
+ //#endregion
1002
+ export { DEFAULT_IGNORE_PATTERNS, appInit, appPrepare, appUse, createAppDirFunction, createBaseApp, createBuildApp, createDevApp, createHookQueue, createPage, createPluginApi, createPluginApiHooks, createPluginApiRegisterHooks, inferPagePath, normalizeAliasDefineHook, normalizeClientConfigFileHook, parsePageContent, prepareClientConfigs, preparePageChunk, prepareRoutes, prepareSiteData, renderPageToVue, resolveAppDir, resolveAppEnv, resolveAppOptions, resolveAppPages, resolveAppSiteData, resolveAppVersion, resolveAppWriteTemp, resolvePageChunkInfo, resolvePageContent, resolvePageDate, resolvePageFilePath, resolvePageHtmlInfo, resolvePageLang, resolvePagePath, resolvePagePermalink, resolvePageRouteMeta, resolvePageSlug, resolvePluginObject, resolveThemeInfo };