Skip to content

Commit

Permalink
perf: optimize debug logs (#371)
Browse files Browse the repository at this point in the history
  • Loading branch information
pengzhanbo authored Dec 6, 2024
1 parent 54c460e commit e7ba562
Show file tree
Hide file tree
Showing 19 changed files with 78 additions and 83 deletions.
10 changes: 5 additions & 5 deletions cli/src/prompt.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { Bundler, Langs, Options, PromptResult } from './types.js'
import type { Bundler, Langs, PromptResult } from './types.js'
import { createRequire } from 'node:module'
import process from 'node:process'
import { cancel, confirm, group, select, text } from '@clack/prompts'
Expand All @@ -20,7 +20,7 @@ export async function prompt(mode: Mode, root?: string): Promise<PromptResult> {

const result: PromptResult = await group({
displayLang: async () => {
const lang = await select<Options<Langs>, Langs>({
const lang = await select<Langs>({
message: 'Select a language to display / 选择显示语言',
options: languageOptions,
})
Expand Down Expand Up @@ -68,7 +68,7 @@ export async function prompt(mode: Mode, root?: string): Promise<PromptResult> {
initialValue: false,
}),

defaultLanguage: () => select<Options<Langs>, Langs>({
defaultLanguage: () => select<Langs>({
message: t('question.defaultLanguage'),
options: languageOptions,
}),
Expand All @@ -93,7 +93,7 @@ export async function prompt(mode: Mode, root?: string): Promise<PromptResult> {
})
},

bundler: () => select<Options<Bundler>, Bundler>({
bundler: () => select<Bundler>({
message: t('question.bundler'),
options: bundlerOptions,
}),
Expand All @@ -102,7 +102,7 @@ export async function prompt(mode: Mode, root?: string): Promise<PromptResult> {
if (mode === Mode.init) {
return DeployType.custom
}
return await select<Options<DeployType>, DeployType>({
return await select<DeployType>({
message: t('question.deploy'),
options: deployOptions,
initialValue: DeployType.custom,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import type {
} from '../types.js'
import {
getLocalePaths,
getRootLangPath,
inferRootLocalePath,
isPlainObject,
} from '@vuepress/helper'
import { ensureLeadingSlash, resolveLocalePath } from 'vuepress/shared'
Expand All @@ -18,7 +18,7 @@ export function createCopyCodeButtonRender(app: App, options?: boolean | CopyCod
const { className = 'copy', locales: userLocales = {} }
= isPlainObject(options) ? options : {}

const root = getRootLangPath(app)
const root = inferRootLocalePath(app)
const locales: LocaleConfig<CopyCodeLocaleOptions> = {
// fallback locale
'/': userLocales['/'] || copyCodeButtonLocales[root],
Expand Down
8 changes: 3 additions & 5 deletions theme/src/node/autoFrontmatter/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import grayMatter from 'gray-matter'
import jsonToYaml from 'json2yaml'
import { fs, hash, path } from 'vuepress/utils'
import { getThemeConfig } from '../loadConfig/index.js'
import { logger } from '../utils/index.js'
import { perfLog, perfMark } from '../utils/index.js'
import { readMarkdown, readMarkdownList } from './readFile.js'
import { resolveOptions } from './resolveOptions.js'

Expand Down Expand Up @@ -88,7 +88,7 @@ export function initAutoFrontmatter(
}

export async function generateAutoFrontmatter(app: App) {
const start = performance.now()
perfMark('generate:frontmatter')
if (!generate)
return

Expand All @@ -109,9 +109,7 @@ export async function generateAutoFrontmatter(app: App) {

await generate.updateCache(app)

if (app.env.isDebug) {
logger.info(`Generate auto frontmatter: ${(performance.now() - start).toFixed(2)}ms`)
}
perfLog('generate:frontmatter', app.env.isDebug)
}

export async function watchAutoFrontmatter(app: App, watchers: any[]) {
Expand Down
4 changes: 2 additions & 2 deletions theme/src/node/config/resolveProvideData.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { App } from 'vuepress'
import type { PlumeThemePluginOptions } from '../../shared/index.js'
import { entries, fromEntries, getLocalePaths, getRootLangPath, isPlainObject } from '@vuepress/helper'
import { entries, fromEntries, getLocalePaths, inferRootLocalePath, isPlainObject } from '@vuepress/helper'
import { PRESET_LOCALES } from '../locales/index.js'

export function resolveProvideData(
app: App,
plugins: PlumeThemePluginOptions,
): Record<string, any> {
const root = getRootLangPath(app)
const root = inferRootLocalePath(app)
const locales = [...getLocalePaths(app), root]
return {
// 注入水印配置
Expand Down
2 changes: 1 addition & 1 deletion theme/src/node/loadConfig/findConfigPath.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { colors } from 'vuepress/utils'
import { logger } from '../utils/index.js'

const CONFIG_FILE_NAME = 'plume.config'
const extensions: string[] = ['ts', 'js', 'mts', 'cts', 'mjs', 'cjs']
const extensions: string[] = ['ts', 'js', 'mjs', 'cjs', 'mts', 'cts']

export async function findConfigPath(app: App, configPath?: string): Promise<string | undefined> {
const cwd = process.cwd()
Expand Down
21 changes: 8 additions & 13 deletions theme/src/node/loadConfig/loader.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { deepMerge } from '@pengzhanbo/utils'
import { watch } from 'chokidar'
import { path } from 'vuepress/utils'
import { resolveLocaleOptions } from '../config/resolveLocaleOptions.js'
import { logger } from '../utils/index.js'
import { perfLog, perfMark } from '../utils/index.js'
import { compiler } from './compiler.js'
import { findConfigPath } from './findConfigPath.js'

Expand Down Expand Up @@ -41,7 +41,7 @@ export async function initConfigLoader(
defaultConfig: ThemeConfig,
{ configFile, onChange }: InitConfigLoaderOptions = {},
) {
const start = performance.now()
perfMark('load-config')
const { encrypt, autoFrontmatter, ...localeOptions } = defaultConfig
loader = {
configFile,
Expand All @@ -58,31 +58,26 @@ export async function initConfigLoader(
},
}

const findStart = performance.now()
perfMark('load-config:find')
loader.configFile = await findConfigPath(app, configFile)
if (app.env.isDebug) {
logger.info(`Find config path: ${(performance.now() - findStart).toFixed(2)}ms`)
}
perfLog('load-config:find', app.env.isDebug)

if (onChange) {
loader.changeEvents.push(onChange)
}

const loadStart = performance.now()
perfMark('load-config:loaded')
const { config, dependencies = [] } = await loader.load()
if (app.env.isDebug) {
logger.info(`theme config call load: ${(performance.now() - loadStart).toFixed(2)}ms`)
}
perfLog('load-config:loaded', app.env.isDebug)

loader.loaded = true
loader.dependencies = [...dependencies]
updateResolvedConfig(app, config)

loader.whenLoaded.forEach(fn => fn(loader!.resolvedConfig))
loader.whenLoaded = []

if (app.env.isDebug) {
logger.info(`Load config: ${(performance.now() - start).toFixed(2)}ms`)
}
perfLog('load-config', app.env.isDebug)
}

export function watchConfigFile(app: App, watchers: any[], onChange: ChangeEvent) {
Expand Down
5 changes: 4 additions & 1 deletion theme/src/node/pages/createPages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,13 @@ import type { App, Page } from 'vuepress/core'
import type { PlumeThemeLocaleOptions } from '../../shared/index.js'
import { getRootLang } from '@vuepress/helper'
import { createPage } from 'vuepress/core'
import { withBase } from '../utils/index.js'
import { perfLog, perfMark, withBase } from '../utils/index.js'

export async function createPages(app: App, localeOption: PlumeThemeLocaleOptions) {
if (localeOption.blog === false)
return

perfMark('create:blog-pages')
const pageList: Promise<Page>[] = []
const locales = localeOption.locales || {}
const rootLang = getRootLang(app)
Expand Down Expand Up @@ -53,4 +54,6 @@ export async function createPages(app: App, localeOption: PlumeThemeLocaleOption
}

app.pages.push(...await Promise.all(pageList))

perfLog('create:blog-pages', app.env.isDebug)
}
4 changes: 2 additions & 2 deletions theme/src/node/plugins/getPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import { watermarkPlugin } from '@vuepress/plugin-watermark'
import { type MarkdownEnhancePluginOptions, mdEnhancePlugin } from 'vuepress-plugin-md-enhance'
import { markdownPowerPlugin } from 'vuepress-plugin-md-power'
import { resolveDocsearchOptions, resolveSearchOptions } from '../config/index.js'
import { deleteAttrs } from '../utils/index.js'
import { omit } from '../utils/index.js'

export interface SetupPluginOptions {
app: App
Expand Down Expand Up @@ -119,7 +119,7 @@ export function getPlugins(
const options: MarkdownEnhancePluginOptions = {
...pluginOptions.markdownEnhance,
}
plugins.push(mdEnhancePlugin(deleteAttrs(options, 'hint', 'alert', 'imgSize', 'imgLazyload', 'imgMark', 'figure', 'obsidianImgSize', 'katex', 'mathjax', 'tabs', 'codetabs', 'align', 'mark', 'sub', 'sup', 'attrs', 'tasklist', 'footnote')))
plugins.push(mdEnhancePlugin(omit(options, 'hint', 'alert', 'imgSize', 'imgLazyload', 'imgMark', 'figure', 'obsidianImgSize', 'katex', 'mathjax', 'tabs', 'codetabs', 'align', 'mark', 'sub', 'sup', 'attrs', 'tasklist', 'footnote')))
}

if (pluginOptions.markdownPower !== false) {
Expand Down
8 changes: 3 additions & 5 deletions theme/src/node/prepare/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { App } from 'vuepress'
import { watch } from 'chokidar'
import { getThemeConfig } from '../loadConfig/index.js'
import { logger } from '../utils/index.js'
import { perfLog, perfMark } from '../utils/index.js'
import { prepareArticleTagColors } from './prepareArticleTagColor.js'
import { preparedBlogData } from './prepareBlogData.js'
import { prepareEncrypt } from './prepareEncrypt.js'
Expand All @@ -11,7 +11,7 @@ import { prepareSidebar } from './prepareSidebar.js'
export async function prepareData(
app: App,
): Promise<void> {
const start = performance.now()
perfMark('prepare:data')
const { localeOptions, encrypt } = getThemeConfig()
await Promise.all([
prepareArticleTagColors(app, localeOptions),
Expand All @@ -21,9 +21,7 @@ export async function prepareData(
prepareIcons(app, localeOptions),
])

if (app.env.isDebug) {
logger.info(`Prepare data: ${(performance.now() - start).toFixed(2)}ms`)
}
perfLog('prepare:data', app.env.isDebug)
}

export function watchPrepare(
Expand Down
11 changes: 3 additions & 8 deletions theme/src/node/prepare/prepareArticleTagColor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { App } from 'vuepress'
import type { PlumeThemeLocaleOptions } from '../../shared/index.js'
import { toArray } from '@pengzhanbo/utils'
import { isPlainObject } from 'vuepress/shared'
import { logger, nanoid, resolveContent, writeTemp } from '../utils/index.js'
import { nanoid, perfLog, perfMark, resolveContent, writeTemp } from '../utils/index.js'

export type TagsColorsItem = readonly [
string, // normal color
Expand Down Expand Up @@ -35,19 +35,14 @@ export const PRESET: TagsColorsItem[] = [
const cache: Record<number, string> = {}

export async function prepareArticleTagColors(app: App, localeOptions: PlumeThemeLocaleOptions): Promise<void> {
const start = performance.now()
perfMark('prepare:tag-colors')
const blog = isPlainObject(localeOptions.blog) ? localeOptions.blog : {}

const { js, css } = genCode(app, blog.tagsTheme ?? 'colored')

await writeTemp(app, 'internal/articleTagColors.css', css)
await writeTemp(app, 'internal/articleTagColors.js', js)

if (app.env.isDebug) {
logger.info(
`Generate article tag colors: ${(performance.now() - start).toFixed(2)}ms`,
)
}
perfLog('prepare:tag-colors', app.env.isDebug)
}

export function genCode(app: App, theme: 'colored' | 'brand' | 'gray'): { js: string, css: string } {
Expand Down
7 changes: 3 additions & 4 deletions theme/src/node/prepare/prepareBlogData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { removeLeadingSlash } from '@vuepress/helper'
import { createFilter } from 'create-filter'
import dayjs from 'dayjs'
import { resolveNotesOptions } from '../config/index.js'
import { logger, normalizePath, resolveContent, writeTemp } from '../utils/index.js'
import { normalizePath, perfLog, perfMark, resolveContent, writeTemp } from '../utils/index.js'
import { isEncryptPage } from './prepareEncrypt.js'

const HEADING_RE = /<h(\d)[^>]*>.*?<\/h\1>/gi
Expand All @@ -32,7 +32,7 @@ export async function preparedBlogData(
return
}

const start = performance.now()
perfMark('prepare:blog-data')

const blog = localeOptions.blog || {}
const notesList = resolveNotesOptions(localeOptions)
Expand Down Expand Up @@ -100,6 +100,5 @@ export async function preparedBlogData(
const content = resolveContent(app, { name: 'blogPostData', content: blogData })
await writeTemp(app, 'internal/blogData.js', content)

if (app.env.isDebug)
logger.info(`prepare blog data time spent: ${(performance.now() - start).toFixed(2)}ms`)
perfLog('prepare:blog-data', app.env.isDebug)
}
8 changes: 3 additions & 5 deletions theme/src/node/prepare/prepareEncrypt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { Page } from 'vuepress/core'
import type { EncryptOptions, PlumeThemePageData } from '../../shared/index.js'
import { isNumber, isString, random, toArray } from '@pengzhanbo/utils'
import { genSaltSync, hashSync } from 'bcrypt-ts'
import { createFsCache, type FsCache, hash, logger, resolveContent, writeTemp } from '../utils/index.js'
import { createFsCache, type FsCache, hash, perfLog, perfMark, resolveContent, writeTemp } from '../utils/index.js'

export type EncryptConfig = readonly [
boolean, // global
Expand All @@ -19,7 +19,7 @@ let contentHash = ''
let fsCache: FsCache<[string, EncryptConfig]> | null = null

export async function prepareEncrypt(app: App, encrypt?: EncryptOptions) {
const start = performance.now()
perfMark('prepare:encrypt')

if (!fsCache && app.env.isDev) {
fsCache = createFsCache(app, 'encrypt')
Expand All @@ -40,9 +40,7 @@ export async function prepareEncrypt(app: App, encrypt?: EncryptOptions) {

fsCache?.write([currentHash, resolvedEncrypt])

if (app.env.isDebug) {
logger.info(`Generate encrypt: ${(performance.now() - start).toFixed(2)}ms`)
}
perfLog('prepare:encrypt', app.env.isDebug)
}

const salt = () => genSaltSync(random(8, 16))
Expand Down
20 changes: 8 additions & 12 deletions theme/src/node/prepare/prepareIcons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { isArray, uniq } from '@pengzhanbo/utils'
import { entries, isLinkAbsolute, isLinkHttp, isPlainObject } from '@vuepress/helper'
import { isPackageExists } from 'local-pkg'
import { fs } from 'vuepress/utils'
import { createFsCache, type FsCache, interopDefault, logger, nanoid, resolveContent, writeTemp } from '../utils/index.js'
import { createFsCache, type FsCache, interopDefault, logger, nanoid, perfLog, perfMark, resolveContent, writeTemp } from '../utils/index.js'

interface IconData {
className: string
Expand Down Expand Up @@ -37,7 +37,7 @@ function isIconify(icon: any): icon is string {
}

export async function prepareIcons(app: App, localeOptions: PlumeThemeLocaleOptions) {
const start = performance.now()
perfMark('prepare:icons:total')
if (!isInstalled) {
await writeTemp(app, JS_FILENAME, resolveContent(app, { name: 'icons', content: '{}' }))
return
Expand All @@ -47,6 +47,7 @@ export async function prepareIcons(app: App, localeOptions: PlumeThemeLocaleOpti
await fsCache.read()
}

perfMark('prepare:pages:icons')
const iconList: string[] = []
app.pages.forEach(page => iconList.push(...getIconsWithPage(page)))
iconList.push(...getIconWithThemeConfig(localeOptions))
Expand All @@ -64,11 +65,9 @@ export async function prepareIcons(app: App, localeOptions: PlumeThemeLocaleOpti
collectMap[collect].push(name)
})

if (app.env.isDebug) {
logger.info(`Generate icons with pages and theme config: ${(performance.now() - start).toFixed(2)}ms`)
}
perfLog('prepare:pages:icons', app.env.isDebug)

const collectStart = performance.now()
perfMark('prepare:icons:imports')

if (!locate) {
const mod = await interopDefault(import('@iconify/json'))
Expand All @@ -83,9 +82,7 @@ export async function prepareIcons(app: App, localeOptions: PlumeThemeLocaleOpti
logger.warn(`[iconify] Unknown icons: ${unknownList.join(', ')}`)
}

if (app.env.isDebug) {
logger.info(`Generate icons with iconify collect: ${(performance.now() - collectStart).toFixed(2)}ms`)
}
perfLog('prepare:icons:imports', app.env.isDebug)

let cssCode = ''
const map: Record<string, string> = {}
Expand All @@ -104,9 +101,8 @@ export async function prepareIcons(app: App, localeOptions: PlumeThemeLocaleOpti
])

fsCache?.write(cache)
if (app.env.isDebug) {
logger.info(`Generate icons total time: ${(performance.now() - start).toFixed(2)}ms`)
}

perfLog('prepare:icons:total', app.env.isDebug)
}

function getIconsWithPage(page: Page): string[] {
Expand Down
Loading

0 comments on commit e7ba562

Please sign in to comment.