Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@
"@docsearch/js": "^4.5.3",
"@docsearch/sidepanel-js": "^4.5.3",
"@iconify-json/simple-icons": "^1.2.69",
"@noble/hashes": "^2.0.1",
"@shikijs/core": "^3.22.0",
"@shikijs/transformers": "^3.22.0",
"@shikijs/types": "^3.22.0",
Expand Down
51 changes: 37 additions & 14 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 5 additions & 2 deletions src/client/app/composables/preFetch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,11 @@ export function usePrefetch() {
const { pathname } = link
if (!hasFetched.has(pathname)) {
hasFetched.add(pathname)
const pageChunkPath = pathToFile(pathname)
if (pageChunkPath) doFetch(pageChunkPath)
try {
doFetch(pathToFile(pathname))
} catch (e) {
// Silently fail prefetch errors.
}
}
}
})
Expand Down
29 changes: 12 additions & 17 deletions src/client/app/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,22 +121,18 @@ function newRouter(): Router {
let isInitialPageLoad = inBrowser

return createRouter((path) => {
let pageFilePath = pathToFile(path)
let pageModule = null

if (pageFilePath) {
try {
// use lean build if this is the initial page load
if (isInitialPageLoad) {
pageFilePath = pageFilePath.replace(/\.js$/, '.lean.js')
}

const chunkPath = pathToFile(path, isInitialPageLoad ? '.lean.js' : '.js')
// Client build always use lean build
if (inBrowser) isInitialPageLoad = false
if (import.meta.env.DEV) {
pageModule = import(/*@vite-ignore*/ pageFilePath).catch((e) => {
return import(/*@vite-ignore*/ chunkPath).catch((e) => {
// page load could fail for other reasons, don't swallow
console.error(e)
// try with/without trailing slash
// in prod this is handled in src/client/app/utils.ts#pathToFile
const url = new URL(pageFilePath!, 'http://a.com')
const url = new URL(chunkPath!, 'http://a.com')
const path =
(url.pathname.endsWith('/index.md')
? url.pathname.slice(0, -9) + '.md'
Expand All @@ -146,15 +142,14 @@ function newRouter(): Router {
return import(/*@vite-ignore*/ path)
})
} else {
pageModule = import(/*@vite-ignore*/ pageFilePath)
return import(/*@vite-ignore*/ chunkPath)
}
} catch (e) {
// let 404 page load failure fall through
if (!/\/404(\.md|\.html|\/)?$/i.test(path))
console.error(`Failed to load page module for ${path}:`, e)
return null
}

if (inBrowser) {
isInitialPageLoad = false
}

return pageModule
}, Theme.NotFound)
}

Expand Down
54 changes: 15 additions & 39 deletions src/client/app/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import { h, onMounted, shallowRef, type AsyncComponentLoader } from 'vue'
import {
EXTERNAL_URL_RE,
inBrowser,
sanitizeFileName,
type Awaitable
type Awaitable,
resolveChunkKeys
} from '../shared'
import { siteDataRef } from './data'

Expand All @@ -26,46 +26,22 @@ export function withBase(path: string) {
: joinPath(siteDataRef.value.base, path)
}

/**
* Converts a url path to the corresponding js chunk filename.
*/
export function pathToFile(path: string) {
let pagePath = path.replace(/\.html$/, '')
pagePath = decodeURIComponent(pagePath)
pagePath = pagePath.replace(/\/$/, '/index') // /foo/ -> /foo/index
if (import.meta.env.DEV) {
// always force re-fetch content in dev
pagePath += `.md?t=${Date.now()}`
} else {
// in production, each .md file is built into a .md.js file following
// the path conversion scheme.
// /foo/bar.html -> ./foo_bar.md
if (inBrowser) {
const base = import.meta.env.BASE_URL
pagePath =
sanitizeFileName(
pagePath.slice(base.length).replace(/\//g, '_') || 'index'
) + '.md'
// client production build needs to account for page hash, which is
// injected directly in the page's html
let pageHash = __VP_HASH_MAP__[pagePath.toLowerCase()]
if (!pageHash) {
pagePath = pagePath.endsWith('_index.md')
? pagePath.slice(0, -9) + '.md'
: pagePath.slice(0, -3) + '_index.md'
pageHash = __VP_HASH_MAP__[pagePath.toLowerCase()]
}
if (!pageHash) return null
pagePath = `${base}${__ASSETS_DIR__}/${pagePath}.${pageHash}.js`
export function pathToFile(path: string, suffix: string = '.js') {
if (inBrowser) {
if (import.meta.env.DEV) {
// In dev server, always force re-fetch content
path = path.replace(/\/$/, '/index').replace(/\.html$/i, '')
return `${path}.md?t=${Date.now()}`
} else {
// ssr build uses much simpler name mapping
pagePath = `./${sanitizeFileName(
pagePath.slice(1).replace(/\//g, '_')
)}.md.js`
// in production, each .md file is built into [assetKey].[hash].js
const base = import.meta.env.BASE_URL
const { assetKey, hash } = resolveChunkKeys(path.slice(base.length), true)
return `${base}${__ASSETS_DIR__}/${assetKey}.${hash}${suffix}`
}
} else {
const { assetKey } = resolveChunkKeys(path, true)
return `./${assetKey}${suffix}`
}

return pagePath
}

export let contentUpdatedCallbacks: (() => any)[] = []
Expand Down
19 changes: 9 additions & 10 deletions src/node/build/build.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ export async function build(
}

try {
const { clientResult, serverResult, pageToHashMap } = await bundle(
const { clientResult, serverResult, hashmap } = await bundle(
siteConfig,
buildOptions
)
Expand All @@ -75,6 +75,9 @@ export async function build(
return
}

// Expose the hash map for SSR `resolveChunkKeys()` to lookup chunk file
;(globalThis as any).__VP_HASH_MAP__ = hashmap

const entryPath = path.join(siteConfig.tempDir, 'app.js')
const { render } = await import(pathToFileURL(entryPath).href)

Expand Down Expand Up @@ -113,7 +116,7 @@ export async function build(
chunk.moduleIds.some((id) => id.includes('client/theme-default'))
)

const metadataScript = generateMetadataScript(pageToHashMap, siteConfig)
const metadataScript = generateMetadataScript(hashmap, siteConfig)

if (isDefaultTheme) {
const fontURL = assets.find((file) =>
Expand Down Expand Up @@ -146,7 +149,7 @@ export async function build(
appChunk,
cssChunk,
assets,
pageToHashMap,
hashmap,
metadataScript,
additionalHeadTags,
usedIcons
Expand All @@ -169,10 +172,7 @@ export async function build(

// emit page hash map for the case where a user session is open
// when the site got redeployed (which invalidates current hash map)
fs.writeJSONSync(
path.join(siteConfig.outDir, 'hashmap.json'),
pageToHashMap
)
fs.writeJSONSync(path.join(siteConfig.outDir, 'hashmap.json'), hashmap)
} finally {
unlinkVue()
if (!process.env.DEBUG) {
Expand Down Expand Up @@ -210,7 +210,7 @@ function linkVue() {
}

function generateMetadataScript(
pageToHashMap: Record<string, string>,
hashmap: Record<string, string>,
config: SiteConfig
) {
if (config.mpa) {
Expand All @@ -221,7 +221,7 @@ function generateMetadataScript(
// so that it doesn't alter the main chunk's hash on every build.
// It's also embedded as a string and JSON.parsed from the client because
// it's faster than embedding as JS object literal.
const hashMapString = JSON.stringify(JSON.stringify(pageToHashMap))
const hashMapString = JSON.stringify(JSON.stringify(hashmap))
const siteDataString = JSON.stringify(
JSON.stringify(serializeFunctions({ ...config.site, head: [] }))
)
Expand All @@ -235,7 +235,6 @@ function generateMetadataScript(
if (!config.metaChunk) {
return { html: `<script>${metadataContent}</script>`, inHead: false }
}

const metadataFile = path.join(
config.assetsDir,
'chunks',
Expand Down
Loading