Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Internal documentation(Plugin, CLI, ...) part 1 #1221

Merged
merged 3 commits into from
Sep 30, 2024
Merged
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 .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ test.json
.next
docs/.vitepress/cache/**
docs/.vitepress/dist/**
docs/.vitepress/graphs/**
!__snapshots__
kubb-files.json
kubb.log
Expand Down
5 changes: 5 additions & 0 deletions docs/.vitepress/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ import { groupIconMdPlugin, groupIconVitePlugin, localIconLoader } from 'vitepre
import { transformerTwoslash } from '@shikijs/vitepress-twoslash'
import { SitemapStream } from 'sitemap'
import { defineConfig } from 'vitepress'

import { renderMermaidGraphsPlugin } from './mermaid'
import { transposeTables } from './transposeTables.ts'
import { transposeTables } from './transposeTables.ts'

import { version } from '../../packages/core/package.json'
Expand Down Expand Up @@ -36,6 +39,7 @@ const knowledgeBaseSidebar = [
{
text: 'Plugins',
collapsed: false,
link: '/knowledge-base/plugins/',
items: [
{
text: 'Plugin system',
Expand Down Expand Up @@ -658,6 +662,7 @@ export default defineConfig({
},
vite: {
plugins: [
renderMermaidGraphsPlugin(),
groupIconVitePlugin({
customIcon: {
'kubb.config.ts': localIconLoader(import.meta.url, '../public/logo.svg'),
Expand Down
103 changes: 103 additions & 0 deletions docs/.vitepress/mermaid.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { createHash } from 'node:crypto'
import { fileURLToPath } from 'node:url'
import { promisify } from 'node:util'
import { readdir, mkdir, readFile, writeFile } from 'node:fs/promises'
import { run } from '@mermaid-js/mermaid-cli'

import type { Plugin } from 'vite'

async function getFilesInDirectory(directory: URL): Promise<string[]> {
return (await readdir(directory)).filter((file) => file[0] !== '.')
}

const graphsDirectory = new URL('graphs/', import.meta.url)

const mermaidRegExp = /^```mermaid\n([\S\s]*?)\n```/gm
const greaterThanRegExp = /&gt;/g
const svgIdRegExp = /my-svg/g
const styleTagRegExp = /<style>[\S\s]*?<\/style>/gm

export function renderMermaidGraphsPlugin(): Plugin {
const existingGraphFileNamesPromise = mkdir(graphsDirectory, { recursive: true })
.then(() => getFilesInDirectory(graphsDirectory))
.then((files) => new Set(files.filter((name) => name.endsWith('.svg'))))
const existingGraphsByName = new Map<string, Promise<string>>()

async function renderGraph(codeBlock: string, outFile: string, hash: string) {
const existingGraphFileNames = await existingGraphFileNamesPromise
const outFileURL = new URL(outFile, graphsDirectory)
if (!existingGraphFileNames.has(outFile)) {
console.warn(
`Pre-rendered file ${outFile} not found, rendering...\nIf this throws on Vercel, you need to run "npm run build:docs" locally first and commit the updated svg files.`,
)
const inFileURL = new URL(`${outFile}.mmd`, graphsDirectory)
await writeFile(inFileURL, codeBlock)

await run(fileURLToPath(inFileURL), fileURLToPath(outFileURL), {
parseMMDOptions: {
mermaidConfig: {
theme: 'dark',
fontSize: 13,
flowchart: {
padding: 4,
useMaxWidth: true,
},
themeCSS: '* { line-height: 1.5; } span.edgeLabel { padding: 2px 5px; }',
},
},
puppeteerConfig: {
args: ['--no-sandbox'],
},
})
}
const outFileContent = await readFile(outFileURL, 'utf8')
// Styles need to be placed top-level, so we extract them and then
// prepend them, separated with a line-break
const extractedStyles: string[] = []
let hasReplacedId = false
const replacementId = `mermaid-${hash}`
const baseGraph = outFileContent
// We need to replace some HTML entities
.replace(greaterThanRegExp, '>')
// First, we replace the default id with a unique, hash-based one
.replace(svgIdRegExp, () => {
hasReplacedId = true
return replacementId
})
.replace(styleTagRegExp, (styleTag) => {
extractedStyles.push(styleTag)
return ''
})
if (!hasReplacedId) {
throw new Error('Could not find expected id "my-svg"')
}
console.log('Extracted styles from mermaid chart:', extractedStyles.length)
return `${extractedStyles.join('')}\n${baseGraph}`
}

return {
enforce: 'pre',
name: 'render-mermaid-charts',
async transform(code, id) {
if (id.endsWith('.md')) {
const renderedGraphs: string[] = []
const mermaidCodeBlocks: string[] = []
let match: RegExpExecArray | null = null
while ((match = mermaidRegExp.exec(code)) !== null) {
mermaidCodeBlocks.push(match[1])
}
await Promise.all(
mermaidCodeBlocks.map(async (codeBlock, index) => {
const hash = createHash('sha256').update(codeBlock).digest('hex').slice(0, 8)
const outFile = `mermaid-${hash}.svg`
if (!existingGraphsByName.has(outFile)) {
existingGraphsByName.set(outFile, renderGraph(codeBlock, outFile, hash))
}
renderedGraphs[index] = await existingGraphsByName.get(outFile)!
}),
)
return code.replace(mermaidRegExp, () => renderedGraphs.shift()!)
}
},
}
}
35 changes: 34 additions & 1 deletion docs/.vitepress/theme/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
--vp-c-brand-lighter: var(--vp-c-brand);
--vp-c-brand-lightest: var(--vp-c-brand);
--vp-c-brand-dark: #854811;
--vp-c-brand-darker: #854811;
--vp-c-brand-darker: var(--vp-c-brand-dark);
--vp-c-brand-dimm: rgba(100, 108, 255, 0.08);
--vp-c-brand-1: var(--vp-c-brand);
--vp-c-brand-2: #f3c796;
Expand Down Expand Up @@ -233,6 +233,39 @@
.dark #VPSidebarNav > .group:nth-child(-n + 9):not(:first-child) > .VPSidebarItem > .item > .text::before {
filter: invert(1);
}

svg[id^='mermaid-'] {
line-height: 1.5;
background-color: transparent !important;
}

svg[id^='mermaid-'] .edgeLabel {
padding: 0 !important;
}

svg[id^='mermaid-'] .cluster rect {
fill: rgba(185, 185, 185, 0.14) !important;
stroke: rgba(185, 185, 185, 0.54) !important;
}

.dark svg[id^='mermaid-'] .flowchart-link {
stroke: lightgrey !important;
}

.dark svg[id^='mermaid-'] .marker {
stroke: lightgrey !important;
fill: lightgrey !important;
}

.dark svg[id^='mermaid-'] .edgeLabel p {
background-color: #585858 !important;
}

.dark svg[id^='mermaid-'] span {
color: #ccc !important;
}


/*#VPSidebarNav > .group > .VPSidebarItem > .item > .text {*/
/* display: flex;*/
/* align-items: center;*/
Expand Down
3 changes: 3 additions & 0 deletions docs/blog/v3.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ output: {
```
- Refactor of grouping(use of name instead of output) and output based on `output` of the current plugin

[//]: # (- [`@kubb/plugin-ts`] Removal of `enumType` in favor of `enum.type`)

[//]: # (- [`@kubb/plugin-ts`] Removal of `enumSuffix` in favor of `enum.suffix`)

## Thanks

Expand Down
2 changes: 1 addition & 1 deletion docs/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default defineConfig({
output: {
path: './clients/axios',
},
group: { type: 'tag', output: './clients/axios/{{tag}}Service' }, // [!code --]
// group: { type: 'tag', output: './clients/axios/{{tag}}Service' }, // [!code --]
group: { type: 'tag', name: ({ group }) => `${group}Service` }, // [!code ++]
}),
],
Expand Down
39 changes: 0 additions & 39 deletions docs/comparison.md

This file was deleted.

40 changes: 33 additions & 7 deletions docs/getting-started/configure.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,14 +242,40 @@ export default defineConfig({
})
```

#### output.exportType
#### output.extension
Override the extension to the generated imports and exports, by default the plugin will add an extension.

| | |
|----------:|:-------------------------|
| Type: | `Record<KubbFile.Extname, KubbFile.Extname>` |
| Required: | `false` |
| Default: | `{ '.ts': '.ts'}` |


```typescript [kubb.config.ts]
import { defineConfig } from '@kubb/core'

export default defineConfig({
input: {
path: './petStore.yaml',
},
output: {
path: './src/gen',
extension: {
'.ts': '.js',
},
},
})
```

#### output.barrelType
Define what needs to exported, here you can also disable the export of barrel files.

| | |
|----------:|:-------------------------------------|
| Type: | `'barrel' \| 'barrelNamed' \| false` |
| Required: | `false` |
| Default: | `'barrelNamed'` |
| | |
|----------:|:----------------------------|
| Type: | `'all' \| 'named' \| false` |
| Required: | `false` |
| Default: | `'named'` |


```typescript [kubb.config.ts]
Expand All @@ -262,7 +288,7 @@ export default defineConfig({
output: {
path: './src/gen',
clean: true,
exportType: 'barrel',
barrelType: 'all',
},
})
```
Expand Down
Loading
Loading